Skip to main content

edge_captive/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![warn(clippy::large_futures)]
3#![allow(clippy::uninlined_format_args)]
4#![allow(unknown_lints)]
5
6use core::fmt::Display;
7use core::time::Duration;
8
9use domain::base::wire::Composer;
10use domain::dep::octseq::{OctetsBuilder, Truncate};
11
12use domain::{
13    base::{
14        iana::{Class, Opcode, Rcode},
15        message::ShortMessage,
16        message_builder::PushError,
17        record::Ttl,
18        wire::ParseError,
19        Record, Rtype,
20    },
21    dep::octseq::ShortBuf,
22    rdata::A,
23};
24
25// This mod MUST go first, so that the others see its macros.
26pub(crate) mod fmt;
27
28#[cfg(feature = "io")]
29pub mod io;
30
31#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
32pub enum DnsError {
33    ShortBuf,
34    InvalidMessage,
35}
36
37impl Display for DnsError {
38    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39        match self {
40            Self::ShortBuf => write!(f, "ShortBuf"),
41            Self::InvalidMessage => write!(f, "InvalidMessage"),
42        }
43    }
44}
45
46#[cfg(feature = "defmt")]
47impl defmt::Format for DnsError {
48    fn format(&self, f: defmt::Formatter<'_>) {
49        match self {
50            Self::ShortBuf => defmt::write!(f, "ShortBuf"),
51            Self::InvalidMessage => defmt::write!(f, "InvalidMessage"),
52        }
53    }
54}
55
56impl core::error::Error for DnsError {}
57
58impl From<ShortBuf> for DnsError {
59    fn from(_: ShortBuf) -> Self {
60        Self::ShortBuf
61    }
62}
63
64impl From<PushError> for DnsError {
65    fn from(_: PushError) -> Self {
66        Self::ShortBuf
67    }
68}
69
70impl From<ShortMessage> for DnsError {
71    fn from(_: ShortMessage) -> Self {
72        Self::InvalidMessage
73    }
74}
75
76impl From<ParseError> for DnsError {
77    fn from(_: ParseError) -> Self {
78        Self::InvalidMessage
79    }
80}
81
82pub fn reply(
83    request: &[u8],
84    ip: &[u8; 4],
85    ttl: Duration,
86    buf: &mut [u8],
87) -> Result<usize, DnsError> {
88    let buf = Buf(buf, 0);
89
90    let message = domain::base::Message::from_octets(request)?;
91    debug!(
92        "Processing message with header: {:?}",
93        debug2format!(message.header())
94    );
95
96    let mut responseb = domain::base::MessageBuilder::from_target(buf)?;
97
98    let buf = if matches!(message.header().opcode(), Opcode::QUERY) {
99        debug!("Message is of type Query, processing all questions");
100
101        let mut answerb = responseb.start_answer(&message, Rcode::NOERROR)?;
102
103        for question in message.question() {
104            let question = question?;
105
106            if matches!(question.qtype(), Rtype::A) && matches!(question.qclass(), Class::IN) {
107                let record = Record::new(
108                    question.qname(),
109                    Class::IN,
110                    Ttl::from_duration_lossy(ttl),
111                    A::from_octets(ip[0], ip[1], ip[2], ip[3]),
112                );
113                debug!(
114                    "Answering {:?} with {:?}",
115                    debug2format!(question),
116                    debug2format!(record)
117                );
118                answerb.push(record)?;
119            } else {
120                debug!(
121                    "Question {:?} is not of type A, not answering",
122                    debug2format!(question)
123                );
124            }
125        }
126
127        answerb.finish()
128    } else {
129        debug!("Message is not of type Query, replying with NotImp");
130
131        let headerb = responseb.header_mut();
132
133        headerb.set_qr(true);
134        headerb.set_id(message.header().id());
135        headerb.set_opcode(message.header().opcode());
136        headerb.set_rd(message.header().rd());
137        headerb.set_rcode(domain::base::iana::Rcode::NOTIMP);
138
139        responseb.finish()
140    };
141
142    Ok(buf.1)
143}
144
145struct Buf<'a>(pub &'a mut [u8], pub usize);
146
147impl Composer for Buf<'_> {}
148
149impl OctetsBuilder for Buf<'_> {
150    type AppendError = ShortBuf;
151
152    fn append_slice(&mut self, slice: &[u8]) -> Result<(), Self::AppendError> {
153        if self.1 + slice.len() <= self.0.len() {
154            let end = self.1 + slice.len();
155            self.0[self.1..end].copy_from_slice(slice);
156            self.1 = end;
157
158            Ok(())
159        } else {
160            Err(ShortBuf)
161        }
162    }
163}
164
165impl Truncate for Buf<'_> {
166    fn truncate(&mut self, len: usize) {
167        self.1 = len;
168    }
169}
170
171impl AsMut<[u8]> for Buf<'_> {
172    fn as_mut(&mut self) -> &mut [u8] {
173        &mut self.0[..self.1]
174    }
175}
176
177impl AsRef<[u8]> for Buf<'_> {
178    fn as_ref(&self) -> &[u8] {
179        &self.0[..self.1]
180    }
181}
182
183#[cfg(test)]
184mod test {
185    use core::time::Duration;
186
187    use domain::base::iana::{Opcode, Rcode, Rtype};
188    use domain::base::name::Name;
189    use domain::base::{Message, MessageBuilder, ToName};
190    use domain::rdata::A;
191
192    use super::{reply, Buf};
193
194    const NAME: &[u8] = b"\x07captive\x05local\x00";
195    const IP: [u8; 4] = [10, 0, 0, 1];
196
197    fn query(id: u16, opcode: Opcode, rtype: Rtype, buf: &mut [u8]) -> usize {
198        let mut mb = MessageBuilder::from_target(Buf(buf, 0)).unwrap();
199        mb.header_mut().set_id(id);
200        mb.header_mut().set_opcode(opcode);
201        mb.header_mut().set_rd(true);
202
203        let mut qb = mb.question();
204        qb.push((Name::from_slice(NAME).unwrap(), rtype)).unwrap();
205
206        qb.finish().1
207    }
208
209    #[test]
210    fn answers_a_queries() {
211        let mut qbuf = [0; 128];
212        let qlen = query(0x1234, Opcode::QUERY, Rtype::A, &mut qbuf);
213
214        let mut rbuf = [0; 256];
215        let len = reply(&qbuf[..qlen], &IP, Duration::from_secs(60), &mut rbuf).unwrap();
216
217        let msg = Message::from_octets(&rbuf[..len]).unwrap();
218        assert_eq!(msg.header().id(), 0x1234);
219        assert!(msg.header().qr());
220        assert_eq!(msg.header().rcode(), Rcode::NOERROR);
221        assert_eq!(msg.header_counts().qdcount(), 1);
222        assert_eq!(msg.header_counts().ancount(), 1);
223
224        let record = msg
225            .answer()
226            .unwrap()
227            .limit_to::<A>()
228            .next()
229            .unwrap()
230            .unwrap();
231        assert_eq!(record.data().addr().octets(), IP);
232        assert_eq!(record.ttl().as_secs(), 60);
233        assert!(record.owner().name_eq(&Name::from_slice(NAME).unwrap()));
234    }
235
236    #[test]
237    fn ignores_other_question_types() {
238        let mut qbuf = [0; 128];
239        let qlen = query(7, Opcode::QUERY, Rtype::AAAA, &mut qbuf);
240
241        let mut rbuf = [0; 256];
242        let len = reply(&qbuf[..qlen], &IP, Duration::from_secs(60), &mut rbuf).unwrap();
243
244        let msg = Message::from_octets(&rbuf[..len]).unwrap();
245        assert_eq!(msg.header().id(), 7);
246        assert!(msg.header().qr());
247        assert_eq!(msg.header().rcode(), Rcode::NOERROR);
248        assert_eq!(msg.header_counts().qdcount(), 1);
249        assert_eq!(msg.header_counts().ancount(), 0);
250    }
251
252    #[test]
253    fn rejects_other_opcodes() {
254        let mut qbuf = [0; 128];
255        let qlen = query(9, Opcode::STATUS, Rtype::A, &mut qbuf);
256
257        let mut rbuf = [0; 256];
258        let len = reply(&qbuf[..qlen], &IP, Duration::from_secs(60), &mut rbuf).unwrap();
259
260        let msg = Message::from_octets(&rbuf[..len]).unwrap();
261        assert_eq!(msg.header().id(), 9);
262        assert!(msg.header().qr());
263        assert_eq!(msg.header().opcode(), Opcode::STATUS);
264        assert_eq!(msg.header().rcode(), Rcode::NOTIMP);
265        assert_eq!(msg.header_counts().ancount(), 0);
266    }
267
268    #[test]
269    fn errors() {
270        // Not a DNS message at all
271        assert!(reply(&[1, 2, 3], &IP, Duration::from_secs(60), &mut [0; 256]).is_err());
272
273        // No room for the answer
274        let mut qbuf = [0; 128];
275        let qlen = query(1, Opcode::QUERY, Rtype::A, &mut qbuf);
276        assert!(reply(&qbuf[..qlen], &IP, Duration::from_secs(60), &mut [0; 16]).is_err());
277    }
278}