Skip to main content

fritz_core/dns/
wire.rs

1//! A minimal DNS client over UDP: one question for the A or AAAA records of
2//! one name, one answer, read with bounds checks.
3
4use std::fmt;
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
6use std::time::Duration;
7
8use serde::Serialize;
9use tokio::net::UdpSocket;
10
11/// The largest answer read. Answers for A and AAAA records are small.
12const MAX_ANSWER: usize = 4096;
13
14/// The kind of record asked for.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
16pub enum Record {
17    A,
18    Aaaa,
19}
20
21impl Record {
22    fn code(self) -> u16 {
23        match self {
24            Self::A => 1,
25            Self::Aaaa => 28,
26        }
27    }
28}
29
30/// Why a query got no addresses.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Failure {
33    /// The server says the name does not exist (NXDOMAIN).
34    NoSuchName,
35    /// The name exists, but has no record of this kind.
36    NoRecord,
37    /// The server did not answer in time.
38    Timeout,
39    /// The server answered with an error, like SERVFAIL or REFUSED.
40    Refused(u8),
41    /// The answer was too long for UDP and cut off, so it is incomplete.
42    Truncated,
43    /// The query could not be sent, or the answer could not be read.
44    Network(String),
45}
46
47impl fmt::Display for Failure {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::NoSuchName => f.write_str("no such name"),
51            Self::NoRecord => f.write_str("no address"),
52            Self::Timeout => f.write_str("no answer in time"),
53            Self::Refused(2) => f.write_str("server failure (SERVFAIL)"),
54            Self::Refused(5) => f.write_str("refused (REFUSED)"),
55            Self::Refused(code) => write!(f, "error code {code}"),
56            Self::Truncated => f.write_str("answer cut off, too long for UDP"),
57            Self::Network(error) => f.write_str(error),
58        }
59    }
60}
61
62/// Asks `server` for the records of `kind` of `name`, and waits at most
63/// `timeout` for the answer. Answers to other queries are ignored.
64///
65/// # Errors
66///
67/// A [`Failure`] if there are no addresses.
68pub async fn query(
69    server: SocketAddr,
70    name: &str,
71    kind: Record,
72    timeout: Duration,
73) -> Result<Vec<IpAddr>, Failure> {
74    let id = query_id();
75    let packet = encode(id, name, kind).map_err(|e| Failure::Network(e.to_owned()))?;
76    let exchange = async {
77        let local: SocketAddr = if server.is_ipv4() {
78            (Ipv4Addr::UNSPECIFIED, 0).into()
79        } else {
80            (Ipv6Addr::UNSPECIFIED, 0).into()
81        };
82        let socket = UdpSocket::bind(local).await?;
83        socket.connect(server).await?;
84        socket.send(&packet).await?;
85        let mut buffer = vec![0; MAX_ANSWER];
86        loop {
87            let length = socket.recv(&mut buffer).await?;
88            if let Some(answer) = decode(id, kind, &buffer[..length]) {
89                return Ok::<_, std::io::Error>(answer);
90            }
91        }
92    };
93    match tokio::time::timeout(timeout, exchange).await {
94        Err(_) => Err(Failure::Timeout),
95        Ok(Err(error)) => Err(Failure::Network(error.to_string())),
96        Ok(Ok(answer)) => answer,
97    }
98}
99
100/// An ID for a query, different for every query of a run.
101fn query_id() -> u16 {
102    use std::sync::atomic::{AtomicU16, Ordering};
103    static NEXT: AtomicU16 = AtomicU16::new(0);
104    let nanos = std::time::SystemTime::now()
105        .duration_since(std::time::UNIX_EPOCH)
106        .map_or(0, |d| d.subsec_nanos());
107    #[expect(clippy::cast_possible_truncation, reason = "any 16 bits will do")]
108    let seed = (nanos ^ std::process::id()) as u16;
109    seed.wrapping_add(NEXT.fetch_add(1, Ordering::Relaxed))
110}
111
112/// The query for the records of `kind` of `name`, with recursion desired.
113pub(crate) fn encode(id: u16, name: &str, kind: Record) -> Result<Vec<u8>, &'static str> {
114    let mut packet = Vec::with_capacity(32 + name.len());
115    packet.extend_from_slice(&id.to_be_bytes());
116    // Recursion desired; one question.
117    packet.extend_from_slice(&[0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0]);
118    for label in name.trim_end_matches('.').split('.') {
119        let length = u8::try_from(label.len())
120            .ok()
121            .filter(|l| (1..=63).contains(l))
122            .ok_or("invalid label")?;
123        packet.push(length);
124        packet.extend_from_slice(label.as_bytes());
125    }
126    packet.push(0);
127    packet.extend_from_slice(&kind.code().to_be_bytes());
128    // Class IN.
129    packet.extend_from_slice(&[0, 1]);
130    Ok(packet)
131}
132
133/// The addresses in the answer to the query `id`, or `None` if `packet` is
134/// not that answer.
135pub(crate) fn decode(id: u16, kind: Record, packet: &[u8]) -> Option<Result<Vec<IpAddr>, Failure>> {
136    let mut reader = Bytes { packet, at: 0 };
137    if reader.u16()? != id {
138        return None;
139    }
140    let flags = reader.u8()?;
141    if flags & 0x80 == 0 {
142        return None;
143    }
144    // TC: the answer was cut off and may lack records.
145    if flags & 0x02 != 0 {
146        return Some(Err(Failure::Truncated));
147    }
148    let code = reader.u8()? & 0x0f;
149    let questions = reader.u16()?;
150    let answers = reader.u16()?;
151    reader.skip(4)?;
152    match code {
153        0 => {}
154        3 => return Some(Err(Failure::NoSuchName)),
155        code => return Some(Err(Failure::Refused(code))),
156    }
157    for _ in 0..questions {
158        reader.name()?;
159        reader.skip(4)?;
160    }
161    let mut addresses = Vec::new();
162    for _ in 0..answers {
163        reader.name()?;
164        let record = reader.u16()?;
165        reader.skip(6)?;
166        let length = usize::from(reader.u16()?);
167        let data = reader.take(length)?;
168        if record == kind.code()
169            && let Some(address) = address(data)
170        {
171            addresses.push(address);
172        }
173    }
174    Some(if addresses.is_empty() {
175        Err(Failure::NoRecord)
176    } else {
177        Ok(addresses)
178    })
179}
180
181/// The address in the data of an A or AAAA record.
182fn address(data: &[u8]) -> Option<IpAddr> {
183    if let Ok(octets) = <[u8; 4]>::try_from(data) {
184        return Some(IpAddr::from(octets));
185    }
186    <[u8; 16]>::try_from(data).ok().map(IpAddr::from)
187}
188
189/// Reads a packet front to back, `None` past its end.
190struct Bytes<'a> {
191    packet: &'a [u8],
192    at: usize,
193}
194
195impl<'a> Bytes<'a> {
196    fn take(&mut self, length: usize) -> Option<&'a [u8]> {
197        let end = self.at.checked_add(length)?;
198        let bytes = self.packet.get(self.at..end)?;
199        self.at = end;
200        Some(bytes)
201    }
202
203    fn skip(&mut self, length: usize) -> Option<()> {
204        self.take(length).map(|_| ())
205    }
206
207    fn u8(&mut self) -> Option<u8> {
208        self.take(1).map(|b| b[0])
209    }
210
211    fn u16(&mut self) -> Option<u16> {
212        self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]]))
213    }
214
215    /// Skips a name: labels, ended by an empty one or a pointer.
216    fn name(&mut self) -> Option<()> {
217        loop {
218            let length = self.u8()?;
219            match length {
220                0 => return Some(()),
221                l if l & 0xc0 == 0xc0 => return self.skip(1),
222                l => self.skip(usize::from(l))?,
223            }
224        }
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    /// An answer to the query `id` with code `code` and the records.
233    fn answer(id: u16, code: u8, records: &[(u16, &[u8])]) -> Vec<u8> {
234        let mut packet = encode(id, "nas.example", Record::A).unwrap();
235        packet[2] = 0x81;
236        packet[3] = 0x80 | code;
237        packet[7] = u8::try_from(records.len()).unwrap();
238        for (kind, data) in records {
239            // A pointer to the name of the question.
240            packet.extend_from_slice(&[0xc0, 12]);
241            packet.extend_from_slice(&kind.to_be_bytes());
242            packet.extend_from_slice(&[0, 1, 0, 0, 0, 60]);
243            packet.extend_from_slice(&u16::try_from(data.len()).unwrap().to_be_bytes());
244            packet.extend_from_slice(data);
245        }
246        packet
247    }
248
249    #[test]
250    fn encodes_a_query() {
251        let packet = encode(0x1234, "nas.example.", Record::Aaaa).unwrap();
252        assert_eq!(
253            packet,
254            [
255                0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, b'n', b'a', b's', 7, b'e', b'x', b'a',
256                b'm', b'p', b'l', b'e', 0, 0, 28, 0, 1
257            ]
258        );
259        assert!(encode(1, "a..b", Record::A).is_err());
260        assert!(encode(1, &"x".repeat(64), Record::A).is_err());
261    }
262
263    #[test]
264    fn decodes_answers() {
265        let cname: &[u8] = &[3, b'n', b'a', b's', 0];
266        let packet = answer(7, 0, &[(5, cname), (1, &[192, 0, 2, 7]), (28, &[0; 16])]);
267        assert_eq!(
268            decode(7, Record::A, &packet),
269            Some(Ok(vec![IpAddr::from([192, 0, 2, 7])]))
270        );
271        assert_eq!(
272            decode(7, Record::Aaaa, &packet),
273            Some(Ok(vec![IpAddr::from([0u8; 16])]))
274        );
275        assert_eq!(
276            decode(7, Record::A, &answer(7, 0, &[])),
277            Some(Err(Failure::NoRecord))
278        );
279        assert_eq!(
280            decode(7, Record::A, &answer(7, 3, &[])),
281            Some(Err(Failure::NoSuchName))
282        );
283        assert_eq!(
284            decode(7, Record::A, &answer(7, 2, &[])),
285            Some(Err(Failure::Refused(2)))
286        );
287        // Another query, a query instead of an answer, cut off.
288        assert_eq!(decode(8, Record::A, &packet), None);
289        assert_eq!(
290            decode(7, Record::A, &encode(7, "nas", Record::A).unwrap()),
291            None
292        );
293        assert_eq!(decode(7, Record::A, &packet[..packet.len() - 2]), None);
294        // An answer cut off for UDP.
295        let mut truncated = packet.clone();
296        truncated[2] |= 0x02;
297        assert_eq!(
298            decode(7, Record::A, &truncated),
299            Some(Err(Failure::Truncated))
300        );
301        assert_eq!(
302            Failure::Truncated.to_string(),
303            "answer cut off, too long for UDP"
304        );
305        // A record with an odd length is skipped.
306        assert_eq!(
307            decode(7, Record::A, &answer(7, 0, &[(1, &[1, 2, 3])])),
308            Some(Err(Failure::NoRecord))
309        );
310    }
311
312    #[test]
313    fn describes_failures() {
314        let texts: Vec<String> = [
315            Failure::NoSuchName,
316            Failure::NoRecord,
317            Failure::Timeout,
318            Failure::Refused(2),
319            Failure::Refused(5),
320            Failure::Refused(4),
321            Failure::Network("unreachable".to_owned()),
322        ]
323        .iter()
324        .map(ToString::to_string)
325        .collect();
326        assert_eq!(
327            texts,
328            [
329                "no such name",
330                "no address",
331                "no answer in time",
332                "server failure (SERVFAIL)",
333                "refused (REFUSED)",
334                "error code 4",
335                "unreachable",
336            ]
337        );
338    }
339}