├── .gitignore ├── .travis.yml ├── Cargo.toml ├── README.md ├── examples ├── host_table.rs ├── lookup_addr.rs ├── lookup_host.rs ├── lookup_srv.rs ├── resolver.rs └── lookup_txt.rs ├── src ├── lib.rs ├── hostname.rs ├── config.rs ├── idna.rs ├── address.rs ├── socket.rs ├── hosts.rs ├── resolv_conf.rs ├── record.rs ├── resolver.rs └── message.rs ├── LICENSE-MIT └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | sudo: false 4 | 5 | notifications: 6 | email: false 7 | 8 | branches: 9 | only: master 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "resolve" 4 | description = "DNS communication protocol" 5 | 6 | documentation = "https://docs.rs/resolve/" 7 | homepage = "https://github.com/murarth/resolve" 8 | repository = "https://github.com/murarth/resolve" 9 | 10 | keywords = [ "dns", "host", "resolver" ] 11 | license = "MIT/Apache-2.0" 12 | readme = "README.md" 13 | 14 | version = "0.2.0" 15 | authors = ["Murarth "] 16 | 17 | [dependencies] 18 | idna = "0.1" 19 | libc = "0.2" 20 | log = "0.4" 21 | rand = "0.5" 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # resolve 2 | 3 | `resolve` is a pure Rust implementation of the DNS protocol. 4 | 5 | It also provides high level facilities for hostname resolution and address 6 | reverse resolution. 7 | 8 | [Documentation](http://docs.rs/resolve/) 9 | 10 | ## Usage 11 | 12 | Add this to your `Cargo.toml`: 13 | 14 | ```toml 15 | [dependencies] 16 | resolve = "0.2" 17 | ``` 18 | 19 | And this to your crate root: 20 | 21 | ```rust 22 | extern crate resolve; 23 | ``` 24 | 25 | ## License 26 | 27 | `resolve` is distributed under the terms of both the MIT license and the 28 | Apache License (Version 2.0). 29 | 30 | See LICENSE-APACHE and LICENSE-MIT for details. 31 | -------------------------------------------------------------------------------- /examples/host_table.rs: -------------------------------------------------------------------------------- 1 | extern crate resolve; 2 | 3 | use resolve::hosts::{host_file, load_hosts}; 4 | 5 | fn main() { 6 | let path = host_file(); 7 | 8 | println!("Loading host table from {}", path.display()); 9 | println!(""); 10 | 11 | let table = match load_hosts(&path) { 12 | Ok(t) => t, 13 | Err(e) => { 14 | println!("Failed to load host table: {}", e); 15 | return; 16 | } 17 | }; 18 | 19 | for host in &table.hosts { 20 | println!(" {:<20} points to {}", host.name, host.address); 21 | 22 | for alias in &host.aliases { 23 | println!(" {:<20} points to {}", alias, host.address); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Domain Name System (DNS) communication protocol. 2 | 3 | #![deny(missing_docs)] 4 | 5 | extern crate idna as external_idna; 6 | extern crate libc; 7 | #[macro_use] extern crate log; 8 | extern crate rand; 9 | 10 | pub use address::address_name; 11 | pub use config::DnsConfig; 12 | pub use idna::{to_ascii, to_unicode}; 13 | pub use message::{DecodeError, EncodeError, Message, Question, Resource, 14 | MESSAGE_LIMIT}; 15 | pub use record::{Class, Record, RecordType}; 16 | pub use resolver::{resolve_addr, resolve_host, DnsResolver}; 17 | pub use socket::{DnsSocket, Error}; 18 | 19 | pub mod address; 20 | pub mod config; 21 | pub mod hosts; 22 | pub mod hostname; 23 | pub mod idna; 24 | pub mod message; 25 | pub mod record; 26 | #[cfg(unix)] pub mod resolv_conf; 27 | pub mod resolver; 28 | pub mod socket; 29 | -------------------------------------------------------------------------------- /examples/lookup_addr.rs: -------------------------------------------------------------------------------- 1 | extern crate resolve; 2 | 3 | use std::env::args; 4 | 5 | use resolve::resolve_addr; 6 | 7 | fn main() { 8 | let args = args().collect::>(); 9 | 10 | if args.len() == 1 { 11 | println!("Usage: {} [...]", args[0]); 12 | return; 13 | } 14 | 15 | for arg in &args[1..] { 16 | let ip = match arg.parse() { 17 | Ok(ip) => ip, 18 | Err(_) => { 19 | println!("\"{}\" is not a valid IP address", arg); 20 | continue; 21 | } 22 | }; 23 | 24 | match resolve_addr(&ip) { 25 | Ok(name) => { 26 | println!("{} resolved to \"{}\"", ip, name); 27 | } 28 | Err(e) => println!("failed to resolve {}: {}", ip, e) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/lookup_host.rs: -------------------------------------------------------------------------------- 1 | extern crate resolve; 2 | 3 | use std::env::args; 4 | 5 | use resolve::resolve_host; 6 | 7 | fn main() { 8 | let args = args().collect::>(); 9 | 10 | if args.len() == 1 { 11 | println!("Usage: {} [...]", args[0]); 12 | return; 13 | } 14 | 15 | for arg in &args[1..] { 16 | match resolve_host(&arg) { 17 | Ok(mut addrs) => { 18 | let addr = addrs.next().expect("empty ResolveHost"); 19 | let n = addrs.count(); 20 | 21 | if n == 0 { 22 | println!("\"{}\" resolved to {}", arg, addr); 23 | } else { 24 | println!("\"{}\" resolved to {} ({} more)", arg, addr, n); 25 | } 26 | } 27 | Err(e) => println!("failed to resolve \"{}\": {}", arg, e) 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/hostname.rs: -------------------------------------------------------------------------------- 1 | //! System hostname detection 2 | 3 | use std::ffi::CStr; 4 | use std::io; 5 | use std::str::from_utf8; 6 | 7 | use libc::{c_char, c_int, size_t}; 8 | 9 | extern "system" { 10 | fn gethostname(name: *mut c_char, len: size_t) -> c_int; 11 | } 12 | 13 | /// Returns the system hostname. 14 | pub fn get_hostname() -> io::Result { 15 | let mut buf = [0 as c_char; 256]; 16 | let res = unsafe { gethostname(buf.as_mut_ptr(), buf.len() as size_t) }; 17 | 18 | match res { 19 | -1 => Err(io::Error::last_os_error()), 20 | _ => { 21 | let s = unsafe { CStr::from_ptr(buf.as_ptr()) }; 22 | match from_utf8(s.to_bytes()) { 23 | Ok(s) => Ok(s.to_owned()), 24 | Err(_) => Err(io::Error::new( 25 | io::ErrorKind::Other, "invalid hostname")) 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Murarth 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 | -------------------------------------------------------------------------------- /examples/lookup_srv.rs: -------------------------------------------------------------------------------- 1 | extern crate resolve; 2 | 3 | use std::env::args; 4 | 5 | use resolve::{DnsConfig, DnsResolver}; 6 | use resolve::record::Srv; 7 | 8 | fn main() { 9 | let args = args().collect::>(); 10 | 11 | if args.len() != 4 { 12 | println!("Usage: {} ", args[0]); 13 | println!(" e.g. {} _http _tcp example.com", args[0]); 14 | return; 15 | } 16 | 17 | let config = match DnsConfig::load_default() { 18 | Ok(config) => config, 19 | Err(e) => { 20 | println!("failed to load system configuration: {}", e); 21 | return; 22 | } 23 | }; 24 | 25 | let resolver = match DnsResolver::new(config) { 26 | Ok(resolver) => resolver, 27 | Err(e) => { 28 | println!("failed to create DNS resolver: {}", e); 29 | return; 30 | } 31 | }; 32 | 33 | let name = format!("{}.{}.{}", args[1], args[2], args[3]); 34 | 35 | match resolver.resolve_record::(&name) { 36 | Ok(records) => { 37 | for srv in records { 38 | println!("SRV priority={} weight={} port={} target={}", 39 | srv.priority, srv.weight, srv.port, srv.target); 40 | } 41 | } 42 | Err(e) => { 43 | println!("{}", e); 44 | return; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/resolver.rs: -------------------------------------------------------------------------------- 1 | //! Example demonstrating a resolver using custom DNS servers 2 | 3 | extern crate resolve; 4 | 5 | use std::env::args; 6 | 7 | use resolve::{DnsConfig, DnsResolver}; 8 | 9 | fn main() { 10 | let config = DnsConfig::with_name_servers(vec![ 11 | // Use Google's public DNS servers instead of the system default. 12 | "8.8.8.8:53".parse().unwrap(), 13 | "8.8.4.4:53".parse().unwrap(), 14 | ]); 15 | 16 | let resolver = match DnsResolver::new(config) { 17 | Ok(r) => r, 18 | Err(e) => { 19 | println!("failed to create DNS resolver: {}", e); 20 | return; 21 | } 22 | }; 23 | 24 | let args = args().collect::>(); 25 | 26 | if args.len() == 1 { 27 | println!("Usage: {} [...]", args[0]); 28 | return; 29 | } 30 | 31 | for arg in &args[1..] { 32 | match resolver.resolve_host(&arg) { 33 | Ok(mut addrs) => { 34 | let addr = addrs.next().expect("empty ResolveHost"); 35 | let n = addrs.count(); 36 | 37 | if n == 0 { 38 | println!("\"{}\" resolved to {}", arg, addr); 39 | } else { 40 | println!("\"{}\" resolved to {} ({} more)", arg, addr, n); 41 | } 42 | } 43 | Err(e) => println!("failed to resolve \"{}\": {}", arg, e) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /examples/lookup_txt.rs: -------------------------------------------------------------------------------- 1 | extern crate resolve; 2 | 3 | use std::str; 4 | use std::env::args; 5 | 6 | use resolve::{DnsConfig, DnsResolver}; 7 | use resolve::record::Txt; 8 | 9 | fn main() { 10 | let args = args().collect::>(); 11 | 12 | if args.len() != 2 { 13 | println!("Usage: {} ", args[0]); 14 | println!(" e.g. {} example.com", args[0]); 15 | return; 16 | } 17 | 18 | let config = match DnsConfig::load_default() { 19 | Ok(config) => config, 20 | Err(e) => { 21 | println!("Failed to load system configuration: {}", e); 22 | return; 23 | } 24 | }; 25 | 26 | let resolver = match DnsResolver::new(config) { 27 | Ok(resolver) => resolver, 28 | Err(e) => { 29 | println!("Failed to create DNS resolver: {}", e); 30 | return; 31 | } 32 | }; 33 | 34 | match resolver.resolve_record::(&args[1]) { 35 | Ok(records) => { 36 | for txt in records { 37 | let data = match str::from_utf8(&txt.data) { 38 | Ok(string) => string, 39 | Err(e) => { 40 | println!("Failed to decode UTF8 data: {}", e); 41 | return; 42 | } 43 | }; 44 | println!("TXT data={}", data); 45 | } 46 | } 47 | Err(e) => { 48 | println!("{}", e); 49 | return; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | //! DNS resolver configuration 2 | 3 | use std::io; 4 | use std::net::SocketAddr; 5 | use std::time::Duration; 6 | 7 | /// Configures the behavior of DNS requests 8 | #[derive(Clone, Debug)] 9 | pub struct DnsConfig { 10 | /// List of name servers; must not be empty 11 | pub name_servers: Vec, 12 | /// List of search domains 13 | pub search: Vec, 14 | 15 | /// Minimum number of dots in a name to trigger an initial absolute query 16 | pub n_dots: u32, 17 | /// Duration before retrying or failing an unanswered request 18 | pub timeout: Duration, 19 | /// Number of attempts made before returning an error 20 | pub attempts: u32, 21 | 22 | /// Whether to rotate through available nameservers 23 | pub rotate: bool, 24 | /// If `true`, perform `AAAA` queries first and return IPv4 addresses 25 | /// as IPv4-mapped IPv6 addresses. 26 | pub use_inet6: bool, 27 | } 28 | 29 | impl DnsConfig { 30 | /// Returns the default system configuration for DNS requests. 31 | pub fn load_default() -> io::Result { 32 | default_config_impl() 33 | } 34 | 35 | /// Returns a `DnsConfig` using the given set of name servers, 36 | /// setting all other fields to generally sensible default values. 37 | pub fn with_name_servers(name_servers: Vec) -> DnsConfig { 38 | DnsConfig{ 39 | name_servers: name_servers, 40 | search: Vec::new(), 41 | 42 | n_dots: 1, 43 | timeout: Duration::from_secs(5), 44 | attempts: 5, 45 | 46 | rotate: false, 47 | use_inet6: false, 48 | } 49 | } 50 | } 51 | 52 | #[cfg(unix)] 53 | fn default_config_impl() -> io::Result { 54 | use resolv_conf::load; 55 | load() 56 | } 57 | 58 | #[cfg(windows)] 59 | fn default_config_impl() -> io::Result { 60 | // TODO: Get a list of nameservers from Windows API. 61 | // For now, return an IO error. 62 | Err(io::Error::new(io::ErrorKind::Other, "Nameserver list not available on Windows")) 63 | } 64 | -------------------------------------------------------------------------------- /src/idna.rs: -------------------------------------------------------------------------------- 1 | //! Implements RFC 3490, Internationalized Domain Names in Applications, 2 | //! encoding for domain name labels containing Unicode. 3 | 4 | use std::borrow::Cow::{self, Borrowed, Owned}; 5 | 6 | use external_idna; 7 | 8 | /// Indicates an error in encoding or decoding Punycode data 9 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 10 | pub struct Error; 11 | 12 | /// Converts a label or host to its ASCII format. If the string is already ASCII, 13 | /// it will be returned unmodified. If an error is encountered in encoding, 14 | /// `Err` will be returned. 15 | pub fn to_ascii(s: &str) -> Result, Error> { 16 | if s.is_ascii() { 17 | Ok(Borrowed(s)) 18 | } else { 19 | external_idna::domain_to_ascii(s) 20 | .map(Owned) 21 | .map_err(|_| Error) 22 | } 23 | } 24 | 25 | /// Converts a label or host to its Unicode format. If the string is not an 26 | /// internationalized domain name, it will be returned unmodified. If an error 27 | /// is encountered in decoding, `Err` will be returned. 28 | pub fn to_unicode(s: &str) -> Result, Error> { 29 | let is_unicode = s.split('.').any(|s| s.starts_with("xn--")); 30 | 31 | if is_unicode { 32 | match external_idna::domain_to_unicode(s) { 33 | (s, Ok(_)) => Ok(Owned(s)), 34 | (_, Err(_)) => Err(Error) 35 | } 36 | } else { 37 | Ok(Borrowed(s)) 38 | } 39 | } 40 | 41 | #[cfg(test)] 42 | mod test { 43 | use super::{to_ascii, to_unicode}; 44 | 45 | static SAMPLE_HOSTS: &'static [(&'static str, &'static str)] = &[ 46 | ("bücher.de.", "xn--bcher-kva.de."), 47 | ("ουτοπία.δπθ.gr.", "xn--kxae4bafwg.xn--pxaix.gr."), 48 | // We want to preserve a lack of trailing '.', too. 49 | ("bücher.de", "xn--bcher-kva.de"), 50 | ("ουτοπία.δπθ.gr", "xn--kxae4bafwg.xn--pxaix.gr"), 51 | ]; 52 | 53 | #[test] 54 | fn test_hosts() { 55 | for &(uni, ascii) in SAMPLE_HOSTS { 56 | assert_eq!(to_ascii(uni).unwrap(), ascii); 57 | assert_eq!(to_unicode(ascii).unwrap(), uni); 58 | 59 | // Ensure the functions are idempotent 60 | assert_eq!(to_ascii(ascii).unwrap(), ascii); 61 | assert_eq!(to_unicode(uni).unwrap(), uni); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/address.rs: -------------------------------------------------------------------------------- 1 | //! IP address utility functions 2 | 3 | use std::net::{IpAddr, SocketAddr}; 4 | 5 | /// Compares two `IpAddr`s, checking for IPv6-compatible or IPv6-mapped addresses. 6 | pub fn address_equal(a: &IpAddr, b: &IpAddr) -> bool { 7 | match (*a, *b) { 8 | // Simple comparisons; (V4 == V4) or (V6 == V6) 9 | (IpAddr::V4(ref a), IpAddr::V4(ref b)) => a == b, 10 | (IpAddr::V6(ref a), IpAddr::V6(ref b)) => a == b, 11 | // Not-so-simple comparison; V4 == maybe-V6-wrapped-V4 12 | (IpAddr::V6(ref a), IpAddr::V4(ref b)) => { 13 | match a.to_ipv4() { 14 | Some(ref a4) => a4 == b, 15 | None => false 16 | } 17 | } 18 | (IpAddr::V4(..), IpAddr::V6(..)) => address_equal(b, a), 19 | } 20 | } 21 | 22 | /// Compares two `SocketAddr`s, checking for IPv6-compatible or IPv6-mapped addresses. 23 | pub fn socket_address_equal(a: &SocketAddr, b: &SocketAddr) -> bool { 24 | a.port() == b.port() && address_equal(&a.ip(), &b.ip()) 25 | } 26 | 27 | /// Returns an IP address formatted as a domain name. 28 | pub fn address_name(addr: &IpAddr) -> String { 29 | match *addr { 30 | IpAddr::V4(ref addr) => { 31 | let octets = addr.octets(); 32 | format!("{}.{}.{}.{}.in-addr.arpa", 33 | octets[3], octets[2], octets[1], octets[0]) 34 | } 35 | IpAddr::V6(ref addr) => { 36 | let s = addr.segments(); 37 | format!( 38 | "{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.\ 39 | {:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.\ 40 | {:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.\ 41 | {:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.{:x}.ip6.arpa", 42 | s[7] & 0xf, (s[7] & 0x00f0) >> 4, (s[7] & 0x0f00) >> 8, (s[7] & 0xf000) >> 12, 43 | s[6] & 0xf, (s[6] & 0x00f0) >> 4, (s[6] & 0x0f00) >> 8, (s[6] & 0xf000) >> 12, 44 | s[5] & 0xf, (s[5] & 0x00f0) >> 4, (s[5] & 0x0f00) >> 8, (s[5] & 0xf000) >> 12, 45 | s[4] & 0xf, (s[4] & 0x00f0) >> 4, (s[4] & 0x0f00) >> 8, (s[4] & 0xf000) >> 12, 46 | s[3] & 0xf, (s[3] & 0x00f0) >> 4, (s[3] & 0x0f00) >> 8, (s[3] & 0xf000) >> 12, 47 | s[2] & 0xf, (s[2] & 0x00f0) >> 4, (s[2] & 0x0f00) >> 8, (s[2] & 0xf000) >> 12, 48 | s[1] & 0xf, (s[1] & 0x00f0) >> 4, (s[1] & 0x0f00) >> 8, (s[1] & 0xf000) >> 12, 49 | s[0] & 0xf, (s[0] & 0x00f0) >> 4, (s[0] & 0x0f00) >> 8, (s[0] & 0xf000) >> 12) 50 | } 51 | } 52 | } 53 | 54 | #[cfg(test)] 55 | mod test { 56 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 57 | use super::{address_equal, address_name}; 58 | 59 | #[test] 60 | fn test_address_equal() { 61 | let ip = Ipv4Addr::new(1, 2, 3, 4); 62 | let a = IpAddr::V4(ip); 63 | 64 | assert!(address_equal(&a, &IpAddr::V6(ip.to_ipv6_compatible()))); 65 | assert!(address_equal(&a, &IpAddr::V6(ip.to_ipv6_mapped()))); 66 | assert!(!address_equal(&a, &IpAddr::V6( 67 | Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0x0102, 0x0304)))); 68 | } 69 | 70 | #[test] 71 | fn test_address_name() { 72 | assert_eq!(address_name(&"192.0.2.5".parse::().unwrap()), 73 | "5.2.0.192.in-addr.arpa"); 74 | assert_eq!(address_name(&"2001:db8::567:89ab".parse::().unwrap()), 75 | "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/socket.rs: -------------------------------------------------------------------------------- 1 | //! Low-level UDP socket operations 2 | 3 | use std::fmt; 4 | use std::io; 5 | use std::net::{IpAddr, Ipv6Addr, SocketAddr, ToSocketAddrs, UdpSocket}; 6 | 7 | use address::socket_address_equal; 8 | use message::{DecodeError, DnsError, EncodeError, Message, MESSAGE_LIMIT}; 9 | 10 | /// Represents a socket transmitting DNS messages. 11 | pub struct DnsSocket { 12 | sock: UdpSocket, 13 | } 14 | 15 | impl DnsSocket { 16 | /// Returns a `DnsSocket`, bound to an unspecified address. 17 | pub fn new() -> io::Result { 18 | DnsSocket::bind(&SocketAddr::new( 19 | IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0)) 20 | } 21 | 22 | /// Returns a `DnsSocket`, bound to the given address. 23 | pub fn bind(addr: A) -> io::Result { 24 | Ok(DnsSocket{ 25 | sock: try!(UdpSocket::bind(addr)), 26 | }) 27 | } 28 | 29 | /// Returns a reference to the wrapped `UdpSocket`. 30 | pub fn get(&self) -> &UdpSocket { 31 | &self.sock 32 | } 33 | 34 | /// Sends a message to the given address. 35 | pub fn send_message(&self, 36 | message: &Message, addr: A) -> Result<(), Error> { 37 | let mut buf = [0; MESSAGE_LIMIT]; 38 | let data = try!(message.encode(&mut buf)); 39 | try!(self.sock.send_to(data, addr)); 40 | Ok(()) 41 | } 42 | 43 | /// Receives a message, returning the address of the sender. 44 | /// The given buffer is used to store and parse message data. 45 | /// 46 | /// The buffer should be exactly `MESSAGE_LIMIT` bytes in length. 47 | pub fn recv_from<'buf>(&self, buf: &'buf mut [u8]) 48 | -> Result<(Message<'buf>, SocketAddr), Error> { 49 | let (n, addr) = try!(self.sock.recv_from(buf)); 50 | 51 | let msg = try!(Message::decode(&buf[..n])); 52 | Ok((msg, addr)) 53 | } 54 | 55 | /// Attempts to read a DNS message. The message will only be decoded if the 56 | /// remote address matches `addr`. If a packet is received from a non-matching 57 | /// address, the message is not decoded and `Ok(None)` is returned. 58 | /// 59 | /// The buffer should be exactly `MESSAGE_LIMIT` bytes in length. 60 | pub fn recv_message<'buf>(&self, addr: &SocketAddr, buf: &'buf mut [u8]) 61 | -> Result>, Error> { 62 | let (n, recv_addr) = try!(self.sock.recv_from(buf)); 63 | 64 | if !socket_address_equal(&recv_addr, addr) { 65 | Ok(None) 66 | } else { 67 | let msg = try!(Message::decode(&buf[..n])); 68 | Ok(Some(msg)) 69 | } 70 | } 71 | } 72 | 73 | /// Represents an error in sending or receiving a DNS message. 74 | #[derive(Debug)] 75 | pub enum Error { 76 | /// Error decoding received data 77 | DecodeError(DecodeError), 78 | /// Error encoding data to be sent 79 | EncodeError(EncodeError), 80 | /// Server responded with error message 81 | DnsError(DnsError), 82 | /// Error generated by network operation 83 | IoError(io::Error), 84 | } 85 | 86 | impl Error { 87 | /// Returns `true` if the error is the result of an operation having timed out. 88 | pub fn is_timeout(&self) -> bool { 89 | match *self { 90 | Error::IoError(ref e) => { 91 | let kind = e.kind(); 92 | kind == io::ErrorKind::TimedOut || 93 | kind == io::ErrorKind::WouldBlock 94 | } 95 | _ => false 96 | } 97 | } 98 | } 99 | 100 | impl fmt::Display for Error { 101 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 102 | match *self { 103 | Error::DecodeError(e) => write!(f, "error decoding message: {}", e), 104 | Error::EncodeError(ref e) => write!(f, "error encoding message: {}", e), 105 | Error::DnsError(e) => write!(f, "server responded with error: {}", e), 106 | Error::IoError(ref e) => fmt::Display::fmt(e, f), 107 | } 108 | } 109 | } 110 | 111 | impl From for Error { 112 | fn from(err: DecodeError) -> Error { 113 | Error::DecodeError(err) 114 | } 115 | } 116 | 117 | impl From for Error { 118 | fn from(err: EncodeError) -> Error { 119 | Error::EncodeError(err) 120 | } 121 | } 122 | 123 | impl From for Error { 124 | fn from(err: DnsError) -> Error { 125 | Error::DnsError(err) 126 | } 127 | } 128 | 129 | impl From for Error { 130 | fn from(err: io::Error) -> Error { 131 | Error::IoError(err) 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/hosts.rs: -------------------------------------------------------------------------------- 1 | //! Implements parsing the system hosts file to produce a host table 2 | 3 | use std::fs::File; 4 | use std::io::{self, Read}; 5 | use std::net::IpAddr; 6 | use std::path::{Path, PathBuf}; 7 | 8 | /// Represents a host table, consisting of addresses mapped to names. 9 | #[derive(Clone, Debug)] 10 | pub struct HostTable { 11 | /// Contained hosts 12 | pub hosts: Vec, 13 | } 14 | 15 | impl HostTable { 16 | /// Returns the address for the first host matching the given name. 17 | /// 18 | /// If no match is found, `None` is returned. 19 | pub fn find_address(&self, name: &str) -> Option { 20 | self.find_host_by_name(name).map(|h| h.address) 21 | } 22 | 23 | /// Returns the canonical name for the first host matching the given address. 24 | /// 25 | /// If no match is found, `None` is returned. 26 | pub fn find_name(&self, addr: IpAddr) -> Option<&str> { 27 | self.find_host_by_address(addr).map(|h| &h.name[..]) 28 | } 29 | 30 | /// Returns the first host matching the given address. 31 | /// 32 | /// If no match is found, `None` is returned. 33 | pub fn find_host_by_address(&self, addr: IpAddr) -> Option<&Host> { 34 | self.hosts.iter().find(|h| h.address == addr) 35 | } 36 | 37 | /// Returns the first host matching the given address. 38 | /// 39 | /// If no match is found, `None` is returned. 40 | pub fn find_host_by_name(&self, name: &str) -> Option<&Host> { 41 | self.hosts.iter().find(|h| h.name == name || 42 | h.aliases.iter().any(|a| a == name)) 43 | } 44 | } 45 | 46 | /// Represents a single host within a host table. 47 | #[derive(Clone, Debug)] 48 | pub struct Host { 49 | /// Host address 50 | pub address: IpAddr, 51 | /// Canonical host name 52 | pub name: String, 53 | /// Host aliases 54 | pub aliases: Vec, 55 | } 56 | 57 | /// Returns the absolute path to the system hosts file. 58 | pub fn host_file() -> PathBuf { 59 | host_file_impl() 60 | } 61 | 62 | #[cfg(unix)] 63 | fn host_file_impl() -> PathBuf { 64 | PathBuf::from("/etc/hosts") 65 | } 66 | 67 | #[cfg(windows)] 68 | fn host_file_impl() -> PathBuf { 69 | use std::env::var_os; 70 | 71 | match var_os("SystemRoot") { 72 | Some(root) => PathBuf::from(root).join("System32/drivers/etc/hosts"), 73 | // I'm not sure if this is the "correct" thing to do, 74 | // but it seems like a better alternative than panicking. 75 | None => PathBuf::from("C:/Windows/System32/drivers/etc/hosts") 76 | } 77 | } 78 | 79 | /// Loads a host table from the given filename. 80 | /// 81 | /// If an error is encountered in opening the file or reading its contents 82 | /// or if the file is malformed, the error is returned. 83 | pub fn load_hosts(path: &Path) -> io::Result { 84 | let mut f = try!(File::open(path)); 85 | let mut buf = String::new(); 86 | 87 | try!(f.read_to_string(&mut buf)); 88 | parse_host_table(&buf) 89 | } 90 | 91 | /// Attempts to parse a host table in the hosts file format. 92 | pub fn parse_host_table(data: &str) -> io::Result { 93 | let mut hosts = Vec::new(); 94 | 95 | for line in data.lines() { 96 | let mut line = line; 97 | 98 | if let Some(pos) = line.find('#') { 99 | line = &line[..pos]; 100 | } 101 | 102 | let mut words = line.split_whitespace(); 103 | 104 | let addr_str = match words.next() { 105 | Some(w) => w, 106 | None => continue 107 | }; 108 | 109 | let addr = match addr_str.parse() { 110 | Ok(addr) => addr, 111 | Err(_) => return Err(io::Error::new(io::ErrorKind::InvalidData, 112 | format!("invalid address: {}", addr_str))) 113 | }; 114 | 115 | let name = match words.next() { 116 | Some(w) => w, 117 | None => return Err(io::Error::new(io::ErrorKind::InvalidData, 118 | "missing names")) 119 | }; 120 | 121 | hosts.push(Host{ 122 | address: addr, 123 | name: name.to_owned(), 124 | aliases: words.map(|s| s.to_owned()).collect(), 125 | }); 126 | } 127 | 128 | Ok(HostTable{hosts: hosts}) 129 | } 130 | 131 | #[cfg(test)] 132 | mod test { 133 | use super::parse_host_table; 134 | use std::net::IpAddr; 135 | 136 | fn ip(s: &str) -> IpAddr { 137 | s.parse().unwrap() 138 | } 139 | 140 | #[test] 141 | fn test_hosts() { 142 | let hosts = parse_host_table("\ 143 | # Comment line 144 | 127.0.0.1 localhost 145 | ::1 ip6-localhost 146 | 147 | 192.168.10.1 foo foo.bar foo.local # Mid-line comment 148 | ").unwrap(); 149 | 150 | assert_eq!(hosts.find_address("localhost"), Some(ip("127.0.0.1"))); 151 | assert_eq!(hosts.find_address("ip6-localhost"), Some(ip("::1"))); 152 | assert_eq!(hosts.find_name(ip("192.168.10.1")), Some("foo")); 153 | 154 | assert_eq!(hosts.find_address("missing"), None); 155 | assert_eq!(hosts.find_name(ip("0.0.0.0")), None); 156 | 157 | let host = hosts.find_host_by_address(ip("192.168.10.1")).unwrap(); 158 | 159 | assert_eq!(host.address, ip("192.168.10.1")); 160 | assert_eq!(host.name, "foo"); 161 | assert_eq!(host.aliases, ["foo.bar", "foo.local"]); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/resolv_conf.rs: -------------------------------------------------------------------------------- 1 | //! Partial Unix `resolv.conf(5)` parser 2 | 3 | use std::cmp::min; 4 | use std::fs::File; 5 | use std::io::{self, BufRead, BufReader}; 6 | use std::time::Duration; 7 | use std::net::{IpAddr, SocketAddr}; 8 | 9 | use config::DnsConfig; 10 | use hostname::get_hostname; 11 | 12 | /// port for DNS communication 13 | const DNS_PORT: u16 = 53; 14 | 15 | /// Maximum number of name servers loaded from `resolv.conf` 16 | pub const MAX_NAME_SERVERS: usize = 3; 17 | 18 | /// Default value of `"options attempts:n"` 19 | pub const DEFAULT_ATTEMPTS: u32 = 2; 20 | 21 | /// Default value of `"options ndots:n"` 22 | pub const DEFAULT_N_DOTS: u32 = 1; 23 | 24 | /// Default value of `"options timeout:n"` 25 | pub const DEFAULT_TIMEOUT: u64 = 5; 26 | 27 | /// Maximum allowed value of `"options attempts:n"` 28 | pub const MAX_ATTEMPTS: u32 = 5; 29 | 30 | /// Maximum allowed value of `"options ndots:n"` 31 | pub const MAX_N_DOTS: u32 = 15; 32 | 33 | /// Maximum allowed value of `"options timeout:n"` 34 | pub const MAX_TIMEOUT: u64 = 30; 35 | 36 | /// Path to system `resolv.conf` 37 | pub const RESOLV_CONF_PATH: &'static str = "/etc/resolv.conf"; 38 | 39 | fn default_config() -> DnsConfig { 40 | DnsConfig{ 41 | name_servers: Vec::new(), 42 | search: Vec::new(), 43 | 44 | n_dots: DEFAULT_N_DOTS, 45 | attempts: DEFAULT_ATTEMPTS, 46 | timeout: Duration::from_secs(DEFAULT_TIMEOUT), 47 | 48 | rotate: false, 49 | use_inet6: false, 50 | } 51 | } 52 | 53 | /// Examines system `resolv.conf` and returns a configuration loosely based 54 | /// on its contents. If the file cannot be read or lacks required directives, 55 | /// an error is returned. 56 | pub fn load() -> io::Result { 57 | parse(BufReader::new(try!(File::open(RESOLV_CONF_PATH)))) 58 | } 59 | 60 | fn parse(r: R) -> io::Result { 61 | let mut cfg = default_config(); 62 | 63 | for line in r.lines() { 64 | let line = try!(line); 65 | 66 | if line.is_empty() || line.starts_with(|c| c == '#' || c == ';') { 67 | continue; 68 | } 69 | 70 | let mut words = line.split_whitespace(); 71 | 72 | let name = match words.next() { 73 | Some(name) => name, 74 | None => continue 75 | }; 76 | 77 | match name { 78 | "nameserver" => { 79 | match words.next() { 80 | Some(ip) => { 81 | if cfg.name_servers.len() < MAX_NAME_SERVERS { 82 | if let Ok(ip) = ip.parse::() { 83 | cfg.name_servers.push(SocketAddr::new(ip, DNS_PORT)) 84 | } 85 | } 86 | } 87 | None => () 88 | } 89 | } 90 | "domain" => { 91 | match words.next() { 92 | Some(domain) => cfg.search = vec![domain.to_owned()], 93 | None => () 94 | } 95 | } 96 | "search" => { 97 | cfg.search = words.map(|s| s.to_owned()).collect(); 98 | } 99 | "options" => { 100 | for opt in words { 101 | let (opt, value) = match opt.find(':') { 102 | Some(pos) => (&opt[..pos], &opt[pos + 1..]), 103 | None => (opt, "") 104 | }; 105 | 106 | match opt { 107 | "ndots" => { 108 | if let Ok(n) = value.parse() { 109 | cfg.n_dots = min(n, MAX_N_DOTS); 110 | } 111 | } 112 | "timeout" => { 113 | if let Ok(n) = value.parse() { 114 | cfg.timeout = Duration::from_secs( 115 | min(n, MAX_TIMEOUT)); 116 | } 117 | } 118 | "attempts" => { 119 | if let Ok(n) = value.parse() { 120 | cfg.attempts = min(n, MAX_ATTEMPTS); 121 | } 122 | } 123 | "rotate" => cfg.rotate = true, 124 | "inet6" => cfg.use_inet6 = true, 125 | _ => () 126 | } 127 | } 128 | } 129 | _ => () 130 | } 131 | } 132 | 133 | if cfg.name_servers.is_empty() { 134 | return Err(io::Error::new(io::ErrorKind::Other, 135 | "no nameserver directives in resolv.conf")) 136 | } 137 | 138 | if cfg.search.is_empty() { 139 | let host = try!(get_hostname()); 140 | 141 | if let Some(pos) = host.find('.') { 142 | cfg.search = vec![host[pos + 1..].to_owned()]; 143 | } 144 | } 145 | 146 | Ok(cfg) 147 | } 148 | 149 | #[cfg(test)] 150 | mod test { 151 | use std::io::Cursor; 152 | use super::{parse, MAX_TIMEOUT}; 153 | 154 | const TEST_CONFIG: &'static str = "\ 155 | nameserver 127.0.0.1 156 | search foo.com bar.com 157 | options timeout:99 ndots:2 rotate"; 158 | 159 | #[test] 160 | fn test_parse() { 161 | let r = Cursor::new(TEST_CONFIG.as_bytes()); 162 | let cfg = parse(r).unwrap(); 163 | 164 | assert_eq!(cfg.name_servers, ["127.0.0.1:53".parse().unwrap()]); 165 | assert_eq!(cfg.search, ["foo.com", "bar.com"]); 166 | assert_eq!(cfg.timeout.as_secs(), MAX_TIMEOUT); 167 | assert_eq!(cfg.n_dots, 2); 168 | assert_eq!(cfg.rotate, true); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/record.rs: -------------------------------------------------------------------------------- 1 | //! DNS resource record types 2 | 3 | use std::mem::transmute; 4 | use std::net::{Ipv4Addr, Ipv6Addr}; 5 | 6 | use message::{DecodeError, EncodeError, MsgReader, MsgWriter}; 7 | 8 | /// Represents the class of data in a message. 9 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 10 | pub enum Class { 11 | /// Internet (`IN`) 12 | Internet, 13 | /// Any (`*`) 14 | Any, 15 | /// An unrecognized class 16 | Other(u16), 17 | } 18 | 19 | impl Class { 20 | /// Converts a `u16` to a `Class`. 21 | pub fn from_u16(u: u16) -> Class { 22 | match u { 23 | 1 => Class::Internet, 24 | 255 => Class::Any, 25 | n => Class::Other(n), 26 | } 27 | } 28 | 29 | /// Converts a `Class` to a `u16`. 30 | pub fn to_u16(&self) -> u16 { 31 | match *self { 32 | Class::Internet => 1, 33 | Class::Any => 255, 34 | Class::Other(n) => n, 35 | } 36 | } 37 | } 38 | 39 | /// Represents the type of data in a message. 40 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 41 | pub enum RecordType { 42 | /// An IPv4 host address 43 | A, 44 | /// An IPv6 host address 45 | AAAA, 46 | /// Canonical name for an alias 47 | CName, 48 | /// Mail exchange 49 | Mx, 50 | /// Authoritative name server 51 | Ns, 52 | /// Domain name pointer 53 | Ptr, 54 | /// Start of authority 55 | Soa, 56 | /// Service record 57 | Srv, 58 | /// Text string 59 | Txt, 60 | /// Unrecognized record type 61 | Other(u16), 62 | } 63 | 64 | macro_rules! record_types { 65 | ( $( $name:ident => $code:expr , )+ ) => { 66 | impl RecordType { 67 | /// Converts a `u16` to a `RecordType`. 68 | pub fn from_u16(u: u16) -> RecordType { 69 | match u { 70 | $( $code => RecordType::$name , )+ 71 | n => RecordType::Other(n), 72 | } 73 | } 74 | 75 | /// Converts a `RecordType` to a `u16`. 76 | pub fn to_u16(&self) -> u16 { 77 | match *self { 78 | $( RecordType::$name => $code , )+ 79 | RecordType::Other(n) => n, 80 | } 81 | } 82 | } 83 | } 84 | } 85 | 86 | record_types!{ 87 | A => 1, 88 | AAAA => 28, 89 | CName => 5, 90 | Mx => 15, 91 | Ns => 2, 92 | Ptr => 12, 93 | Soa => 6, 94 | Srv => 33, 95 | Txt => 16, 96 | } 97 | 98 | /// Represents resource record data. 99 | pub trait Record: Sized { 100 | /// Decodes the `Record` from resource rdata. 101 | fn decode(data: &mut MsgReader) -> Result; 102 | 103 | /// Encodes the `Record` to resource rdata. 104 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError>; 105 | 106 | /// Returns the `RecordType` of queries for this record. 107 | fn record_type() -> RecordType; 108 | } 109 | 110 | /// An IPv4 host address 111 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] 112 | pub struct A { 113 | /// The host address 114 | pub address: Ipv4Addr, 115 | } 116 | 117 | impl Record for A { 118 | fn decode(data: &mut MsgReader) -> Result { 119 | let mut buf = [0; 4]; 120 | try!(data.read(&mut buf)); 121 | Ok(A{address: Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3])}) 122 | } 123 | 124 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 125 | data.write(&self.address.octets()) 126 | } 127 | 128 | fn record_type() -> RecordType { RecordType::A } 129 | } 130 | 131 | /// An IPv6 host address 132 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] 133 | pub struct AAAA { 134 | /// The host address 135 | pub address: Ipv6Addr, 136 | } 137 | 138 | impl Record for AAAA { 139 | fn decode(data: &mut MsgReader) -> Result { 140 | let mut buf = [0; 16]; 141 | try!(data.read(&mut buf)); 142 | let segments: [u16; 8] = unsafe { transmute(buf) }; 143 | Ok(AAAA{address: Ipv6Addr::new( 144 | u16::from_be(segments[0]), u16::from_be(segments[1]), 145 | u16::from_be(segments[2]), u16::from_be(segments[3]), 146 | u16::from_be(segments[4]), u16::from_be(segments[5]), 147 | u16::from_be(segments[6]), u16::from_be(segments[7]))}) 148 | } 149 | 150 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 151 | let mut segments = self.address.segments(); 152 | for seg in &mut segments { *seg = seg.to_be() } 153 | let buf: [u8; 16] = unsafe { transmute(segments) }; 154 | data.write(&buf) 155 | } 156 | 157 | fn record_type() -> RecordType { RecordType::AAAA } 158 | } 159 | 160 | /// Canonical name for an alias 161 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 162 | pub struct CName { 163 | /// Canonical host name 164 | pub name: String, 165 | } 166 | 167 | impl Record for CName { 168 | fn decode(data: &mut MsgReader) -> Result { 169 | Ok(CName{name: try!(data.read_name())}) 170 | } 171 | 172 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 173 | data.write_name(&self.name) 174 | } 175 | 176 | fn record_type() -> RecordType { RecordType::CName } 177 | } 178 | 179 | /// Mail exchange data 180 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 181 | pub struct Mx { 182 | /// Represents the preference of this record among others. 183 | /// Lower values are preferred. 184 | pub preference: u16, 185 | /// Domain name willing to act as mail exchange for the host. 186 | pub exchange: String, 187 | } 188 | 189 | impl Record for Mx { 190 | fn decode(data: &mut MsgReader) -> Result { 191 | Ok(Mx{ 192 | preference: try!(data.read_u16()), 193 | exchange: try!(data.read_name()), 194 | }) 195 | } 196 | 197 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 198 | try!(data.write_u16(self.preference)); 199 | data.write_name(&self.exchange) 200 | } 201 | 202 | fn record_type() -> RecordType { RecordType::Mx } 203 | } 204 | 205 | /// Authoritative name server 206 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 207 | pub struct Ns { 208 | /// Host which should be authoritative for the specified class and domain 209 | pub name: String, 210 | } 211 | 212 | impl Record for Ns { 213 | fn decode(data: &mut MsgReader) -> Result { 214 | Ok(Ns{name: try!(data.read_name())}) 215 | } 216 | 217 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 218 | data.write_name(&self.name) 219 | } 220 | 221 | fn record_type() -> RecordType { RecordType::Ns } 222 | } 223 | 224 | /// Domain name pointer 225 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 226 | pub struct Ptr { 227 | /// The name of the host 228 | pub name: String, 229 | } 230 | 231 | impl Record for Ptr { 232 | fn decode(data: &mut MsgReader) -> Result { 233 | Ok(Ptr{name: try!(data.read_name())}) 234 | } 235 | 236 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 237 | data.write_name(&self.name) 238 | } 239 | 240 | fn record_type() -> RecordType { RecordType::Ptr } 241 | } 242 | 243 | /// Start of authority 244 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 245 | pub struct Soa { 246 | /// Domain name of the name server that was the original or primary source 247 | /// of data for this zone. 248 | pub mname: String, 249 | /// Domain name which specifies the mailbox of the person responsible 250 | /// for this zone. 251 | pub rname: String, 252 | /// Version number of the original copy of the zone. This value wraps and 253 | /// should be compared using sequence space arithmetic. 254 | pub serial: u32, 255 | /// Time interval before the zone should be refreshed. 256 | pub refresh: u32, 257 | /// Time interval that should elapse before a failed refresh should be retried. 258 | pub retry: u32, 259 | /// Time value that specifies the upper limit on the time interval that can 260 | /// elapse before the zone is no longer authoritative. 261 | pub expire: u32, 262 | /// Minimum TTL that should be exported with any resource record from this zone. 263 | pub minimum: u32, 264 | } 265 | 266 | impl Record for Soa { 267 | fn decode(data: &mut MsgReader) -> Result { 268 | Ok(Soa{ 269 | mname: try!(data.read_name()), 270 | rname: try!(data.read_name()), 271 | serial: try!(data.read_u32()), 272 | refresh: try!(data.read_u32()), 273 | retry: try!(data.read_u32()), 274 | expire: try!(data.read_u32()), 275 | minimum: try!(data.read_u32()), 276 | }) 277 | } 278 | 279 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 280 | try!(data.write_name(&self.mname)); 281 | try!(data.write_name(&self.rname)); 282 | try!(data.write_u32(self.serial)); 283 | try!(data.write_u32(self.refresh)); 284 | try!(data.write_u32(self.retry)); 285 | try!(data.write_u32(self.expire)); 286 | try!(data.write_u32(self.minimum)); 287 | Ok(()) 288 | } 289 | 290 | fn record_type() -> RecordType { RecordType::Soa } 291 | } 292 | 293 | /// Service record 294 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 295 | pub struct Srv { 296 | /// Record priority 297 | pub priority: u16, 298 | /// Record weight 299 | pub weight: u16, 300 | /// Service port 301 | pub port: u16, 302 | /// Target host name 303 | pub target: String, 304 | } 305 | 306 | impl Record for Srv { 307 | fn decode(data: &mut MsgReader) -> Result { 308 | Ok(Srv{ 309 | priority: try!(data.read_u16()), 310 | weight: try!(data.read_u16()), 311 | port: try!(data.read_u16()), 312 | target: try!(data.read_name()), 313 | }) 314 | } 315 | 316 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 317 | try!(data.write_u16(self.priority)); 318 | try!(data.write_u16(self.weight)); 319 | try!(data.write_u16(self.port)); 320 | try!(data.write_name(&self.target)); 321 | Ok(()) 322 | } 323 | 324 | fn record_type() -> RecordType { RecordType::Srv } 325 | } 326 | 327 | /// Text record 328 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 329 | pub struct Txt { 330 | /// One or more character strings 331 | pub data: Vec, 332 | } 333 | 334 | impl Record for Txt { 335 | fn decode(data: &mut MsgReader) -> Result { 336 | Ok(Txt{data: try!(data.read_character_string())}) 337 | } 338 | 339 | fn encode(&self, data: &mut MsgWriter) -> Result<(), EncodeError> { 340 | data.write_character_string(&self.data) 341 | } 342 | 343 | fn record_type() -> RecordType { RecordType::Txt } 344 | } 345 | -------------------------------------------------------------------------------- /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 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/resolver.rs: -------------------------------------------------------------------------------- 1 | //! High-level resolver operations 2 | 3 | use std::cell::Cell; 4 | use std::io; 5 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; 6 | use std::time::{Duration, Instant}; 7 | use std::vec::IntoIter; 8 | 9 | use address::address_name; 10 | use config::DnsConfig; 11 | use message::{Message, Qr, Question, MESSAGE_LIMIT}; 12 | use record::{A, AAAA, Class, Ptr, Record, RecordType}; 13 | use socket::{DnsSocket, Error}; 14 | 15 | /// Performs resolution operations 16 | pub struct DnsResolver { 17 | sock: DnsSocket, 18 | config: DnsConfig, 19 | /// Index of `config.name_servers` to use in next DNS request; 20 | /// ignored if `config.rotate` is `false`. 21 | next_ns: Cell, 22 | } 23 | 24 | impl DnsResolver { 25 | /// Constructs a `DnsResolver` using the given configuration. 26 | pub fn new(config: DnsConfig) -> io::Result { 27 | let bind = bind_addr(&config.name_servers); 28 | let sock = try!(DnsSocket::bind((bind, 0))); 29 | DnsResolver::with_sock(sock, config) 30 | } 31 | 32 | /// Constructs a `DnsResolver` using the given configuration and bound 33 | /// to the given address. 34 | pub fn bind(addr: A, config: DnsConfig) -> io::Result { 35 | let sock = try!(DnsSocket::bind(addr)); 36 | DnsResolver::with_sock(sock, config) 37 | } 38 | 39 | fn with_sock(sock: DnsSocket, config: DnsConfig) -> io::Result { 40 | Ok(DnsResolver{ 41 | sock: sock, 42 | config: config, 43 | next_ns: Cell::new(0), 44 | }) 45 | } 46 | 47 | /// Resolves an IPv4 or IPv6 address to a hostname. 48 | pub fn resolve_addr(&self, addr: &IpAddr) -> io::Result { 49 | convert_error("failed to resolve address", || { 50 | let mut out_msg = self.basic_message(); 51 | 52 | out_msg.question.push(Question::new( 53 | address_name(addr), RecordType::Ptr, Class::Internet)); 54 | 55 | let mut buf = [0; MESSAGE_LIMIT]; 56 | let msg = try!(self.send_message(&out_msg, &mut buf)); 57 | 58 | for rr in msg.answer.into_iter() { 59 | if rr.r_type == RecordType::Ptr { 60 | let ptr = try!(rr.read_rdata::()); 61 | let mut name = ptr.name; 62 | if name.ends_with('.') { 63 | name.pop(); 64 | } 65 | return Ok(name); 66 | } 67 | } 68 | 69 | Err(Error::IoError(io::Error::new(io::ErrorKind::Other, 70 | "failed to resolve address: name not found"))) 71 | }) 72 | } 73 | 74 | /// Resolves a hostname to a series of IPv4 or IPv6 addresses. 75 | pub fn resolve_host(&self, host: &str) -> io::Result { 76 | convert_error("failed to resolve host", || { 77 | query_names(host, &self.config, |name| { 78 | let mut err; 79 | let mut res = Vec::new(); 80 | 81 | info!("attempting lookup of name \"{}\"", name); 82 | 83 | if self.config.use_inet6 { 84 | err = self.resolve_host_v6(&name, 85 | |ip| res.push(IpAddr::V6(ip))).err(); 86 | 87 | if res.is_empty() { 88 | err = err.or(self.resolve_host_v4(&name, 89 | |ip| res.push(IpAddr::V6(ip.to_ipv6_mapped()))).err()); 90 | } 91 | } else { 92 | err = self.resolve_host_v4(&name, |ip| res.push(IpAddr::V4(ip))).err(); 93 | err = err.or(self.resolve_host_v6(&name, 94 | |ip| res.push(IpAddr::V6(ip))).err()); 95 | } 96 | 97 | if !res.is_empty() { 98 | return Ok(ResolveHost(res.into_iter())); 99 | } 100 | 101 | if let Some(e) = err { 102 | Err(e) 103 | } else { 104 | Err(Error::IoError(io::Error::new(io::ErrorKind::Other, 105 | "failed to resolve host: name not found"))) 106 | } 107 | }) 108 | }) 109 | } 110 | 111 | /// Requests a type of record from the DNS server and returns the results. 112 | pub fn resolve_record(&self, name: &str) -> io::Result> { 113 | convert_error("failed to resolve record", || { 114 | let r_ty = Rec::record_type(); 115 | let mut msg = self.basic_message(); 116 | 117 | msg.question.push(Question::new(name.to_owned(), r_ty, Class::Internet)); 118 | 119 | let mut buf = [0; MESSAGE_LIMIT]; 120 | let reply = try!(self.send_message(&msg, &mut buf)); 121 | 122 | let mut rec = Vec::new(); 123 | 124 | for rr in reply.answer.into_iter() { 125 | if rr.r_type == r_ty { 126 | rec.push(try!(rr.read_rdata::())); 127 | } 128 | } 129 | 130 | Ok(rec) 131 | }) 132 | } 133 | 134 | fn resolve_host_v4(&self, host: &str, mut f: F) -> Result<(), Error> 135 | where F: FnMut(Ipv4Addr) { 136 | let mut out_msg = self.basic_message(); 137 | 138 | out_msg.question.push(Question::new( 139 | host.to_owned(), RecordType::A, Class::Internet)); 140 | 141 | let mut buf = [0; MESSAGE_LIMIT]; 142 | let msg = try!(self.send_message(&out_msg, &mut buf)); 143 | 144 | for rr in msg.answer.into_iter() { 145 | if rr.r_type == RecordType::A { 146 | let a = try!(rr.read_rdata::()); 147 | f(a.address); 148 | } 149 | } 150 | 151 | Ok(()) 152 | } 153 | 154 | fn resolve_host_v6(&self, host: &str, mut f: F) -> Result<(), Error> 155 | where F: FnMut(Ipv6Addr) { 156 | let mut out_msg = self.basic_message(); 157 | 158 | out_msg.question.push(Question::new( 159 | host.to_owned(), RecordType::AAAA, Class::Internet)); 160 | 161 | let mut buf = [0; MESSAGE_LIMIT]; 162 | let msg = try!(self.send_message(&out_msg, &mut buf)); 163 | 164 | for rr in msg.answer.into_iter() { 165 | if rr.r_type == RecordType::AAAA { 166 | let aaaa = try!(rr.read_rdata::()); 167 | f(aaaa.address); 168 | } 169 | } 170 | 171 | Ok(()) 172 | } 173 | 174 | fn basic_message(&self) -> Message { 175 | let mut msg = Message::new(); 176 | 177 | msg.header.recursion_desired = true; 178 | msg 179 | } 180 | 181 | /// Sends a message to the DNS server and attempts to read a response. 182 | pub fn send_message<'buf>(&self, out_msg: &Message, buf: &'buf mut [u8]) 183 | -> Result, Error> { 184 | let mut last_err = None; 185 | 186 | // FIXME(rust-lang/rust#21906): 187 | // Workaround for mutable borrow interfering with itself. 188 | // The drop probably isn't necessary, but it makes me feel better. 189 | let buf_ptr = buf as *mut _; 190 | drop(buf); 191 | 192 | 'retry: for retries in 0..self.config.attempts { 193 | let ns_addr = if self.config.rotate { 194 | self.next_nameserver() 195 | } else { 196 | let n = self.config.name_servers.len(); 197 | self.config.name_servers[retries as usize % n] 198 | }; 199 | 200 | let mut timeout = self.config.timeout; 201 | 202 | info!("resolver sending message to {}", ns_addr); 203 | 204 | try!(self.sock.send_message(out_msg, &ns_addr)); 205 | 206 | loop { 207 | try!(self.sock.get().set_read_timeout(Some(timeout))); 208 | 209 | // The other part of the aforementioned workaround. 210 | let buf = unsafe { &mut *buf_ptr }; 211 | 212 | let start = Instant::now(); 213 | 214 | match self.sock.recv_message(&ns_addr, buf) { 215 | Ok(None) => { 216 | let passed = start.elapsed(); 217 | 218 | // Maintain the right total timeout if we're interrupted 219 | // by irrelevant messages. 220 | if timeout < passed { 221 | timeout = Duration::from_secs(0); 222 | } else { 223 | timeout = timeout - passed; 224 | } 225 | } 226 | Ok(Some(msg)) => { 227 | // Ignore irrelevant messages 228 | if msg.header.id == out_msg.header.id && 229 | msg.header.qr == Qr::Response { 230 | try!(msg.get_error()); 231 | return Ok(msg); 232 | } 233 | } 234 | Err(e) => { 235 | // Retry on timeout 236 | if e.is_timeout() { 237 | last_err = Some(e); 238 | continue 'retry; 239 | } 240 | // Immediately bail for other errors 241 | return Err(e); 242 | } 243 | } 244 | } 245 | } 246 | 247 | Err(last_err.unwrap()) 248 | } 249 | 250 | fn next_nameserver(&self) -> SocketAddr { 251 | let n = self.next_ns.get(); 252 | self.next_ns.set((n + 1) % self.config.name_servers.len()); 253 | self.config.name_servers[n] 254 | } 255 | } 256 | 257 | fn bind_addr(name_servers: &[SocketAddr]) -> IpAddr { 258 | match name_servers.first() { 259 | Some(&SocketAddr::V6(_)) => IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 260 | _ => IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)) 261 | } 262 | } 263 | 264 | fn convert_error(desc: &str, f: F) -> io::Result 265 | where F: FnOnce() -> Result { 266 | match f() { 267 | Ok(t) => Ok(t), 268 | Err(Error::IoError(e)) => Err(e), 269 | Err(e) => Err(io::Error::new( 270 | io::ErrorKind::Other, format!("{}: {}", desc, e))) 271 | } 272 | } 273 | 274 | fn query_names(name: &str, config: &DnsConfig, mut f: F) -> Result 275 | where F: FnMut(String) -> Result { 276 | let use_search = !name.ends_with('.') && 277 | name.chars().filter(|&c| c == '.') 278 | .count() as u32 >= config.n_dots; 279 | 280 | if use_search { 281 | let mut err = None; 282 | 283 | for name in with_suffixes(name, &config.search) { 284 | match f(name) { 285 | Ok(t) => return Ok(t), 286 | Err(e) => err = Some(e) 287 | } 288 | } 289 | 290 | if let Some(e) = err { 291 | Err(e) 292 | } else { 293 | Err(Error::IoError(io::Error::new(io::ErrorKind::Other, 294 | "failed to resolve host: name not found"))) 295 | } 296 | } else { 297 | f(name.to_owned()) 298 | } 299 | } 300 | 301 | fn with_suffixes(host: &str, suffixes: &[String]) -> Vec { 302 | let mut v = suffixes.iter() 303 | .map(|s| format!("{}.{}", host, s)).collect::>(); 304 | v.push(host.to_owned()); 305 | v 306 | } 307 | 308 | /// Resolves an IPv4 or IPv6 address to a hostname. 309 | pub fn resolve_addr(addr: &IpAddr) -> io::Result { 310 | let r = try!(DnsResolver::new(try!(DnsConfig::load_default()))); 311 | r.resolve_addr(addr) 312 | } 313 | 314 | /// Resolves a hostname to one or more IPv4 or IPv6 addresses. 315 | /// 316 | /// # Example 317 | /// 318 | /// ```no_run 319 | /// use resolve::resolve_host; 320 | /// # use std::io; 321 | /// 322 | /// # fn _foo() -> io::Result<()> { 323 | /// for addr in try!(resolve_host("rust-lang.org")) { 324 | /// println!("found address: {}", addr); 325 | /// } 326 | /// # Ok(()) 327 | /// # } 328 | /// ``` 329 | pub fn resolve_host(host: &str) -> io::Result { 330 | let r = try!(DnsResolver::new(try!(DnsConfig::load_default()))); 331 | r.resolve_host(host) 332 | } 333 | 334 | /// Yields a series of `IpAddr` values from `resolve_host`. 335 | pub struct ResolveHost(IntoIter); 336 | 337 | impl Iterator for ResolveHost { 338 | type Item = IpAddr; 339 | 340 | fn next(&mut self) -> Option { 341 | self.0.next() 342 | } 343 | } 344 | -------------------------------------------------------------------------------- /src/message.rs: -------------------------------------------------------------------------------- 1 | //! Utilities for composing, decoding, and encoding messages. 2 | 3 | use std::borrow::Cow::{self, Borrowed, Owned}; 4 | use std::cell::Cell; 5 | use std::default::Default; 6 | use std::fmt; 7 | use std::io::{Cursor, Read, Write}; 8 | use std::mem::{transmute, zeroed}; 9 | use std::slice::Iter; 10 | use std::str::from_utf8_unchecked; 11 | use std::vec::IntoIter; 12 | 13 | use rand::random; 14 | 15 | use idna; 16 | use record::{Class, Record, RecordType}; 17 | 18 | /// Maximum size of a DNS message, in bytes. 19 | pub const MESSAGE_LIMIT: usize = 0xffff; 20 | 21 | /// Maximum length of a name segment (i.e. a `.`-separated identifier). 22 | pub const LABEL_LIMIT: usize = 63; 23 | 24 | /// Maximum total length of a name, in encoded format. 25 | pub const NAME_LIMIT: usize = 255; 26 | 27 | /// An error response code received in a response message. 28 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 29 | pub struct DnsError(pub RCode); 30 | 31 | impl fmt::Display for DnsError { 32 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 33 | f.write_str(self.0.get_error()) 34 | } 35 | } 36 | 37 | /// Represents an error in decoding a DNS message. 38 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 39 | pub enum DecodeError { 40 | /// Extraneous data encountered at the end of message 41 | ExtraneousData, 42 | /// Message end was encountered before expected 43 | ShortMessage, 44 | /// Unable to decode invalid data 45 | InvalidMessage, 46 | /// An invalid name was encountered 47 | InvalidName, 48 | } 49 | 50 | impl fmt::Display for DecodeError { 51 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 52 | f.write_str(match *self { 53 | DecodeError::ExtraneousData => "extraneous data", 54 | DecodeError::ShortMessage => "short message", 55 | DecodeError::InvalidMessage => "invalid message", 56 | DecodeError::InvalidName => "invalid name", 57 | }) 58 | } 59 | } 60 | 61 | /// Represents an error in encoding a DNS message. 62 | #[derive(Clone, Debug, Eq, PartialEq)] 63 | pub enum EncodeError { 64 | /// A name or label was too long or contained invalid characters 65 | InvalidName, 66 | /// Message exceeded given buffer or `MESSAGE_LIMIT` bytes 67 | TooLong, 68 | } 69 | 70 | impl fmt::Display for EncodeError { 71 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 72 | match *self { 73 | EncodeError::InvalidName => f.write_str("invalid name value"), 74 | EncodeError::TooLong => f.write_str("message too long"), 75 | } 76 | } 77 | } 78 | 79 | /// Reads a single DNS message from a series of bytes. 80 | pub struct MsgReader<'a> { 81 | data: Cursor<&'a [u8]>, 82 | } 83 | 84 | impl<'a> MsgReader<'a> { 85 | /// Constructs a new message reader. 86 | pub fn new(data: &[u8]) -> MsgReader { 87 | MsgReader{data: Cursor::new(data)} 88 | } 89 | 90 | /// Constructs a new message reader, which will read from `data`, 91 | /// beginning at `offset`. 92 | pub fn with_offset(data: &[u8], offset: usize) -> MsgReader { 93 | let mut cur = Cursor::new(data); 94 | cur.set_position(offset as u64); 95 | MsgReader{data: cur} 96 | } 97 | 98 | /// Returns the number of bytes remaining in the message. 99 | pub fn remaining(&self) -> usize { 100 | self.data.get_ref().len() - self.data.position() as usize 101 | } 102 | 103 | /// Reads a number of bytes equal to the length of the given buffer. 104 | /// Returns `Err(ShortMessage)` if there are not enough bytes remaining. 105 | pub fn read(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> { 106 | match self.data.read(buf) { 107 | Ok(n) if n == buf.len() => Ok(()), 108 | _ => Err(DecodeError::ShortMessage), 109 | } 110 | } 111 | 112 | /// Reads a single byte from the message. 113 | pub fn read_byte(&mut self) -> Result { 114 | let mut buf = [0]; 115 | try!(self.read(&mut buf)); 116 | Ok(buf[0]) 117 | } 118 | 119 | /// Reads all remaining bytes. 120 | pub fn read_to_end(&mut self) -> Result, DecodeError> { 121 | let mut res = Vec::with_capacity(self.remaining()); 122 | res.resize(self.remaining(), 0); 123 | try!(self.read(&mut res)); 124 | Ok(res) 125 | } 126 | 127 | /// Read a character-string. 128 | /// 129 | /// According to RFC 1035: 130 | /// 131 | /// > is a single length octet followed 132 | /// > by that number of characters. is 133 | /// > treated as binary information, and can be up to 256 134 | /// > characters in length (including the length octet). 135 | pub fn read_character_string(&mut self) -> Result, DecodeError> { 136 | let length_octet = try!(self.read_byte()) as usize; 137 | let mut res = Vec::with_capacity(length_octet); 138 | res.resize(length_octet, 0); 139 | try!(self.read(&mut res)); 140 | Ok(res) 141 | } 142 | 143 | /// Reads a big-endian unsigned 16 bit integer. 144 | pub fn read_u16(&mut self) -> Result { 145 | let mut buf = [0; 2]; 146 | try!(self.read(&mut buf)); 147 | Ok(u16::from_be(unsafe { transmute(buf) })) 148 | } 149 | 150 | /// Reads a big-endian unsigned 32 bit integer. 151 | pub fn read_u32(&mut self) -> Result { 152 | let mut buf = [0; 4]; 153 | try!(self.read(&mut buf)); 154 | Ok(u32::from_be(unsafe { transmute(buf) })) 155 | } 156 | 157 | /// Reads `n` bytes, which are inserted at the end of the given buffer. 158 | pub fn read_into(&mut self, buf: &mut Vec, n: usize) -> Result<(), DecodeError> { 159 | let len = buf.len(); 160 | buf.resize(len + n, 0); 161 | self.read(&mut buf[len..]) 162 | } 163 | 164 | /// Reads a name from the message. 165 | pub fn read_name(&mut self) -> Result { 166 | // Start position, used to check against pointer references 167 | let start_pos = self.data.position(); 168 | // Offset to return to if we've finished parsing a pointer reference 169 | let mut restore = None; 170 | 171 | let mut res = String::new(); 172 | let mut total_read = 0; 173 | 174 | loop { 175 | let len = try!(self.read_byte()); 176 | 177 | if len == 0 { 178 | if total_read + 1 > NAME_LIMIT { 179 | return Err(DecodeError::InvalidName); 180 | } 181 | break; 182 | } 183 | 184 | // If the length flag starts with "11", it will be followed by a 185 | // pointer reference. For more information see RFC 1035 section 186 | // 4.1.4 (Message compression). 187 | // Prefix "00" means "no compression". Prefixes 0x01 and 0x10 188 | // are reserved for future use. 189 | let compressed = match len >> 6 { 190 | 0b11 => true, 191 | 0b00 => false, 192 | _ => return Err(DecodeError::InvalidMessage), 193 | }; 194 | 195 | if compressed { 196 | // The beginning of a pointer reference. 14 bit denote the 197 | // offset from the start of the message. 198 | let hi = (len & 0b00111111) as u64; 199 | let lo = try!(self.read_byte()) as u64; 200 | let offset = (hi << 8) | lo; 201 | 202 | // To prevent an infinite loop, we require the pointer to 203 | // point before the start of this name. 204 | if offset >= start_pos { 205 | return Err(DecodeError::InvalidName); 206 | } 207 | 208 | if restore.is_none() { 209 | restore = Some(self.data.position()); 210 | } 211 | 212 | self.data.set_position(offset); 213 | continue; 214 | } 215 | 216 | if total_read + 1 + len as usize > NAME_LIMIT { 217 | return Err(DecodeError::InvalidName); 218 | } 219 | total_read += 1 + len as usize; 220 | 221 | try!(self.read_segment(&mut res, len as usize)); 222 | } 223 | 224 | if res.is_empty() { 225 | res.push('.'); 226 | } else { 227 | res.shrink_to_fit(); 228 | } 229 | 230 | if let Some(pos) = restore { 231 | self.data.set_position(pos); 232 | } 233 | 234 | Ok(res) 235 | } 236 | 237 | fn read_segment(&mut self, buf: &mut String, len: usize) -> Result<(), DecodeError> { 238 | let mut bytes = [0; 64]; 239 | 240 | try!(self.read(&mut bytes[..len])); 241 | 242 | let seg = &bytes[..len]; 243 | 244 | if !seg.is_ascii() { 245 | return Err(DecodeError::InvalidName); 246 | } 247 | 248 | // We just verified this was ASCII, so it's safe. 249 | let s = unsafe { from_utf8_unchecked(seg) }; 250 | 251 | if !is_valid_segment(s) { 252 | return Err(DecodeError::InvalidName); 253 | } 254 | 255 | let label = match idna::to_unicode(s) { 256 | Ok(s) => s, 257 | Err(_) => return Err(DecodeError::InvalidName) 258 | }; 259 | 260 | buf.push_str(&label); 261 | buf.push('.'); 262 | Ok(()) 263 | } 264 | 265 | fn consume(&mut self, n: u64) { 266 | let p = self.data.position(); 267 | self.data.set_position(p + n); 268 | } 269 | 270 | /// Called at the end of message parsing. Returns `Err(ExtraneousData)` 271 | /// if there are any unread bytes remaining. 272 | fn finish(self) -> Result<(), DecodeError> { 273 | if self.remaining() == 0 { 274 | Ok(()) 275 | } else { 276 | Err(DecodeError::ExtraneousData) 277 | } 278 | } 279 | 280 | /// Reads a message header 281 | fn read_header(&mut self) -> Result { 282 | let mut buf = [0; 12]; 283 | 284 | try!(self.read(&mut buf)); 285 | 286 | let hdr: HeaderData = unsafe { transmute(buf) }; 287 | 288 | let id = u16::from_be(hdr.id); 289 | 290 | // 1 bit: query or response flag 291 | let qr = hdr.flags0 & 0b10000000; 292 | // 4 bits: opcode 293 | let op = hdr.flags0 & 0b01111000; 294 | // 1 bit: authoritative answer flag 295 | let aa = hdr.flags0 & 0b00000100; 296 | // 1 bit: truncation flag 297 | let tc = hdr.flags0 & 0b00000010; 298 | // 1 bit: recursion desired flag 299 | let rd = hdr.flags0 & 0b00000001; 300 | 301 | // 1 bit: recursion available flag 302 | let ra = hdr.flags1 & 0b10000000; 303 | // 3 bits: reserved for future use 304 | // = hdr.flags1 & 0b01110000; 305 | // 4 bits: response code 306 | let rc = hdr.flags1 & 0b00001111; 307 | 308 | let qd_count = u16::from_be(hdr.qd_count); 309 | let an_count = u16::from_be(hdr.an_count); 310 | let ns_count = u16::from_be(hdr.ns_count); 311 | let ar_count = u16::from_be(hdr.ar_count); 312 | 313 | Ok(FullHeader{ 314 | id: id, 315 | qr: if qr == 0 { Qr::Query } else { Qr::Response }, 316 | op: OpCode::from_u8(op), 317 | authoritative: aa != 0, 318 | truncated: tc != 0, 319 | recursion_desired: rd != 0, 320 | recursion_available: ra != 0, 321 | rcode: RCode::from_u8(rc), 322 | qd_count: qd_count, 323 | an_count: an_count, 324 | ns_count: ns_count, 325 | ar_count: ar_count, 326 | }) 327 | } 328 | 329 | /// Reads a question item 330 | fn read_question(&mut self) -> Result { 331 | let name = try!(self.read_name()); 332 | 333 | let mut buf = [0; 4]; 334 | 335 | try!(self.read(&mut buf)); 336 | 337 | let msg: QuestionData = unsafe { transmute(buf) }; 338 | 339 | let q_type = u16::from_be(msg.q_type); 340 | let q_class = u16::from_be(msg.q_class); 341 | 342 | Ok(Question{ 343 | name: name, 344 | q_type: RecordType::from_u16(q_type), 345 | q_class: Class::from_u16(q_class), 346 | }) 347 | } 348 | 349 | /// Reads a resource record item 350 | fn read_resource(&mut self) -> Result, DecodeError> { 351 | let name = try!(self.read_name()); 352 | 353 | let mut buf = [0; 10]; 354 | 355 | try!(self.read(&mut buf)); 356 | 357 | let msg: ResourceData = unsafe { transmute(buf) }; 358 | 359 | let r_type = u16::from_be(msg.r_type); 360 | let r_class = u16::from_be(msg.r_class); 361 | let ttl = u32::from_be(msg.ttl); 362 | let length = u16::from_be(msg.length); 363 | 364 | let data = *self.data.get_ref(); 365 | let offset = self.data.position() as usize; 366 | 367 | let r_data = &data[..offset + length as usize]; 368 | self.consume(length as u64); 369 | 370 | Ok(Resource{ 371 | name: name, 372 | r_type: RecordType::from_u16(r_type), 373 | r_class: Class::from_u16(r_class), 374 | ttl: ttl, 375 | data: Borrowed(r_data), 376 | offset: offset, 377 | }) 378 | } 379 | } 380 | 381 | /// Writes a single DNS message as a series of bytes. 382 | pub struct MsgWriter<'a> { 383 | data: Cursor<&'a mut [u8]>, 384 | } 385 | 386 | impl<'a> MsgWriter<'a> { 387 | /// Constructs a new message writer that will write into the given byte slice. 388 | pub fn new(data: &mut [u8]) -> MsgWriter { 389 | MsgWriter{data: Cursor::new(data)} 390 | } 391 | 392 | /// Returns the number of bytes written so far. 393 | pub fn written(&self) -> usize { 394 | self.data.position() as usize 395 | } 396 | 397 | /// Returns a subslice of the wrapped byte slice that contains only the 398 | /// bytes written. 399 | pub fn into_bytes(self) -> &'a [u8] { 400 | let n = self.written(); 401 | &self.data.into_inner()[..n] 402 | } 403 | 404 | /// Writes a series of bytes to the message. Returns `Err(TooLong)` if the 405 | /// whole buffer cannot be written. 406 | pub fn write(&mut self, data: &[u8]) -> Result<(), EncodeError> { 407 | if self.written() + data.len() > MESSAGE_LIMIT { 408 | // No matter the size of the buffer, 409 | // we always want to stop at the hard-coded message limit. 410 | Err(EncodeError::TooLong) 411 | } else { 412 | self.data.write_all(data).map_err(|_| EncodeError::TooLong) 413 | } 414 | } 415 | 416 | /// Write a character string, as defined by RFC 1035. 417 | pub fn write_character_string(&mut self, data: &[u8]) -> Result<(), EncodeError> { 418 | let len = data.len(); 419 | 420 | if len > 255 { 421 | Err(EncodeError::TooLong) 422 | } else { 423 | try!(self.write_byte(len as u8)); 424 | self.write(data) 425 | } 426 | } 427 | 428 | /// Writes a name to the message. 429 | pub fn write_name(&mut self, name: &str) -> Result<(), EncodeError> { 430 | if !is_valid_name(name) { 431 | Err(EncodeError::InvalidName) 432 | } else if name == "." { 433 | self.write_byte(0) 434 | } else { 435 | let mut total_len = 0; 436 | 437 | for seg in name.split('.') { 438 | let seg = match idna::to_ascii(seg) { 439 | Ok(seg) => seg, 440 | Err(_) => return Err(EncodeError::InvalidName) 441 | }; 442 | 443 | if !is_valid_segment(&seg) { 444 | return Err(EncodeError::InvalidName); 445 | } 446 | 447 | if seg.len() > LABEL_LIMIT { 448 | return Err(EncodeError::InvalidName); 449 | } 450 | 451 | // Add the size octet and the segment length 452 | total_len += 1 + seg.len(); 453 | 454 | if total_len > NAME_LIMIT { 455 | return Err(EncodeError::InvalidName); 456 | } 457 | 458 | try!(self.write_byte(seg.len() as u8)); 459 | try!(self.write(seg.as_bytes())); 460 | } 461 | 462 | if !name.ends_with('.') { 463 | if total_len + 1 > NAME_LIMIT { 464 | return Err(EncodeError::InvalidName); 465 | } 466 | try!(self.write_byte(0)); 467 | } 468 | 469 | Ok(()) 470 | } 471 | } 472 | 473 | /// Writes a single byte to the message. 474 | pub fn write_byte(&mut self, data: u8) -> Result<(), EncodeError> { 475 | self.write(&[data]) 476 | } 477 | 478 | /// Writes an unsigned 16 bit integer in big-endian format. 479 | pub fn write_u16(&mut self, data: u16) -> Result<(), EncodeError> { 480 | let data: [u8; 2] = unsafe { transmute(data.to_be()) }; 481 | self.write(&data) 482 | } 483 | 484 | /// Writes an unsigned 32 bit integer in big-endian format. 485 | pub fn write_u32(&mut self, data: u32) -> Result<(), EncodeError> { 486 | let data: [u8; 4] = unsafe { transmute(data.to_be()) }; 487 | self.write(&data) 488 | } 489 | 490 | /// Writes a message header 491 | fn write_header(&mut self, header: &FullHeader) -> Result<(), EncodeError> { 492 | let mut hdr: HeaderData = unsafe { zeroed() }; 493 | 494 | // 2 bytes: message ID 495 | hdr.id = header.id.to_be(); 496 | 497 | // 1 bit: query or response flag 498 | hdr.flags0 |= (header.qr as u8 & 1) << 7; 499 | // 4 bits: opcode 500 | hdr.flags0 |= (header.op.to_u8() & 0b1111) << 3; 501 | // 1 bit: authoritative answer flag 502 | hdr.flags0 |= (header.authoritative as u8) << 2; 503 | // 1 bit: truncation flag 504 | hdr.flags0 |= (header.truncated as u8) << 1; 505 | // 1 bit: recursion desired flag 506 | hdr.flags0 |= header.recursion_desired as u8; 507 | 508 | // 1 bit: recursion available flag 509 | hdr.flags1 |= (header.recursion_available as u8) << 7; 510 | // 3 bits: reserved for future use 511 | // .flags1 |= (0 as u8 & 0b111) << 4; 512 | // 4 bits: response code 513 | hdr.flags1 |= header.rcode.to_u8() & 0b1111; 514 | 515 | hdr.qd_count = header.qd_count.to_be(); 516 | hdr.an_count = header.an_count.to_be(); 517 | hdr.ns_count = header.ns_count.to_be(); 518 | hdr.ar_count = header.ar_count.to_be(); 519 | 520 | let buf: [u8; 12] = unsafe { transmute(hdr) }; 521 | 522 | self.write(&buf) 523 | } 524 | 525 | /// Writes a question item 526 | fn write_question(&mut self, question: &Question) -> Result<(), EncodeError> { 527 | try!(self.write_name(&question.name)); 528 | 529 | let mut qd: QuestionData = unsafe { zeroed() }; 530 | 531 | qd.q_type = question.q_type.to_u16().to_be(); 532 | qd.q_class = question.q_class.to_u16().to_be(); 533 | 534 | let buf: [u8; 4] = unsafe { transmute(qd) }; 535 | 536 | self.write(&buf) 537 | } 538 | 539 | /// Writes a resource record item 540 | fn write_resource(&mut self, resource: &Resource) -> Result<(), EncodeError> { 541 | try!(self.write_name(&resource.name)); 542 | 543 | let mut rd: ResourceData = unsafe { zeroed() }; 544 | 545 | let rdata = resource.get_rdata(); 546 | 547 | rd.r_type = resource.r_type.to_u16().to_be(); 548 | rd.r_class = resource.r_class.to_u16().to_be(); 549 | rd.ttl = resource.ttl.to_be(); 550 | rd.length = try!(to_u16(rdata.len())).to_be(); 551 | 552 | let buf: [u8; 10] = unsafe { transmute(rd) }; 553 | 554 | try!(self.write(&buf)); 555 | self.write(rdata) 556 | } 557 | } 558 | 559 | /// Returns a sequential ID value from a thread-local random starting value. 560 | pub fn generate_id() -> u16 { 561 | // It's not really necessary for these to be sequential, but it avoids the 562 | // 1-in-65536 chance of producing the same random number twice in a row. 563 | thread_local!(static ID: Cell = Cell::new(random())); 564 | ID.with(|id| { 565 | let value = id.get(); 566 | id.set(value.wrapping_add(1)); 567 | value 568 | }) 569 | } 570 | 571 | /// Returns whether the given string appears to be a valid hostname. 572 | /// The contents of the name (i.e. characters in labels) are not checked here; 573 | /// only the structure of the name is validated. 574 | fn is_valid_name(name: &str) -> bool { 575 | let len = name.len(); 576 | len != 0 && (len == 1 || !name.starts_with('.')) && !name.contains("..") 577 | } 578 | 579 | /// Returns whether the given string constitutes a valid name segment. 580 | /// This check is not as strict as internet DNS servers will be. It only checks 581 | /// for basic sanity of input. If an invalid name is given, a DNS server will 582 | /// respond that it doesn't exist, anyway. 583 | fn is_valid_segment(s: &str) -> bool { 584 | !(s.starts_with('-') || s.ends_with('-')) && 585 | s.chars().all(|c| !(c == '.' || c.is_whitespace() || c.is_control())) 586 | } 587 | 588 | /// Represents a DNS message. 589 | #[derive(Clone, Debug, Default, Eq, PartialEq)] 590 | pub struct Message<'a> { 591 | /// Describes the content of the remainder of the message. 592 | pub header: Header, 593 | /// Carries the question of query type messages. 594 | pub question: Vec, 595 | /// Resource records that answer the query 596 | pub answer: Vec>, 597 | /// Resource records that point to an authoritative name server 598 | pub authority: Vec>, 599 | /// Resource records that relate to the query, but are not strictly 600 | /// answers for the question. 601 | pub additional: Vec>, 602 | } 603 | 604 | impl<'a> Message<'a> { 605 | /// Constructs a new `Message` with a random id value. 606 | pub fn new() -> Message<'a> { 607 | Message{ 608 | header: Header::new(), 609 | ..Default::default() 610 | } 611 | } 612 | 613 | /// Constructs a new `Message` with the given id value. 614 | pub fn with_id(id: u16) -> Message<'a> { 615 | Message{ 616 | header: Header::with_id(id), 617 | ..Default::default() 618 | } 619 | } 620 | 621 | /// Decodes a message from a series of bytes. 622 | pub fn decode(data: &[u8]) -> Result { 623 | let mut r = MsgReader::new(data); 624 | 625 | let header = try!(r.read_header()); 626 | let mut msg = Message{ 627 | header: header.to_header(), 628 | // TODO: Cap these values to prevent abuse? 629 | question: Vec::with_capacity(header.qd_count as usize), 630 | answer: Vec::with_capacity(header.an_count as usize), 631 | authority: Vec::with_capacity(header.ns_count as usize), 632 | additional: Vec::with_capacity(header.ar_count as usize), 633 | }; 634 | 635 | for _ in 0..header.qd_count { 636 | msg.question.push(try!(r.read_question())); 637 | } 638 | 639 | for _ in 0..header.an_count { 640 | msg.answer.push(try!(r.read_resource())); 641 | } 642 | 643 | for _ in 0..header.ns_count { 644 | msg.authority.push(try!(r.read_resource())); 645 | } 646 | 647 | for _ in 0..header.ar_count { 648 | msg.additional.push(try!(r.read_resource())); 649 | } 650 | 651 | try!(r.finish()); 652 | Ok(msg) 653 | } 654 | 655 | /// Encodes a message to a series of bytes. On success, returns a subslice 656 | /// of the given buffer containing only the encoded message bytes. 657 | pub fn encode<'buf>(&self, buf: &'buf mut [u8]) -> Result<&'buf [u8], EncodeError> { 658 | let mut w = MsgWriter::new(buf); 659 | let hdr = &self.header; 660 | 661 | let header = FullHeader{ 662 | id: hdr.id, 663 | qr: hdr.qr, 664 | op: hdr.op, 665 | authoritative: hdr.authoritative, 666 | truncated: hdr.truncated, 667 | recursion_desired: hdr.recursion_desired, 668 | recursion_available: hdr.recursion_available, 669 | rcode: hdr.rcode, 670 | qd_count: try!(to_u16(self.question.len())), 671 | an_count: try!(to_u16(self.answer.len())), 672 | ns_count: try!(to_u16(self.authority.len())), 673 | ar_count: try!(to_u16(self.additional.len())), 674 | }; 675 | 676 | try!(w.write_header(&header)); 677 | 678 | for q in &self.question { 679 | try!(w.write_question(q)); 680 | } 681 | for r in &self.answer { 682 | try!(w.write_resource(r)); 683 | } 684 | for r in &self.authority { 685 | try!(w.write_resource(r)); 686 | } 687 | for r in &self.additional { 688 | try!(w.write_resource(r)); 689 | } 690 | 691 | Ok(w.into_bytes()) 692 | } 693 | 694 | /// Returns a `DnsError` if the message response code is an error. 695 | pub fn get_error(&self) -> Result<(), DnsError> { 696 | if self.header.rcode == RCode::NoError { 697 | Ok(()) 698 | } else { 699 | Err(DnsError(self.header.rcode)) 700 | } 701 | } 702 | 703 | /// Returns an iterator over the records in this message. 704 | pub fn records(&self) -> RecordIter { 705 | RecordIter{ 706 | iters: [ 707 | self.answer.iter(), 708 | self.authority.iter(), 709 | self.additional.iter(), 710 | ] 711 | } 712 | } 713 | 714 | /// Consumes the message and returns an iterator over its records. 715 | pub fn into_records(self) -> RecordIntoIter<'a> { 716 | RecordIntoIter{ 717 | iters: [ 718 | self.answer.into_iter(), 719 | self.authority.into_iter(), 720 | self.additional.into_iter(), 721 | ] 722 | } 723 | } 724 | } 725 | 726 | /// Yields `&Resource` items from a Message. 727 | pub struct RecordIter<'a> { 728 | iters: [Iter<'a, Resource<'a>>; 3], 729 | } 730 | 731 | impl<'a> Iterator for RecordIter<'a> { 732 | type Item = &'a Resource<'a>; 733 | 734 | fn next(&mut self) -> Option<&'a Resource<'a>> { 735 | self.iters[0].next() 736 | .or_else(|| self.iters[1].next()) 737 | .or_else(|| self.iters[2].next()) 738 | } 739 | } 740 | 741 | /// Yields `Resource` items from a Message. 742 | pub struct RecordIntoIter<'a> { 743 | iters: [IntoIter>; 3], 744 | } 745 | 746 | impl<'a> Iterator for RecordIntoIter<'a> { 747 | type Item = Resource<'a>; 748 | 749 | fn next(&mut self) -> Option> { 750 | self.iters[0].next() 751 | .or_else(|| self.iters[1].next()) 752 | .or_else(|| self.iters[2].next()) 753 | } 754 | } 755 | 756 | /// Represents a message header. 757 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 758 | pub struct Header { 759 | /// Transaction ID; corresponding replies will have the same ID. 760 | pub id: u16, 761 | /// Query or response 762 | pub qr: Qr, 763 | /// Kind of query 764 | pub op: OpCode, 765 | /// In a response, indicates that the responding name server is an authority 766 | /// for the domain name in question section. 767 | pub authoritative: bool, 768 | /// Indicates whether the message was truncated due to length greater than 769 | /// that permitted on the transmission channel. 770 | pub truncated: bool, 771 | /// In a query, directs the name server to pursue the query recursively. 772 | pub recursion_desired: bool, 773 | /// In a response, indicates whether recursive queries are available on the 774 | /// name server. 775 | pub recursion_available: bool, 776 | /// Response code 777 | pub rcode: RCode, 778 | } 779 | 780 | impl Header { 781 | /// Constructs a new `Header` with a random id value. 782 | pub fn new() -> Header { 783 | Header{ 784 | id: generate_id(), 785 | ..Default::default() 786 | } 787 | } 788 | 789 | /// Constructs a new `Header` with the given id value. 790 | pub fn with_id(id: u16) -> Header { 791 | Header{ 792 | id: id, 793 | ..Default::default() 794 | } 795 | } 796 | } 797 | 798 | impl Default for Header { 799 | fn default() -> Header { 800 | Header{ 801 | id: 0, 802 | qr: Qr::Query, 803 | op: OpCode::Query, 804 | authoritative: false, 805 | truncated: false, 806 | recursion_desired: false, 807 | recursion_available: false, 808 | rcode: RCode::NoError, 809 | } 810 | } 811 | } 812 | 813 | /// Contains all header data decoded from a message. 814 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 815 | struct FullHeader { 816 | pub id: u16, 817 | pub qr: Qr, 818 | pub op: OpCode, 819 | pub authoritative: bool, 820 | pub truncated: bool, 821 | pub recursion_desired: bool, 822 | pub recursion_available: bool, 823 | pub rcode: RCode, 824 | pub qd_count: u16, 825 | pub an_count: u16, 826 | pub ns_count: u16, 827 | pub ar_count: u16, 828 | } 829 | 830 | impl FullHeader { 831 | fn to_header(&self) -> Header { 832 | Header{ 833 | id: self.id, 834 | qr: self.qr, 835 | op: self.op, 836 | authoritative: self.authoritative, 837 | truncated: self.truncated, 838 | recursion_desired: self.recursion_desired, 839 | recursion_available: self.recursion_available, 840 | rcode: self.rcode, 841 | } 842 | } 843 | } 844 | 845 | impl Default for FullHeader { 846 | fn default() -> FullHeader { 847 | FullHeader{ 848 | id: 0, 849 | qr: Qr::Query, 850 | op: OpCode::Query, 851 | authoritative: false, 852 | truncated: false, 853 | recursion_desired: false, 854 | recursion_available: false, 855 | rcode: RCode::NoError, 856 | qd_count: 0, 857 | an_count: 0, 858 | ns_count: 0, 859 | ar_count: 0, 860 | } 861 | } 862 | } 863 | 864 | /// Represents a question item. 865 | #[derive(Clone, Debug, Eq, PartialEq)] 866 | pub struct Question { 867 | /// Query name 868 | pub name: String, 869 | /// Query type 870 | pub q_type: RecordType, 871 | /// Query class 872 | pub q_class: Class, 873 | } 874 | 875 | impl Question { 876 | /// Constructs a new `Question`. 877 | pub fn new(name: String, q_type: RecordType, q_class: Class) -> Question { 878 | Question{ 879 | name: name, 880 | q_type: q_type, 881 | q_class: q_class, 882 | } 883 | } 884 | } 885 | 886 | /// Represents a resource record item. 887 | #[derive(Clone, Debug, Eq, PartialEq)] 888 | pub struct Resource<'a> { 889 | /// Resource name 890 | pub name: String, 891 | /// Resource type 892 | pub r_type: RecordType, 893 | /// Resource class 894 | pub r_class: Class, 895 | /// Time-to-live 896 | pub ttl: u32, 897 | /// Message data, up to and including resource record data 898 | data: Cow<'a, [u8]>, 899 | /// Beginning of rdata within `data` 900 | offset: usize, 901 | } 902 | 903 | impl<'a> Resource<'a> { 904 | /// Constructs a new `Resource`. 905 | pub fn new(name: String, r_type: RecordType, 906 | r_class: Class, ttl: u32) -> Resource<'a> { 907 | Resource{ 908 | name: name, 909 | r_type: r_type, 910 | r_class: r_class, 911 | ttl: ttl, 912 | data: Owned(Vec::new()), 913 | offset: 0, 914 | } 915 | } 916 | 917 | /// Returns resource data. 918 | pub fn get_rdata(&self) -> &[u8] { 919 | &self.data[self.offset..] 920 | } 921 | 922 | /// Decodes resource data into the given `Record` type. 923 | pub fn read_rdata(&self) -> Result { 924 | let mut r = MsgReader::with_offset(&self.data, self.offset); 925 | let res = try!(Record::decode(&mut r)); 926 | try!(r.finish()); 927 | Ok(res) 928 | } 929 | 930 | /// Encodes resource data from the given `Record` type. 931 | pub fn write_rdata(&mut self, record: &R) -> Result<(), EncodeError> { 932 | let mut buf = [0; MESSAGE_LIMIT]; 933 | let mut w = MsgWriter::new(&mut buf[..]); 934 | try!(record.encode(&mut w)); 935 | self.data = Owned(w.into_bytes().to_vec()); 936 | self.offset = 0; 937 | Ok(()) 938 | } 939 | } 940 | 941 | /// Indicates a message is either a query or response. 942 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 943 | #[repr(u8)] 944 | pub enum Qr { 945 | /// Query 946 | Query = 0, 947 | /// Response 948 | Response = 1, 949 | } 950 | 951 | /// Represents the kind of message query. 952 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 953 | pub enum OpCode { 954 | /// Query 955 | Query, 956 | /// Status 957 | Status, 958 | /// Notify 959 | Notify, 960 | /// Update 961 | Update, 962 | /// Unrecognized opcode 963 | Other(u8), 964 | } 965 | 966 | impl OpCode { 967 | /// Converts a `u8` to an `OpCode`. 968 | pub fn from_u8(u: u8) -> OpCode { 969 | match u { 970 | 0 => OpCode::Query, 971 | 2 => OpCode::Status, 972 | 4 => OpCode::Notify, 973 | 5 => OpCode::Update, 974 | n => OpCode::Other(n), 975 | } 976 | } 977 | 978 | /// Converts an `OpCode` to a `u8`. 979 | pub fn to_u8(&self) -> u8 { 980 | match *self { 981 | OpCode::Query => 0, 982 | OpCode::Status => 2, 983 | OpCode::Notify => 4, 984 | OpCode::Update => 5, 985 | OpCode::Other(n) => n, 986 | } 987 | } 988 | } 989 | 990 | /// Represents the response code of a message 991 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 992 | pub enum RCode { 993 | /// No error condition. 994 | NoError, 995 | /// The server was unable to interpret the query. 996 | FormatError, 997 | /// The name server was unable to process the query due to a failure of 998 | /// the name server. 999 | ServerFailure, 1000 | /// Name referenced in query does not exist. 1001 | NameError, 1002 | /// Requested query kind is not supported by name server. 1003 | NotImplemented, 1004 | /// The name server refuses to perform the specified operation for policy 1005 | /// reasons. 1006 | Refused, 1007 | /// Unknown response code. 1008 | Other(u8), 1009 | } 1010 | 1011 | impl RCode { 1012 | /// Returns an error string for the response code. 1013 | pub fn get_error(&self) -> &'static str { 1014 | match *self { 1015 | RCode::NoError => "no error", 1016 | RCode::FormatError => "format error", 1017 | RCode::ServerFailure => "server failure", 1018 | RCode::NameError => "no such name", 1019 | RCode::NotImplemented => "not implemented", 1020 | RCode::Refused => "refused", 1021 | RCode::Other(_) => "unknown response code", 1022 | } 1023 | } 1024 | 1025 | /// Converts a `u8` to an `RCode`. 1026 | pub fn from_u8(u: u8) -> RCode { 1027 | match u { 1028 | 0 => RCode::NoError, 1029 | 1 => RCode::FormatError, 1030 | 2 => RCode::ServerFailure, 1031 | 3 => RCode::NameError, 1032 | 4 => RCode::NotImplemented, 1033 | 5 => RCode::Refused, 1034 | n => RCode::Other(n), 1035 | } 1036 | } 1037 | 1038 | /// Converts an `RCode` to a `u8`. 1039 | pub fn to_u8(&self) -> u8 { 1040 | match *self { 1041 | RCode::NoError => 0, 1042 | RCode::FormatError => 1, 1043 | RCode::ServerFailure => 2, 1044 | RCode::NameError => 3, 1045 | RCode::NotImplemented => 4, 1046 | RCode::Refused => 5, 1047 | RCode::Other(n) => n, 1048 | } 1049 | } 1050 | } 1051 | 1052 | #[derive(Copy, Clone, Debug)] 1053 | #[repr(C, packed)] 1054 | struct HeaderData { 1055 | id: u16, 1056 | flags0: u8, 1057 | flags1: u8, 1058 | qd_count: u16, 1059 | an_count: u16, 1060 | ns_count: u16, 1061 | ar_count: u16, 1062 | } 1063 | 1064 | #[derive(Copy, Clone, Debug)] 1065 | #[repr(C, packed)] 1066 | struct QuestionData { 1067 | // name: String, -- dynamically sized 1068 | q_type: u16, 1069 | q_class: u16, 1070 | } 1071 | 1072 | #[derive(Copy, Clone, Debug)] 1073 | #[repr(C, packed)] 1074 | struct ResourceData { 1075 | // name: String, -- dynamically sized 1076 | r_type: u16, 1077 | r_class: u16, 1078 | ttl: u32, 1079 | length: u16, 1080 | } 1081 | 1082 | fn to_u16(n: usize) -> Result { 1083 | if n > u16::max_value() as usize { 1084 | Err(EncodeError::TooLong) 1085 | } else { 1086 | Ok(n as u16) 1087 | } 1088 | } 1089 | 1090 | #[cfg(test)] 1091 | mod test { 1092 | use super::{is_valid_name, EncodeError, MESSAGE_LIMIT}; 1093 | use super::{Header, Message, Question, Qr, OpCode, RCode}; 1094 | use super::{MsgReader, MsgWriter}; 1095 | use record::{Class, RecordType}; 1096 | 1097 | #[test] 1098 | fn test_idna_name() { 1099 | let mut buf = [0; 64]; 1100 | let mut w = MsgWriter::new(&mut buf); 1101 | 1102 | w.write_name("bücher.de.").unwrap(); 1103 | w.write_name("ουτοπία.δπθ.gr.").unwrap(); 1104 | 1105 | let bytes = w.into_bytes(); 1106 | 1107 | assert_eq!(bytes, &b"\ 1108 | \x0dxn--bcher-kva\x02de\x00\ 1109 | \x0exn--kxae4bafwg\x09xn--pxaix\x02gr\x00\ 1110 | "[..]); 1111 | 1112 | let mut r = MsgReader::new(&bytes); 1113 | 1114 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok("bücher.de.")); 1115 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok("ουτοπία.δπθ.gr.")); 1116 | } 1117 | 1118 | #[test] 1119 | fn test_message() { 1120 | let msg = Message{ 1121 | header: Header{ 1122 | id: 0xabcd, 1123 | qr: Qr::Query, 1124 | op: OpCode::Query, 1125 | authoritative: false, 1126 | truncated: false, 1127 | recursion_desired: true, 1128 | recursion_available: true, 1129 | rcode: RCode::NoError, 1130 | }, 1131 | question: vec![ 1132 | Question::new("foo.bar.com.".to_owned(), 1133 | RecordType::A, Class::Internet) 1134 | ], 1135 | answer: Vec::new(), 1136 | authority: Vec::new(), 1137 | additional: Vec::new(), 1138 | }; 1139 | 1140 | let mut buf = [0; 64]; 1141 | let bytes = msg.encode(&mut buf).unwrap(); 1142 | 1143 | assert_eq!(bytes, 1144 | &[0xab, 0xcd, 1145 | 0b00000001, 0b10000000, 1146 | 0, 1, 0, 0, 0, 0, 0, 0, 1147 | 3, b'f', b'o', b'o', 1148 | 3, b'b', b'a', b'r', 1149 | 3, b'c', b'o', b'm', 0, 1150 | 0, 1, 0, 1][..]); 1151 | 1152 | let msg2 = Message::decode(&bytes).unwrap(); 1153 | 1154 | assert_eq!(msg, msg2); 1155 | } 1156 | 1157 | #[test] 1158 | fn test_primitives() { 1159 | let mut buf = [0; 64]; 1160 | let mut w = MsgWriter::new(&mut buf); 1161 | 1162 | w.write_byte(0x11).unwrap(); 1163 | w.write_u16(0x2233).unwrap(); 1164 | w.write_u32(0x44556677).unwrap(); 1165 | w.write_name("alpha.bravo.charlie").unwrap(); 1166 | w.write_name("delta.echo.foxtrot.").unwrap(); 1167 | w.write_name(".").unwrap(); 1168 | 1169 | assert_eq!(w.write_name(""), Err(EncodeError::InvalidName)); 1170 | assert_eq!(w.write_name( 1171 | "ohmyglobhowdidthisgethereiamnotgoodwithcomputerrrrrrrrrrrrrrrrrr.org"), 1172 | Err(EncodeError::InvalidName)); 1173 | 1174 | let bytes = w.into_bytes(); 1175 | 1176 | assert_eq!(bytes, &b"\ 1177 | \x11\ 1178 | \x22\x33\ 1179 | \x44\x55\x66\x77\ 1180 | \x05alpha\x05bravo\x07charlie\x00\ 1181 | \x05delta\x04echo\x07foxtrot\x00\ 1182 | \x00"[..]); 1183 | 1184 | let mut r = MsgReader::new(&bytes); 1185 | 1186 | assert_eq!(r.read_byte(), Ok(0x11)); 1187 | assert_eq!(r.read_u16(), Ok(0x2233)); 1188 | assert_eq!(r.read_u32(), Ok(0x44556677)); 1189 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok("alpha.bravo.charlie.")); 1190 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok("delta.echo.foxtrot.")); 1191 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok(".")); 1192 | } 1193 | 1194 | const LONGEST_NAME: &'static str = 1195 | "aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1196 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1197 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1198 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1199 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaa\ 1200 | .com"; 1201 | const LONGEST_NAME_DOT: &'static str = 1202 | "aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1203 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1204 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1205 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1206 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaa\ 1207 | .com."; 1208 | const TOO_LONG_NAME: &'static str = 1209 | "aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1210 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1211 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1212 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1213 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1214 | .com"; 1215 | const TOO_LONG_NAME_DOT: &'static str = 1216 | "aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1217 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1218 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1219 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1220 | aaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaa\ 1221 | .com."; 1222 | const TOO_LONG_SEGMENT: &'static str = 1223 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ 1224 | aaaaaaaaaaaaaa.com"; 1225 | 1226 | #[test] 1227 | fn test_encode_name() { 1228 | let mut buf = [0; MESSAGE_LIMIT]; 1229 | let mut w = MsgWriter::new(&mut buf); 1230 | 1231 | w.write_name(LONGEST_NAME).unwrap(); 1232 | w.write_name(LONGEST_NAME_DOT).unwrap(); 1233 | 1234 | let bytes = w.into_bytes(); 1235 | let mut r = MsgReader::new(&bytes); 1236 | 1237 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok(LONGEST_NAME_DOT)); 1238 | assert_eq!(r.read_name().as_ref().map(|s| &s[..]), Ok(LONGEST_NAME_DOT)); 1239 | 1240 | let mut buf = [0; MESSAGE_LIMIT]; 1241 | let mut w = MsgWriter::new(&mut buf); 1242 | 1243 | assert_eq!(w.write_name(TOO_LONG_NAME), Err(EncodeError::InvalidName)); 1244 | assert_eq!(w.write_name(TOO_LONG_NAME_DOT), Err(EncodeError::InvalidName)); 1245 | assert_eq!(w.write_name(TOO_LONG_SEGMENT), Err(EncodeError::InvalidName)); 1246 | } 1247 | 1248 | #[test] 1249 | fn test_valid_name() { 1250 | assert!(is_valid_name(".")); 1251 | assert!(is_valid_name("foo.com.")); 1252 | assert!(is_valid_name("foo-123.com.")); 1253 | assert!(is_valid_name("FOO-BAR.COM")); 1254 | 1255 | assert!(!is_valid_name("")); 1256 | assert!(!is_valid_name(".foo.com")); 1257 | assert!(!is_valid_name("foo..bar.com")); 1258 | } 1259 | } 1260 | --------------------------------------------------------------------------------