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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! High-level resolver operations

use std::cell::Cell;
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::time::{Duration, Instant};
use std::vec::IntoIter;

use address::address_name;
use config::{default_config, DnsConfig};
use message::{Message, Qr, Question, MESSAGE_LIMIT};
use record::{A, AAAA, Class, Ptr, Record, RecordType};
use socket::{DnsSocket, Error};

/// Performs resolution operations
pub struct DnsResolver {
    sock: DnsSocket,
    config: DnsConfig,
    /// Index of `config.name_servers` to use in next DNS request;
    /// ignored if `config.rotate` is `false`.
    next_ns: Cell<usize>,
}

impl DnsResolver {
    /// Constructs a `DnsResolver` using the given configuration.
    pub fn new(config: DnsConfig) -> io::Result<DnsResolver> {
        let bind = bind_addr(&config.name_servers);
        let sock = try!(DnsSocket::bind((bind, 0)));
        DnsResolver::with_sock(sock, config)
    }

    /// Constructs a `DnsResolver` using the given configuration and bound
    /// to the given address.
    pub fn bind<A: ToSocketAddrs>(addr: A, config: DnsConfig) -> io::Result<DnsResolver> {
        let sock = try!(DnsSocket::bind(addr));
        DnsResolver::with_sock(sock, config)
    }

    fn with_sock(sock: DnsSocket, config: DnsConfig) -> io::Result<DnsResolver> {
        Ok(DnsResolver{
            sock: sock,
            config: config,
            next_ns: Cell::new(0),
        })
    }

    /// Resolves an IPv4 or IPv6 address to a hostname.
    pub fn resolve_addr(&self, addr: &IpAddr) -> io::Result<String> {
        convert_error("failed to resolve address", || {
            let mut out_msg = self.basic_message();

            out_msg.question.push(Question::new(
                address_name(addr), RecordType::Ptr, Class::Internet));

            let mut buf = [0; MESSAGE_LIMIT];
            let msg = try!(self.send_message(&out_msg, &mut buf));

            for rr in msg.answer.into_iter() {
                if rr.r_type == RecordType::Ptr {
                    let ptr = try!(rr.read_rdata::<Ptr>());
                    let mut name = ptr.name;
                    if name.ends_with('.') {
                        name.pop();
                    }
                    return Ok(name);
                }
            }

            Err(Error::IoError(io::Error::new(io::ErrorKind::Other,
                "failed to resolve address: name not found")))
        })
    }

    /// Resolves a hostname to a series of IPv4 or IPv6 addresses.
    pub fn resolve_host(&self, host: &str) -> io::Result<ResolveHost> {
        convert_error("failed to resolve host", || {
            query_names(host, &self.config, |name| {
                let mut err;
                let mut res = Vec::new();

                info!("attempting lookup of name \"{}\"", name);

                if self.config.use_inet6 {
                    err = self.resolve_host_v6(&name,
                        |ip| res.push(IpAddr::V6(ip))).err();

                    if res.is_empty() {
                        err = err.or(self.resolve_host_v4(&name,
                            |ip| res.push(IpAddr::V6(ip.to_ipv6_mapped()))).err());
                    }
                } else {
                    err = self.resolve_host_v4(&name, |ip| res.push(IpAddr::V4(ip))).err();
                    err = err.or(self.resolve_host_v6(&name,
                        |ip| res.push(IpAddr::V6(ip))).err());
                }

                if !res.is_empty() {
                    return Ok(ResolveHost(res.into_iter()));
                }

                if let Some(e) = err {
                    Err(e)
                } else {
                    Err(Error::IoError(io::Error::new(io::ErrorKind::Other,
                        "failed to resolve host: name not found")))
                }
            })
        })
    }

    /// Requests a type of record from the DNS server and returns the results.
    pub fn resolve_record<Rec: Record>(&self, name: &str) -> io::Result<Vec<Rec>> {
        convert_error("failed to resolve record", || {
            let r_ty = Rec::record_type();
            let mut msg = self.basic_message();

            msg.question.push(Question::new(name.to_owned(), r_ty, Class::Internet));

            let mut buf = [0; MESSAGE_LIMIT];
            let reply = try!(self.send_message(&msg, &mut buf));

            let mut rec = Vec::new();

            for rr in reply.answer.into_iter() {
                if rr.r_type == r_ty {
                    rec.push(try!(rr.read_rdata::<Rec>()));
                }
            }

            Ok(rec)
        })
    }

    fn resolve_host_v4<F>(&self, host: &str, mut f: F) -> Result<(), Error>
            where F: FnMut(Ipv4Addr) {
        let mut out_msg = self.basic_message();

        out_msg.question.push(Question::new(
            host.to_owned(), RecordType::A, Class::Internet));

        let mut buf = [0; MESSAGE_LIMIT];
        let msg = try!(self.send_message(&out_msg, &mut buf));

        for rr in msg.answer.into_iter() {
            if rr.r_type == RecordType::A {
                let a = try!(rr.read_rdata::<A>());
                f(a.address);
            }
        }

        Ok(())
    }

