resolv_conf

Struct Config

Source
pub struct Config {
Show 20 fields pub nameservers: Vec<ScopedIp>, pub sortlist: Vec<Network>, pub debug: bool, pub ndots: u32, pub timeout: u32, pub attempts: u32, pub rotate: bool, pub no_check_names: bool, pub inet6: bool, pub ip6_bytestring: bool, pub ip6_dotint: bool, pub edns0: bool, pub single_request: bool, pub single_request_reopen: bool, pub no_tld_query: bool, pub use_vc: bool, pub no_reload: bool, pub trust_ad: bool, pub lookup: Vec<Lookup>, pub family: Vec<Family>, /* private fields */
}
Expand description

Represent a resolver configuration, as described in man 5 resolv.conf. The options and defaults match those in the linux man page.

Note: while most fields in the structure are public the search and domain fields must be accessed via methods. This is because there are few different ways to treat domain field. In GNU libc search and domain replace each other (get_last_search_or_domain). In MacOS /etc/resolve/* files domain is treated in entirely different way.

Also consider using glibc_normalize and get_system_domain to match behavior of GNU libc. (latter requires system feature enabled)

extern crate resolv_conf;

use std::net::Ipv4Addr;
use resolv_conf::{Config, ScopedIp};

fn main() {
    // Create a new config
    let mut config = Config::new();
    config.nameservers.push(ScopedIp::V4(Ipv4Addr::new(8, 8, 8, 8)));
    config.set_search(vec!["example.com".into()]);

    // Parse a config
    let parsed = Config::parse("nameserver 8.8.8.8\nsearch example.com").unwrap();
    assert_eq!(parsed, config);
}

Fields§

§nameservers: Vec<ScopedIp>

List of nameservers

§sortlist: Vec<Network>

List of preferred addresses

§debug: bool

Enable DNS resolve debugging

§ndots: u32

Number of dots in name to try absolute resolving first (default 1)

§timeout: u32

Dns query timeout (default 5 [sec])

§attempts: u32

Number of attempts to resolve name if server is inaccesible (default 2)

§rotate: bool

Round-robin selection of servers (default false)

§no_check_names: bool

Don’t check names for validity (default false)

§inet6: bool

Try AAAA query before A

§ip6_bytestring: bool

Use reverse lookup of ipv6 using bit-label format described instead of nibble format

§ip6_dotint: bool

Do ipv6 reverse lookups in ip6.int zone instead of ip6.arpa (default false)

§edns0: bool

Enable dns extensions described in RFC 2671

§single_request: bool

Don’t make ipv4 and ipv6 requests simultaneously

§single_request_reopen: bool

Use same socket for the A and AAAA requests

§no_tld_query: bool

Don’t resolve unqualified name as top level domain

§use_vc: bool

Force using TCP for DNS resolution

§no_reload: bool

Disable the automatic reloading of a changed configuration file

§trust_ad: bool

Optionally send the AD (authenticated data) bit in queries

§lookup: Vec<Lookup>

The order in which databases should be searched during a lookup (openbsd-only)

§family: Vec<Family>

The order in which internet protocol families should be prefered (openbsd-only)

Implementations§

Source§

impl Config

Source

pub fn new() -> Config

Create a new Config object with default values.

use resolv_conf::Config;
let config = Config::new();
assert_eq!(config.nameservers, vec![]);
assert!(config.get_domain().is_none());
assert!(config.get_search().is_none());
assert_eq!(config.sortlist, vec![]);
assert_eq!(config.debug, false);
assert_eq!(config.ndots, 1);
assert_eq!(config.timeout, 5);
assert_eq!(config.attempts, 2);
assert_eq!(config.rotate, false);
assert_eq!(config.no_check_names, false);
assert_eq!(config.inet6, false);
assert_eq!(config.ip6_bytestring, false);
assert_eq!(config.ip6_dotint, false);
assert_eq!(config.edns0, false);
assert_eq!(config.single_request, false);
assert_eq!(config.single_request_reopen, false);
assert_eq!(config.no_tld_query, false);
assert_eq!(config.use_vc, false);
Source

pub fn parse<T: AsRef<[u8]>>(buf: T) -> Result<Config, ParseError>

Parse a buffer and return the corresponding Config object.

use resolv_conf::{ScopedIp, Config};
let config_str = "# /etc/resolv.conf
nameserver  8.8.8.8
nameserver  8.8.4.4
search      example.com sub.example.com
options     ndots:8 attempts:8";

// Parse the config
let parsed_config = Config::parse(&config_str).expect("Failed to parse config");

// Print the config
println!("{:?}", parsed_config);
Examples found in repository?
examples/parse.rs (line 11)
7
8
9
10
11
12
13
fn main() {
    let mut buf = Vec::with_capacity(4096);
    let mut f = File::open("/etc/resolv.conf").unwrap();
    f.read_to_end(&mut buf).unwrap();
    let cfg = resolv_conf::Config::parse(&buf).unwrap();
    println!("---- Config -----\n{:#?}\n", cfg);
}
Source

pub fn get_last_search_or_domain<'a>(&'a self) -> DomainIter<'a>

Return the suffixes declared in the last “domain” or “search” directive.

use resolv_conf::{ScopedIp, Config};
let config_str = "search example.com sub.example.com\ndomain localdomain";
let parsed_config = Config::parse(&config_str).expect("Failed to parse config");
let domains = parsed_config.get_last_search_or_domain()
                           .map(|domain| domain.clone())
                           .collect::<Vec<String>>();
assert_eq!(domains, vec![String::from("localdomain")]);

let config_str = "domain localdomain\nsearch example.com sub.example.com";
let parsed_config = Config::parse(&config_str).expect("Failed to parse config");
let domains = parsed_config.get_last_search_or_domain()
                           .map(|domain| domain.clone())
                           .collect::<Vec<String>>();
assert_eq!(domains, vec![String::from("example.com"), String::from("sub.example.com")]);
Source

pub fn get_domain(&self) -> Option<&String>

Return the domain declared in the last “domain” directive.

Return the domains declared in the last “search” directive.

Source

pub fn set_domain(&mut self, domain: String)

Set the domain corresponding to the “domain” directive.

Set the domains corresponding the “search” directive.

Source

pub fn glibc_normalize(&mut self)

Normalize config according to glibc rulees

Currently this method does the following things:

  1. Truncates list of nameservers to 3 at max
  2. Truncates search list to 6 at max

Other normalizations may be added in future as long as they hold true for a particular GNU libc implementation.

Note: this method is not called after parsing, because we think it’s not forward-compatible to rely on such small and ugly limits. Still, it’s useful to keep implementation as close to glibc as possible.

Source

pub fn get_nameservers_or_local(&self) -> Vec<ScopedIp>

Get nameserver or on the local machine

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Config

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Config

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Config

Source§

fn eq(&self, other: &Config) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Config

Source§

impl StructuralPartialEq for Config

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.