Skip to main content

fritz_sim/
dns.rs

1//! A small DNS server on the loopback interface, for tests of DNS clients:
2//! it answers A and AAAA queries from a table of names and addresses, and
3//! every other name with NXDOMAIN.
4//!
5//! ```no_run
6//! # async fn example() -> std::io::Result<()> {
7//! let dns = fritz_sim::dns::DnsServer::start(&[("nas.fritz.box", "192.0.2.10")]).await?;
8//! println!("ask {}", dns.address());
9//! # Ok(())
10//! # }
11//! ```
12
13use std::io;
14use std::net::{IpAddr, Ipv4Addr, SocketAddr};
15use std::sync::{Arc, Mutex, PoisonError};
16
17use tokio::net::UdpSocket;
18use tokio::task::JoinHandle;
19
20/// A DNS server that answers until it is dropped.
21#[derive(Debug)]
22pub struct DnsServer {
23    address: SocketAddr,
24    queries: Arc<Mutex<Vec<String>>>,
25    task: JoinHandle<()>,
26}
27
28impl DnsServer {
29    /// Serves `records`, pairs of a name and an address, on a free UDP port
30    /// of the loopback interface. Names are compared ignoring case.
31    ///
32    /// # Errors
33    ///
34    /// The errors of binding the port, and [`io::ErrorKind::InvalidInput`]
35    /// for an address that is not one.
36    pub async fn start(records: &[(&str, &str)]) -> io::Result<Self> {
37        let table = records
38            .iter()
39            .map(|(name, address)| {
40                let address = address
41                    .parse::<IpAddr>()
42                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
43                Ok((name.trim_end_matches('.').to_ascii_lowercase(), address))
44            })
45            .collect::<io::Result<Vec<_>>>()?;
46        let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await?;
47        let address = socket.local_addr()?;
48        let queries = Arc::new(Mutex::new(Vec::new()));
49        let seen = Arc::clone(&queries);
50        let task = tokio::spawn(async move {
51            let mut buffer = [0; 512];
52            loop {
53                if let Ok((length, peer)) = socket.recv_from(&mut buffer).await
54                    && let Some((name, reply)) = reply(&buffer[..length], &table)
55                {
56                    seen.lock()
57                        .unwrap_or_else(PoisonError::into_inner)
58                        .push(name);
59                    let _ = socket.send_to(&reply, peer).await;
60                }
61            }
62        });
63        Ok(Self {
64            address,
65            queries,
66            task,
67        })
68    }
69
70    /// The address to send queries to.
71    pub fn address(&self) -> SocketAddr {
72        self.address
73    }
74
75    /// The names asked for so far, in lower case, one per query.
76    pub fn queries(&self) -> Vec<String> {
77        self.queries
78            .lock()
79            .unwrap_or_else(PoisonError::into_inner)
80            .clone()
81    }
82}
83
84impl Drop for DnsServer {
85    fn drop(&mut self) {
86        self.task.abort();
87    }
88}
89
90/// The name asked for in `query` and the answer from `table`, `None` for
91/// anything but a query with one question.
92fn reply(query: &[u8], table: &[(String, IpAddr)]) -> Option<(String, Vec<u8>)> {
93    let header = query.get(..12)?;
94    if header[2] & 0x80 != 0 || header[4..6] != [0, 1] {
95        return None;
96    }
97    let mut at = 12;
98    let mut labels = Vec::new();
99    loop {
100        let length = usize::from(*query.get(at)?);
101        at += 1;
102        if length == 0 {
103            break;
104        }
105        labels.push(String::from_utf8_lossy(query.get(at..at + length)?).to_ascii_lowercase());
106        at += length;
107    }
108    // The question ends with its type and class.
109    let question = query.get(12..at + 4)?;
110    let kind = &query[at..at + 2];
111    let name = labels.join(".");
112    let known = table.iter().any(|(n, _)| *n == name);
113    let answers: Vec<&IpAddr> = table
114        .iter()
115        .filter(|(n, a)| *n == name && (a.is_ipv4() == (kind == [0, 1])))
116        .map(|(_, a)| a)
117        .collect();
118    let mut packet = Vec::with_capacity(64);
119    packet.extend_from_slice(&header[..2]);
120    // An answer, recursion available, and NXDOMAIN for unknown names.
121    packet.extend_from_slice(&[0x81, if known { 0x80 } else { 0x83 }, 0, 1, 0]);
122    packet.push(u8::try_from(answers.len()).ok()?);
123    packet.extend_from_slice(&[0, 0, 0, 0]);
124    packet.extend_from_slice(question);
125    for address in answers {
126        let data = match address {
127            IpAddr::V4(v4) => v4.octets().to_vec(),
128            IpAddr::V6(v6) => v6.octets().to_vec(),
129        };
130        // The name of the question, class IN, 60 seconds.
131        packet.extend_from_slice(&[0xc0, 12]);
132        packet.extend_from_slice(kind);
133        packet.extend_from_slice(&[0, 1, 0, 0, 0, 60, 0]);
134        packet.push(u8::try_from(data.len()).ok()?);
135        packet.extend_from_slice(&data);
136    }
137    Some((name, packet))
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn ignores_what_is_not_a_query() {
146        assert_eq!(reply(&[0; 4], &[]), None);
147        // An answer.
148        let mut answer = [0; 17];
149        answer[2] = 0x80;
150        answer[5] = 1;
151        assert_eq!(reply(&answer, &[]), None);
152        // Cut off in the name.
153        let mut cut = [0; 14];
154        cut[5] = 1;
155        cut[12] = 5;
156        assert_eq!(reply(&cut, &[]), None);
157    }
158}