dns-lookup-1.0.8/.cargo_vcs_info.json0000644000000001120000000000000131260ustar { "git": { "sha1": "581e8cab9611a57dda9068dc8c7083444c6a20ae" } } dns-lookup-1.0.8/Cargo.toml0000644000000025340000000000000111360ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "dns-lookup" version = "1.0.8" authors = ["Josh Driver "] include = ["src/**", "README.md", "LICENSE*", "Cargo.*"] description = "A simple dns resolving api, much like rust's unstable api. Also includes getaddrinfo and getnameinfo wrappers for libc variants." documentation = "https://docs.rs/dns-lookup" readme = "README.md" keywords = ["dns", "resolve", "lookup", "getaddrinfo", "getnameinfo"] license = "MIT/Apache-2.0" repository = "https://github.com/keeperofdakeys/dns-lookup/" [dependencies.cfg-if] version = "^1.0" [dependencies.clippy] version = "^0" optional = true [dependencies.socket2] version = "^0.4" [target."cfg(unix)".dependencies.libc] version = "^0.2" [target."cfg(windows)".dependencies.winapi] version = "^0.3" features = ["windef", "ws2def", "ws2tcpip"] default-features = false dns-lookup-1.0.8/Cargo.toml.orig000064400000000000000000000014610000000000000145730ustar 00000000000000[package] name = "dns-lookup" version = "1.0.8" authors = ["Josh Driver "] description = "A simple dns resolving api, much like rust's unstable api. Also includes getaddrinfo and getnameinfo wrappers for libc variants." documentation = "https://docs.rs/dns-lookup" repository = "https://github.com/keeperofdakeys/dns-lookup/" readme = "README.md" keywords = ["dns", "resolve", "lookup", "getaddrinfo", "getnameinfo"] license = "MIT/Apache-2.0" include = [ "src/**", "README.md", "LICENSE*", "Cargo.*" ] [dependencies] socket2 = "^0.4" clippy = {version = "^0", optional = true} cfg-if = "^1.0" [target."cfg(windows)".dependencies.winapi] version = "^0.3" default-features = false features = ["windef", "ws2def", "ws2tcpip"] [target."cfg(unix)".dependencies] libc = "^0.2" dns-lookup-1.0.8/LICENSE-APACHE000064400000000000000000000251360000000000000136350ustar 00000000000000 Apache License Version 2.0, January 2004 http://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 http://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. dns-lookup-1.0.8/LICENSE-MIT000064400000000000000000000023670000000000000133460ustar 00000000000000Copyright for portions of the project dns-lookup are held by The Rust Project Developers as part of The Rust Project. All other copyright for project dns-lookup are held by keeperofdakeys. The MIT License (MIT) Copyright (c) 2016 keeperofdakeys 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. dns-lookup-1.0.8/README.md000064400000000000000000000040210000000000000131560ustar 00000000000000# dns-lookup [![Crates.io](https://img.shields.io/crates/v/dns-lookup.svg?maxAge=2592000)](https://crates.io/crates/dns-lookup) A small wrapper for libc to perform simple DNS lookups. You can use the `lookup_host` function to get a list of IP Addresses for a given hostname, and the `lookup_name` function to get the reverse dns entry for the given IP Address. PS: If you only need a single result, consider [ToSocketAddrs](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html) in libstd. The library also includes a safe wrapper for `getaddrinfo` and `getnameinfo`. [Documentation](https://docs.rs/dns-lookup/) ## Usage ### Simple API ```rust use dns_lookup::{lookup_host, lookup_addr}; { let hostname = "localhost"; let ips: Vec = lookup_host(hostname).unwrap(); assert!(ips.contains(&"127.0.0.1".parse().unwrap())); } { let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap(); let host = lookup_addr(&ip).unwrap(); // The string "localhost" on unix, and the hostname on Windows. } ``` ### libc API ```rust { extern crate dns_lookup; use dns_lookup::{getaddrinfo, AddrInfoHints, SockType}; fn main() { let hostname = "localhost"; let service = "ssh"; let hints = AddrInfoHints { socktype: SockType::Stream.into(), .. AddrInfoHints::default() }; let sockets = getaddrinfo(Some(hostname), Some(service), Some(hints)) .unwrap().collect::>>().unwrap(); for socket in sockets { // Try connecting to socket println!("{:?}", socket); } } } { use dns_lookup::getnameinfo; use std::net::{IpAddr, SocketAddr}; let ip: IpAddr = "127.0.0.1".parse().unwrap(); let port = 22; let socket: SocketAddr = (ip, port).into(); let (name, service) = match getnameinfo(&socket, 0) { Ok((n, s)) => (n, s), Err(e) => panic!("Failed to lookup socket {:?}", e), }; println!("{:?} {:?}", name, service); let _ = (name, service); } { use dns_lookup::gethostname; let hostname = gethostname().unwrap(); } ``` dns-lookup-1.0.8/src/addrinfo.rs000064400000000000000000000140230000000000000146250ustar 00000000000000use socket2::SockAddr; use std::ffi::{CStr, CString}; use std::io; use std::mem; use std::net::SocketAddr; use std::ptr; #[cfg(unix)] use libc::{getaddrinfo as c_getaddrinfo, freeaddrinfo as c_freeaddrinfo, addrinfo as c_addrinfo}; #[cfg(windows)] use winapi::shared::ws2def::{ADDRINFOA as c_addrinfo}; #[cfg(windows)] use winapi::um::ws2tcpip::{getaddrinfo as c_getaddrinfo, freeaddrinfo as c_freeaddrinfo}; use err::LookupError; /// A struct used as the hints argument to getaddrinfo. #[derive(Copy, Clone, Debug, PartialEq)] pub struct AddrInfoHints { /// Type of this socket. 0 for none. /// /// Values are defined by the libc on your system. pub socktype: i32, /// Protcol for this socket. 0 for none. /// /// Values are defined by the libc on your system. pub protocol: i32, /// Address family for this socket. 0 for none. /// /// Values are defined by the libc on your system. pub address: i32, /// Optional bitmask arguments. Bitwise OR bitflags to change the /// behaviour of getaddrinfo. 0 for none. /// /// Values are defined by the libc on your system. pub flags: i32, } impl AddrInfoHints { unsafe fn as_addrinfo(&self) -> c_addrinfo { let mut addrinfo: c_addrinfo = mem::zeroed(); addrinfo.ai_socktype = self.socktype; addrinfo.ai_protocol = self.protocol; addrinfo.ai_family = self.address; addrinfo.ai_flags = self.flags; addrinfo } } impl Default for AddrInfoHints { /// Generate a blank AddrInfoHints struct, so new values can easily /// be specified. fn default() -> Self { AddrInfoHints { socktype: 0, protocol: 0, address: 0, flags: 0, } } } /// Struct that stores socket information, as returned by getaddrinfo. /// /// This maps to the same definition provided by libc backends. #[derive(Clone, Debug, PartialEq)] pub struct AddrInfo { /// Type of this socket. /// /// Values are defined by the libc on your system. pub socktype: i32, /// Protcol family for this socket. /// /// Values are defined by the libc on your system. pub protocol: i32, /// Address family for this socket (usually matches protocol family). /// /// Values are defined by the libc on your system. pub address: i32, /// Socket address for this socket, usually containing an actual /// IP Address and port. pub sockaddr: SocketAddr, /// If requested, this is the canonical name for this socket/host. pub canonname: Option, /// Optional bitmask arguments, usually set to zero. pub flags: i32, } impl AddrInfo { /// Copy the informataion from the given addrinfo pointer, and /// create a new AddrInfo struct with that information. /// /// Used for interfacing with getaddrinfo. unsafe fn from_ptr(a: *mut c_addrinfo) -> io::Result { if a.is_null() { return Err( io::Error::new(io::ErrorKind::Other, "Supplied pointer is null." ))?; } let addrinfo = *a; let ((), sockaddr) = SockAddr::init(|storage, len| { *len = addrinfo.ai_addrlen as _; std::ptr::copy_nonoverlapping( addrinfo.ai_addr as *const u8, storage as *mut u8, addrinfo.ai_addrlen as usize ); Ok(()) })?; let sock = sockaddr.as_socket().ok_or_else(|| io::Error::new( io::ErrorKind::Other, format!("Found unknown address family: {}", sockaddr.family()) ))?; Ok(AddrInfo { socktype: addrinfo.ai_socktype, protocol: addrinfo.ai_protocol, address: addrinfo.ai_family, sockaddr: sock, canonname: addrinfo.ai_canonname.as_ref().map(|s| CStr::from_ptr(s).to_str().unwrap().to_owned() ), flags: 0, }) } } /// An iterator of `AddrInfo` structs, wrapping a linked-list /// returned by getaddrinfo. /// /// It's recommended to use `.collect>()` on this /// to collapse possible errors. pub struct AddrInfoIter { orig: *mut c_addrinfo, cur: *mut c_addrinfo, } impl Iterator for AddrInfoIter { type Item = io::Result; fn next(&mut self) -> Option { unsafe { if self.cur.is_null() { return None; } let ret = AddrInfo::from_ptr(self.cur); self.cur = (*self.cur).ai_next as *mut c_addrinfo; Some(ret) } } } unsafe impl Sync for AddrInfoIter {} unsafe impl Send for AddrInfoIter {} impl Drop for AddrInfoIter { fn drop(&mut self) { unsafe { c_freeaddrinfo(self.orig) } } } /// Retrieve socket information for a host, service, or both. Acts as a thin /// wrapper around the libc getaddrinfo. /// /// The only portable way to support International Domain Names (UTF8 DNS /// names) is to manually convert to puny code before calling this function - /// which can be done using the `idna` crate. However some libc backends may /// support this natively, or by using bitflags in the hints argument. /// /// Resolving names from non-UTF8 locales is currently not supported (as the /// interface uses &str). Raise an issue if this is a concern for you. pub fn getaddrinfo(host: Option<&str>, service: Option<&str>, hints: Option) -> Result { // We must have at least host or service. if host.is_none() && service.is_none() { return Err(io::Error::new( io::ErrorKind::Other, "Either host or service must be supplied" ))?; } // Allocate CStrings, and keep around to free. let host = match host { Some(host_str) => Some(CString::new(host_str)?), None => None }; let c_host = host.as_ref().map_or(ptr::null(), |s| s.as_ptr()); let service = match service { Some(service_str) => Some(CString::new(service_str)?), None => None }; let c_service = service.as_ref().map_or(ptr::null(), |s| s.as_ptr()); let c_hints = unsafe { match hints { Some(hints) => hints.as_addrinfo(), None => mem::zeroed(), } }; let mut res = ptr::null_mut(); // Prime windows. #[cfg(windows)] ::win::init_winsock(); unsafe { LookupError::match_gai_error( c_getaddrinfo(c_host, c_service, &c_hints, &mut res) )?; } Ok(AddrInfoIter { orig: res, cur: res }) } dns-lookup-1.0.8/src/err.rs000064400000000000000000000147670000000000000136460ustar 00000000000000use std::ffi; use std::io; #[cfg(unix)] use std::str; /// Struct that stores a lookup error from `getaddrinfo` /// or `getnameinfo`. Can automatically be coerced to an io::Error using `?`. #[derive(Debug)] pub struct LookupError { kind: LookupErrorKind, err_num: i32, inner: io::Error, } impl LookupError { /// Match a `gai` error, returning Ok() if it's /// `0`. Otherwise return Err(LookupError) with /// the specific error details. pub fn match_gai_error(err: i32) -> Result<(), Self> { match err { 0 => Ok(()), _ => Err(LookupError::new(err)), } } /// Create a new LookupError from a `gai` error, /// returned by `getaddrinfo` and `getnameinfo`. pub fn new(err: i32) -> Self { LookupError { kind: LookupErrorKind::new(err), err_num: err, inner: gai_err_to_io_err(err), } } /// Get the error kind explicitly. If this is an /// io::Error, use From/Into to convert it. pub fn kind(&self) -> LookupErrorKind { self.kind } /// Get the actual error number. This can be used /// to find non-standard return codes from some /// implementations (be careful of portability here). pub fn error_num(&self) -> i32 { self.err_num } } /// Different kinds of lookup errors that `getaddrinfo` and /// `getnameinfo` can return. These can be a little inconsitant /// between platforms, so it's recommended not to rely on them. #[derive(Copy, Clone, Debug)] pub enum LookupErrorKind { /// Temporary failure in name resolution. /// /// May also be returend when DNS server returns a SERVFAIL. Again, /// Invalid value for `ai_flags' field. Badflags, /// NAME or SERVICE is unknown. /// /// May also be returned when domain doesn't exist (NXDOMAIN) or domain /// exists but contains no address records (NODATA). NoName, /// The specified network host exists, but has no data defined. /// /// This is no longer a POSIX standard, however it's still returned by /// some platforms. Be warned that FreeBSD does not include the corresponding /// `EAI_NODATA` symbol. NoData, /// Non-recoverable failure in name resolution. Fail, /// `ai_family' not supported. Family, /// `ai_socktype' not supported. Socktype, /// SERVICE not supported for `ai_socktype'. Service, /// Memory allocation failure. Memory, /// System error returned in `errno'. System, /// An unknown result code was returned. /// /// For some platforms, you may wish to match on an unknown value directly. /// Note that `gai_strerr` is used to get error messages, so the generated IO /// error should contain the correct error message for the platform. Unknown, /// A generic C error or IO error occured. /// /// You should convert this `LookupError` into an IO error directly. Note /// that the error code is set to 0 in the case this is returned. IO, } impl LookupErrorKind { #[cfg(all(not(windows), not(unix)))] /// Create a `LookupErrorKind` from a `gai` error. pub fn new(err: i32) -> Self { LookupErrorKind::IO } #[cfg(unix)] /// Create a `LookupErrorKind` from a `gai` error. pub fn new(err: i32) -> Self { use libc as c; match err { c::EAI_AGAIN => LookupErrorKind::Again, c::EAI_BADFLAGS => LookupErrorKind::Badflags, c::EAI_FAIL => LookupErrorKind::Fail, c::EAI_FAMILY => LookupErrorKind::Family, c::EAI_MEMORY => LookupErrorKind::Memory, c::EAI_NONAME => LookupErrorKind::NoName, // FreeBSD has no EAI_NODATA, so don't match it on that platform. #[cfg(not(any(target_os="freebsd", target_os="emscripten")))] c::EAI_NODATA => LookupErrorKind::NoData, c::EAI_SERVICE => LookupErrorKind::Service, c::EAI_SOCKTYPE => LookupErrorKind::Socktype, c::EAI_SYSTEM => LookupErrorKind::System, _ => LookupErrorKind::IO, } } #[cfg(windows)] /// Create a `LookupErrorKind` from a `gai` error. pub fn new(err: i32) -> Self { use winapi::shared::winerror as e; match err as u32 { e::WSATRY_AGAIN => LookupErrorKind::Again, e::WSAEINVAL => LookupErrorKind::Badflags, e::WSANO_RECOVERY => LookupErrorKind::Fail, e::WSAEAFNOSUPPORT => LookupErrorKind::Family, e::ERROR_NOT_ENOUGH_MEMORY => LookupErrorKind::Memory, e::WSAHOST_NOT_FOUND => LookupErrorKind::NoName, e::WSANO_DATA => LookupErrorKind::NoData, e::WSATYPE_NOT_FOUND => LookupErrorKind::Service, e::WSAESOCKTNOSUPPORT => LookupErrorKind::Socktype, _ => LookupErrorKind::IO, } } } impl From for io::Error { fn from(err: LookupError) -> io::Error { err.inner } } impl From for LookupError { fn from(err: io::Error) -> LookupError { LookupError { kind: LookupErrorKind::IO, err_num: 0, inner: err, } } } impl From for LookupError { fn from(err: ffi::NulError) -> LookupError { let err: io::Error = err.into(); err.into() } } #[cfg(all(not(windows), not(unix)))] /// Given a gai error, return an `std::io::Error` with /// the appropriate error message. Note `0` is not an /// error, but will still map to an error pub(crate) fn gai_err_to_io_err(err: i32) -> io::Error { match (err) { 0 => io::Error::new( io::ErrorKind::Other, "address information lookup success" ), _ => io::Error::new( io::ErrorKind::Other, "failed to lookup address information" ), } } #[cfg(unix)] /// Given a gai error, return an `std::io::Error` with /// the appropriate error message. Note `0` is not an /// error, but will still map to an error pub(crate) fn gai_err_to_io_err(err: i32) -> io::Error { use libc::{EAI_SYSTEM, gai_strerror}; match err { 0 => return io::Error::new( io::ErrorKind::Other, "address information lookup success" ), EAI_SYSTEM => return io::Error::last_os_error(), _ => {}, } let detail = unsafe { str::from_utf8(ffi::CStr::from_ptr(gai_strerror(err)).to_bytes()).unwrap() .to_owned() }; io::Error::new(io::ErrorKind::Other, &format!("failed to lookup address information: {}", detail)[..] ) } #[cfg(windows)] /// Given a gai error, return an `std::io::Error` with /// the appropriate error message. Note `0` is not an /// error, but will still map to an error pub(crate) fn gai_err_to_io_err(err: i32) -> io::Error { use winapi::um::winsock2::WSAGetLastError; match err { 0 => io::Error::new( io::ErrorKind::Other, "address information lookup success" ), _ => { io::Error::from_raw_os_error( unsafe { WSAGetLastError() } ) } } } dns-lookup-1.0.8/src/hostname.rs000064400000000000000000000017460000000000000146650ustar 00000000000000use std::ffi::CStr; use std::io; use std::str; #[cfg(unix)] use libc::{gethostname as c_gethostname, c_char}; #[cfg(windows)] use winapi::ctypes::c_char; #[cfg(windows)] use winapi::um::winsock2::gethostname as c_gethostname; /// Fetch the local hostname. pub fn get_hostname() -> Result { // Prime windows. #[cfg(windows)] ::win::init_winsock(); let mut c_name = [0 as c_char; 256 as usize]; let res = unsafe { c_gethostname(c_name.as_mut_ptr(), c_name.len() as _) }; // If an error occured, check errno for error message. if res != 0 { return Err(io::Error::last_os_error()); } let hostname = unsafe { CStr::from_ptr(c_name.as_ptr()) }; str::from_utf8(hostname.to_bytes()) .map(|h| h.to_owned()) .map_err(|_| io::Error::new(io::ErrorKind::Other, "Non-UTF8 hostname")) } #[test] fn test_get_hostname() { // We don't know the hostname of the local box, so just verify it doesn't return an error. get_hostname().unwrap(); } dns-lookup-1.0.8/src/lib.rs000064400000000000000000000051400000000000000136050ustar 00000000000000//! # `dns_lookup` //! A small wrapper for libc to perform simple DNS lookups. //! //! Two main functions are provided. //! //! PS: If you only need a single result, consider [ToSocketAddrs](https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html) in libstd. //! //! //! # `lookup_host` //! Given a hostname, return an Iterator the IP Addresses associated with //! it. //! //! ```rust //! use dns_lookup::lookup_host; //! //! let hostname = "localhost"; //! let ips: Vec = lookup_host(hostname).unwrap(); //! assert!(ips.contains(&"127.0.0.1".parse().unwrap())); //! ``` //! //! # `lookup_addr` //! Given an IP Address, return the reverse DNS entry (hostname) for the //! given IP Address. //! //! //! ```rust //! use dns_lookup::lookup_addr; //! //! let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap(); //! let host = lookup_addr(&ip).unwrap(); //! //! // The string "localhost" on unix, and the hostname on Windows. //! ``` //! //! # `getaddrinfo` //! ```rust //! extern crate dns_lookup; //! //! use dns_lookup::{getaddrinfo, AddrInfoHints, SockType}; //! //! fn main() { //! let hostname = "localhost"; //! let service = "ssh"; //! let hints = AddrInfoHints { //! socktype: SockType::Stream.into(), //! .. AddrInfoHints::default() //! }; //! let sockets = //! getaddrinfo(Some(hostname), Some(service), Some(hints)) //! .unwrap().collect::>>().unwrap(); //! //! for socket in sockets { //! // Try connecting to socket //! let _ = socket; //! } //! } //! ``` //! //! # `getnameinfo` //! ```rust //! use dns_lookup::getnameinfo; //! use std::net::{IpAddr, SocketAddr}; //! //! let ip: IpAddr = "127.0.0.1".parse().unwrap(); //! let port = 22; //! let socket: SocketAddr = (ip, port).into(); //! //! let (name, service) = match getnameinfo(&socket, 0) { //! Ok((n, s)) => (n, s), //! Err(e) => panic!("Failed to lookup socket {:?}", e), //! }; //! //! println!("{:?} {:?}", name, service); //! let _ = (name, service); //! ``` #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #[cfg(unix)] extern crate libc; #[cfg(windows)] extern crate winapi; extern crate socket2; mod addrinfo; mod nameinfo; mod err; mod lookup; mod types; mod hostname; #[cfg(windows)] mod win; pub use addrinfo::{getaddrinfo, AddrInfoIter, AddrInfo, AddrInfoHints}; pub use hostname::get_hostname; pub use lookup::{lookup_host, lookup_addr}; pub use nameinfo::getnameinfo; pub use types::{SockType, Protocol, AddrFamily}; pub use err::{LookupErrorKind, LookupError}; dns-lookup-1.0.8/src/lookup.rs000064400000000000000000000043730000000000000143570ustar 00000000000000use std::io; use std::net::IpAddr; use std::str; #[cfg(unix)] use libc::{NI_NUMERICSERV, SOCK_STREAM}; #[cfg(windows)] use winapi::shared::ws2def::{NI_NUMERICSERV, SOCK_STREAM}; use addrinfo::{getaddrinfo, AddrInfoHints}; use nameinfo::getnameinfo; /// Lookup the address for a given hostname via DNS. /// /// Returns an iterator of IP Addresses, or an `io::Error` on failure. pub fn lookup_host(host: &str) -> io::Result> { let hints = AddrInfoHints { socktype: SOCK_STREAM, ..AddrInfoHints::default() }; match getaddrinfo(Some(host), None, Some(hints)) { Ok(addrs) => { let addrs: io::Result> = addrs.map(|r| r.map(|a| a.sockaddr.ip())).collect(); addrs }, Err(e) => { reload_dns_nameserver(); Err(e)? }, } } /// Lookup the hostname of a given IP Address via DNS. /// /// Returns the hostname as a String, or an `io::Error` on failure. pub fn lookup_addr(addr: &IpAddr) -> io::Result { let sock = (*addr, 0).into(); match getnameinfo(&sock, NI_NUMERICSERV) { Ok((name, _)) => Ok(name), Err(e) => { reload_dns_nameserver(); Err(e)? }, } } // The lookup failure could be caused by using a stale /etc/resolv.conf. // See https://github.com/rust-lang/rust/issues/41570. // We therefore force a reload of the nameserver information. // MacOS and IOS don't seem to have this problem. fn reload_dns_nameserver() { cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { } else if #[cfg(target_os = "ios")] { } else if #[cfg(unix)] { use libc; unsafe { libc::res_init(); } } } } #[test] fn test_localhost() { let ips = lookup_host("localhost").unwrap(); assert!(ips.contains(&IpAddr::V4("127.0.0.1".parse().unwrap()))); assert!(!ips.contains(&IpAddr::V4("10.0.0.1".parse().unwrap()))); } #[cfg(unix)] #[test] fn test_rev_localhost() { let name = lookup_addr(&IpAddr::V4("127.0.0.1".parse().unwrap())); assert_eq!(name.unwrap(), "localhost"); } #[cfg(windows)] #[test] fn test_hostname() { // Get machine's hostname. let hostname = ::hostname::get_hostname().unwrap(); // Do reverse lookup of 127.0.0.1. let rev_name = lookup_addr(&IpAddr::V4("127.0.0.1".parse().unwrap())); assert_eq!(rev_name.unwrap(), hostname); } dns-lookup-1.0.8/src/nameinfo.rs000064400000000000000000000052600000000000000146360ustar 00000000000000use socket2::SockAddr; use std::ffi::CStr; use std::io; use std::net::SocketAddr; use std::str; #[cfg(unix)] use libc::{c_char, getnameinfo as c_getnameinfo}; #[cfg(windows)] use winapi::ctypes::c_char; #[cfg(windows)] use winapi::um::ws2tcpip::getnameinfo as c_getnameinfo; use err::LookupError; /// Retrieve the name for a given IP and Service. Acts as a thin wrapper around /// the libc getnameinfo. /// /// Returned names may be encoded in puny code for Interational Domain Names /// (UTF8 DNS names). You can use the `idna` crate to decode these to their /// actual UTF8 representation. /// /// Retrieving names or services that contain non-UTF8 locales is currently not /// supported (as String is returned). Raise an issue if this is a concern for /// you. pub fn getnameinfo(sock: &SocketAddr, flags: i32) -> Result<(String, String), LookupError> { // Convert the socket into our type, so we can get a sockaddr_in{,6} ptr. let sock: SockAddr = (*sock).into(); let c_sock = sock.as_ptr(); let c_sock_len = sock.len(); // Hard code maximums, as they aren't defined in libc/winapi. // Allocate buffers for name and service strings. let mut c_host = [0 as c_char; 1024 as usize]; // No NI_MAXSERV, so use suggested value. let mut c_service = [0 as c_char; 32 as usize]; // Prime windows. #[cfg(windows)] ::win::init_winsock(); unsafe { LookupError::match_gai_error( c_getnameinfo( c_sock, c_sock_len, c_host.as_mut_ptr(), c_host.len() as _, c_service.as_mut_ptr(), c_service.len() as _, flags ) )?; } let host = unsafe { CStr::from_ptr(c_host.as_ptr()) }; let service = unsafe { CStr::from_ptr(c_service.as_ptr()) }; let host = match str::from_utf8(host.to_bytes()) { Ok(name) => Ok(name.to_owned()), Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Host UTF8 parsing failed")) }?; let service = match str::from_utf8(service.to_bytes()) { Ok(service) => Ok(service.to_owned()), Err(_) => Err(io::Error::new(io::ErrorKind::Other, "Service UTF8 parsing failed")) }?; Ok((host, service)) } #[test] fn test_getnameinfo() { use std::net::{IpAddr, SocketAddr}; let ip: IpAddr = "127.0.0.1".parse().unwrap(); let port = 22; let socket: SocketAddr = (ip, port).into(); let (name, service) = match getnameinfo(&socket, 0) { Ok((n, s)) => (n, s), Err(e) => panic!("Failed to lookup socket {:?}", e), }; assert_eq!(service, "ssh"); #[cfg(unix)] { assert_eq!(name, "localhost"); } #[cfg(windows)] { let hostname = ::hostname::get_hostname().unwrap(); assert_eq!(name, hostname); } } dns-lookup-1.0.8/src/types.rs000064400000000000000000000062020000000000000142030ustar 00000000000000#[cfg(unix)] use libc::c_int; #[cfg(unix)] use libc as c; #[cfg(windows)] use winapi::ctypes::c_int; #[cfg(windows)] use winapi::shared::ws2def as c; /// Socket Type /// /// Cross platform enum of common Socket Types. For missing types use /// the `libc` and `winapi` crates, depending on platform. #[derive(Copy, Clone, Debug, PartialEq)] pub enum SockType { /// Sequenced, reliable, connection-based byte streams. Stream, /// Connectionless, unreliable datagrams of fixed max length. DGram, /// Raw protocol interface. #[cfg(not(target_os = "redox"))] Raw, /// Reliably-delivered messages. #[cfg(not(target_os = "redox"))] RDM, } impl From for c_int { fn from(sock: SockType) -> c_int { match sock { SockType::Stream => c::SOCK_STREAM, SockType::DGram => c::SOCK_DGRAM, #[cfg(not(target_os = "redox"))] SockType::Raw => c::SOCK_RAW, #[cfg(not(target_os = "redox"))] SockType::RDM => c::SOCK_RDM, } } } impl PartialEq for SockType { fn eq(&self, other: &c_int) -> bool { let int: c_int = (*self).into(); *other == int } } impl PartialEq for c_int { fn eq(&self, other: &SockType) -> bool { let int: c_int = (*other).into(); *self == int } } /// Socket Protocol /// /// Cross platform enum of common Socket Protocols. For missing types use /// the `libc` and `winapi` crates, depending on platform. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Protocol { /// Internet Control Message Protocol. ICMP, /// Transmission Control Protocol. TCP, /// User Datagram Protocol. UDP, } impl From for c_int { #[cfg(unix)] fn from(sock: Protocol) -> c_int { match sock { Protocol::ICMP => c::IPPROTO_ICMP, Protocol::TCP => c::IPPROTO_TCP, Protocol::UDP => c::IPPROTO_UDP, } } #[cfg(windows)] fn from(sock: Protocol) -> c_int { match sock { Protocol::ICMP => c::IPPROTO_ICMP as c_int, Protocol::TCP => c::IPPROTO_TCP as c_int, Protocol::UDP => c::IPPROTO_UDP as c_int, } } } impl PartialEq for Protocol { fn eq(&self, other: &c_int) -> bool { let int: c_int = (*self).into(); *other == int } } impl PartialEq for c_int { fn eq(&self, other: &Protocol) -> bool { let int: c_int = (*other).into(); *self == int } } /// Address Family /// /// Cross platform enum of common Address Families. For missing types use /// the `libc` and `winapi` crates, depending on platform. #[derive(Copy, Clone, Debug, PartialEq)] pub enum AddrFamily { /// Local to host (pipes and file-domain) Unix, /// IP protocol family. Inet, /// IP version 6. Inet6 } impl From for c_int { fn from(sock: AddrFamily) -> c_int { match sock { AddrFamily::Unix => c::AF_UNIX, AddrFamily::Inet => c::AF_INET, AddrFamily::Inet6 => c::AF_INET6, } } } impl PartialEq for AddrFamily { fn eq(&self, other: &c_int) -> bool { let int: c_int = (*self).into(); *other == int } } impl PartialEq for c_int { fn eq(&self, other: &AddrFamily) -> bool { let int: c_int = (*other).into(); *self == int } } dns-lookup-1.0.8/src/win.rs000064400000000000000000000007420000000000000136370ustar 00000000000000use std::net::UdpSocket; use std::sync::{Once, ONCE_INIT}; // Start windows socket library - From socket2-rs pub(crate) fn init_winsock() { static INIT: Once = ONCE_INIT; INIT.call_once(|| { // Initialize winsock through the standard library by just creating a // dummy socket. Whether this is successful or not we drop the result as // libstd will be sure to have initialized winsock. let _ = UdpSocket::bind("127.0.0.1:34254"); }); }