1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Copyright 2015-2017 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! System configuration loading
//!
//! This module is responsible for parsing and returning the configuration from
//!  the host system. It will read from the default location on each operating
//!  system, e.g. most Unixes have this written to `/etc/resolv.conf`

use std::fs::File;
use std::io;
use std::io::Read;
use std::net::SocketAddr;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;

use resolv_conf;

use crate::config::*;
use crate::proto::rr::Name;

const DEFAULT_PORT: u16 = 53;

pub fn read_system_conf() -> io::Result<(ResolverConfig, ResolverOpts)> {
    read_resolv_conf("/etc/resolv.conf")
}

fn read_resolv_conf<P: AsRef<Path>>(path: P) -> io::Result<(ResolverConfig, ResolverOpts)> {
    let mut data = String::new();
    let mut file = File::open(path)?;
    file.read_to_string(&mut data)?;
    parse_resolv_conf(&data)
}

pub fn parse_resolv_conf<T: AsRef<[u8]>>(data: T) -> io::Result<(ResolverConfig, ResolverOpts)> {
    let parsed_conf = resolv_conf::Config::parse(&data).map_err(|e| {
        io::Error::new(
            io::ErrorKind::Other,
            format!("Error parsing resolv.conf: {e}"),
        )
    })?;
    into_resolver_config(parsed_conf)
}

// TODO: use a custom parsing error type maybe?
fn into_resolver_config(
    parsed_config: resolv_conf::Config,
) -> io::Result<(ResolverConfig, ResolverOpts)> {
    let domain = if let Some(domain) = parsed_config.get_system_domain() {
        // The system domain name maybe appear to be valid to the resolv_conf
        // crate but actually be invalid. For example, if the hostname is "matt.schulte's computer"
        // In order to prevent a hostname which macOS or Windows would consider
        // valid from returning an error here we turn parse errors to options
        Name::from_str(domain.as_str()).ok()
    } else {
        None
    };

    // nameservers
    let mut nameservers = Vec::<NameServerConfig>::with_capacity(parsed_config.nameservers.len());
    for ip in &parsed_config.nameservers {
        nameservers.push(NameServerConfig {
            socket_addr: SocketAddr::new(ip.into(), DEFAULT_PORT),
            protocol: Protocol::Udp,
            tls_dns_name: None,
            trust_negative_responses: false,
            #[cfg(feature = "dns-over-rustls")]
            tls_config: None,
            bind_addr: None,
        });
        nameservers.push(NameServerConfig {
            socket_addr: SocketAddr::new(ip.into(), DEFAULT_PORT),
            protocol: Protocol::Tcp,
            tls_dns_name: None,
            trust_negative_responses: false,
            #[cfg(feature = "dns-over-rustls")]
            tls_config: None,
            bind_addr: None,
        });
    }
    if nameservers.is_empty() {
        tracing::warn!("no nameservers found in config");
    }

    // search
    let mut search = vec![];
    for search_domain in parsed_config.get_last_search_or_domain() {
        // Ignore invalid search domains
        if search_domain == "--" {
            continue;
        }

        search.push(Name::from_str_relaxed(search_domain).map_err(|e| {
            io::Error::new(
                io::ErrorKind::Other,
                format!("Error parsing resolv.conf: {e}"),
            )
        })?);
    }

    let config = ResolverConfig::from_parts(domain, search, nameservers);

    let options = ResolverOpts {
        ndots: parsed_config.ndots as usize,
        timeout: Duration::from_secs(u64::from(parsed_config.timeout)),
        attempts: parsed_config.attempts as usize,
        ..ResolverOpts::default()
    };

    Ok((config, options))
}

#[cfg(test)]
mod tests {
    use super::*;
    use proto::rr::Name;
    use std::env;
    use std::net::*;
    use std::str::FromStr;

    fn empty_config() -> ResolverConfig {
        ResolverConfig::from_parts(None, vec![], vec![])
    }

    fn nameserver_config(ip: &str) -> [NameServerConfig; 2] {
        let addr = SocketAddr::new(IpAddr::from_str(ip).unwrap(), 53);
        [
            NameServerConfig {
                socket_addr: addr,
                protocol: Protocol::Udp,
                tls_dns_name: None,
                trust_negative_responses: false,
                #[cfg(feature = "dns-over-rustls")]
                tls_config: None,
                bind_addr: None,
            },
            NameServerConfig {
                socket_addr: addr,
                protocol: Protocol::Tcp,
                tls_dns_name: None,
                trust_negative_responses: false,
                #[cfg(feature = "dns-over-rustls")]
                tls_config: None,
                bind_addr: None,
            },
        ]
    }

    fn tests_dir() -> String {
        let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "../..".to_owned());
        format!("{server_path}/crates/resolver/tests")
    }

    #[test]
    #[allow(clippy::redundant_clone)]
    fn test_name_server() {
        let parsed = parse_resolv_conf("nameserver 127.0.0.1").expect("failed");
        let mut cfg = empty_config();
        let nameservers = nameserver_config("127.0.0.1");
        cfg.add_name_server(nameservers[0].clone());
        cfg.add_name_server(nameservers[1].clone());
        assert_eq!(cfg.name_servers(), parsed.0.name_servers());
        assert_eq!(ResolverOpts::default(), parsed.1);
    }

    #[test]
    fn test_search() {
        let parsed = parse_resolv_conf("search localnet.").expect("failed");
        let mut cfg = empty_config();
        cfg.add_search(Name::from_str("localnet.").unwrap());
        assert_eq!(cfg.search(), parsed.0.search());
        assert_eq!(ResolverOpts::default(), parsed.1);
    }

    #[test]
    fn test_skips_invalid_search() {
        let parsed =
            parse_resolv_conf("\n\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch -- lan\n")
                .expect("failed");
        let mut cfg = empty_config();

        {
            let nameservers = nameserver_config("127.0.0.53");
            cfg.add_name_server(nameservers[0].clone());
            cfg.add_name_server(nameservers[1].clone());
            assert_eq!(cfg.name_servers(), parsed.0.name_servers());
            assert_eq!(ResolverOpts::default(), parsed.1);
        }

        // This is the important part, that the invalid `--` is skipped during parsing
        {
            cfg.add_search(Name::from_str("lan").unwrap());
            assert_eq!(cfg.search(), parsed.0.search());
            assert_eq!(ResolverOpts::default(), parsed.1);
        }
    }

    #[test]
    fn test_underscore_in_search() {
        let parsed = parse_resolv_conf("search Speedport_000").expect("failed");
        let mut cfg = empty_config();
        cfg.add_search(Name::from_str_relaxed("Speedport_000.").unwrap());
        assert_eq!(cfg.search(), parsed.0.search());
        assert_eq!(ResolverOpts::default(), parsed.1);
    }

    #[test]
    fn test_domain() {
        let parsed = parse_resolv_conf("domain example.com").expect("failed");
        let mut cfg = empty_config();
        cfg.set_domain(Name::from_str("example.com").unwrap());
        assert_eq!(cfg, parsed.0);
        assert_eq!(ResolverOpts::default(), parsed.1);
    }

    #[test]
    fn test_read_resolv_conf() {
        read_resolv_conf(format!("{}/resolv.conf-simple", tests_dir())).expect("simple failed");
        read_resolv_conf(format!("{}/resolv.conf-macos", tests_dir())).expect("macos failed");
        read_resolv_conf(format!("{}/resolv.conf-linux", tests_dir())).expect("linux failed");
    }
}