    fn resolve_host_v6<F>(&self, host: &str, mut f: F) -> Result<(), Error>
            where F: FnMut(Ipv6Addr) {
        let mut out_msg = self.basic_message();

        out_msg.question.push(Question::new(
            host.to_owned(), RecordType::AAAA, Class::Internet));

        let mut buf = [0; MESSAGE_LIMIT];
        let msg = try!(self.send_message(&out_msg, &mut buf));

        for rr in msg.answer.into_iter() {
            if rr.r_type == RecordType::AAAA {
                let aaaa = try!(rr.read_rdata::<AAAA>());
                f(aaaa.address);
            }
        }

        Ok(())
    }

    fn basic_message(&self) -> Message {
        let mut msg = Message::new();

        msg.header.recursion_desired = true;
        msg
    }

    /// Sends a message to the DNS server and attempts to read a response.
    pub fn send_message<'buf>(&self, out_msg: &Message, buf: &'buf mut [u8])
            -> Result<Message<'buf>, Error> {
        let mut last_err = None;

        // FIXME(rust-lang/rust#21906):
        // Workaround for mutable borrow interfering with itself.
        // The drop probably isn't necessary, but it makes me feel better.
        let buf_ptr = buf as *mut _;
        drop(buf);

        'retry: for retries in 0..self.config.attempts {
            let ns_addr = if self.config.rotate {
                self.next_nameserver()
            } else {
                let n = self.config.name_servers.len();
                self.config.name_servers[retries as usize % n]
            };

            let mut timeout = self.config.timeout;

            info!("resolver sending message to {}", ns_addr);

            try!(self.sock.send_message(out_msg, &ns_addr));

            loop {
                try!(self.sock.get().set_read_timeout(Some(timeout)));

                // The other part of the aforementioned workaround.
                let buf = unsafe { &mut *buf_ptr };

                let start = Instant::now();

                match self.sock.recv_message(&ns_addr, buf) {
                    Ok(None) => {
                        let passed = start.elapsed();

                        // Maintain the right total timeout if we're interrupted
                        // by irrelevant messages.
                        if timeout < passed {
                            timeout = Duration::from_secs(0);
                        } else {
                            timeout = timeout - passed;
                        }
                    }
                    Ok(Some(msg)) => {
                        // Ignore irrelevant messages
                        if msg.header.id == out_msg.header.id &&
                                msg.header.qr == Qr::Response {
                            try!(msg.get_error());
                            return Ok(msg);
                        }
                    }
                    Err(e) => {
                        // Retry on timeout
                        if e.is_timeout() {
                            last_err = Some(e);
                            continue 'retry;
                        }
                        // Immediately bail for other errors
                        return Err(e);
                    }
                }
            }
        }

        Err(last_err.unwrap())
    }

    fn next_nameserver(&self) -> SocketAddr {
        let n = self.next_ns.get();
        self.next_ns.set((n + 1) % self.config.name_servers.len());
        self.config.name_servers[n]
    }
}

fn bind_addr(name_servers: &[SocketAddr]) -> IpAddr {
    match name_servers.first() {
        Some(&SocketAddr::V6(_)) => IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
        _ => IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))
    }
}

fn convert_error<T, F>(desc: &str, f: F) -> io::Result<T>
        where F: FnOnce() -> Result<T, Error> {
    match f() {
        Ok(t) => Ok(t),
        Err(Error::IoError(e)) => Err(e),
        Err(e) => Err(io::Error::new(
            io::ErrorKind::Other, format!("{}: {}", desc, e)))
    }
}

fn query_names<F, T>(name: &str, config: &DnsConfig, mut f: F) -> Result<T, Error>
        where F: FnMut(String) -> Result<T, Error> {
    let use_search = !name.ends_with('.') &&
        name.chars().filter(|&c| c == '.')
            .count() as u32 >= config.n_dots;

    if use_search {
        let mut err = None;

        for name in with_suffixes(name, &config.search) {
            match f(name) {
                Ok(t) => return Ok(t),
                Err(e) => err = Some(e)
            }
        }

        if let Some(e) = err {
            Err(e)
        } else {
            Err(Error::IoError(io::Error::new(io::ErrorKind::Other,
                "failed to resolve host: name not found")))
        }
    } else {
        f(name.to_owned())
    }
}

fn with_suffixes(host: &str, suffixes: &[String]) -> Vec<String> {
    let mut v = suffixes.iter()
        .map(|s| format!("{}.{}", host, s)).collect::<Vec<_>>();
    v.push(host.to_owned());
    v
}

/// Resolves an IPv4 or IPv6 address to a hostname.
pub fn resolve_addr(addr: &IpAddr) -> io::Result<String> {
    let r = try!(DnsResolver::new(try!(default_config())));
    r.resolve_addr(addr)
}

/// Resolves a hostname to one or more IPv4 or IPv6 addresses.
///
/// # Example
///
/// ```no_run
/// use resolve::resolve_host;
/// # use std::io;
///
/// # fn _foo() -> io::Result<()> {
/// for addr in try!(resolve_host("rust-lang.org")) {
///     println!("found address: {}", addr);
/// }
/// # Ok(())
/// # }
/// ```
pub fn resolve_host(host: &str) -> io::Result<ResolveHost> {
    let r = try!(DnsResolver::new(try!(default_config())));
    r.resolve_host(host)
}

/// Yields a series of `IpAddr` values from `resolve_host`.
pub struct ResolveHost(IntoIter<IpAddr>);

impl Iterator for ResolveHost {
    type Item = IpAddr;

    fn next(&mut self) -> Option<IpAddr> {
        self.0.next()
    }
}