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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

/// Domain name structure and funtions
pub mod name;

use crate::binutils::*;
use crate::body::name::Name;
use crate::ParseError;
use std::borrow::Cow;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str;

const INIT_RR_SIZE: usize = 64;

macro_rules! types {
    (
        $(
            #[$inner:meta]
            $variant:tt = $value:literal
        )+
    ) => {
        /// The type of [ResourceRecord].
        #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd)]
        pub enum Type {
            $(
                #[$inner]
                $variant,
            )*
            /// ?: A value has been received that does not correspond to any known qtype.
            Unknown(u16),
        }

        impl TryFrom<QType> for Type {
            type Error = &'static str;

            #[inline]
            fn try_from(value: QType) -> Result<Self, Self::Error> {
                match value {
                    $(QType::$variant => Ok(Self::$variant),)*
                    QType::Unknown(n) => Ok(Self::Unknown(n)),
                    _ => Err("QType is not a valid Type")
                }
            }
        }

        impl From<u16> for Type {
            #[inline]
            fn from(value: u16) -> Self {
                match value {
                    $($value => Self::$variant,)*
                    _ => Self::Unknown(value),
                }
            }
        }

        impl From<Type> for u16 {
            #[inline]
            fn from(value: Type) -> Self {
                match value {
                    $(Type::$variant => $value,)*
                    Type::Unknown(n) => n,
                }
            }
        }

        /// The type of [Question].
        #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd)]
        pub enum QType {
            $(
                #[$inner]
                $variant,
            )*
            /// All types
            All,
            /// ?: A value has been received that does not correspond to any known qtype.
            Unknown(u16),
        }

        impl From<Type> for QType {
            #[inline]
            fn from(value: Type) -> Self {
                match value {
                    $(Type::$variant => Self::$variant,)*
                    Type::Unknown(n) => Self::Unknown(n),
                }
            }
        }

        impl From<u16> for QType {
            #[inline]
            fn from(value: u16) -> Self {
                match value {
                    $($value => Self::$variant,)*
                    255 => Self::All,
                    _ => Self::Unknown(value),
                }
            }
        }

        impl From<QType> for u16 {
            #[inline]
            fn from(value: QType) -> Self {
                match value {
                    $(QType::$variant => $value,)*
                    QType::All => 255,
                    QType::Unknown(n) => n,
                }
            }
        }
    };
}

/// A query for a [ResourceRecord] of the specified [QType] and [Class].
///
/// ```text
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                                               |
///    /                     QNAME                     /
///    /                                               /
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                     QTYPE                     |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                     QCLASS                    |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
#[derive(Clone, Debug)]
pub struct Question<'a> {
    /// The domain name to be queried
    pub name: Name<'a>,
    /// The type of [ResourceRecord] being queried
    pub qtype: QType,
    /// The class of [ResourceRecord] being queried
    pub class: Class,
}

impl From<Question<'_>> for Vec<u8> {
    #[inline]
    fn from(question: Question<'_>) -> Self {
        let mut out = question.name.into();
        push_u16(&mut out, question.qtype.into());
        push_u16(&mut out, question.class.into());
        out
    }
}

impl<'a> Question<'a> {
    /// Parse from the specified `buff`, starting at position `start`.
    ///
    /// # Errors
    ///
    /// It will error if the buffer does not contain a valid question. If the domain name
    /// in the question has been compressed the buffer should include all previous bytes from
    /// the DNS packet to be considered valid.
    #[inline]
    pub fn parse(buff: &'a [u8], start: usize) -> Result<(Self, usize), crate::ParseError> {
        let (name, size) = Name::parse(buff, start)?;
        let n = start + size;
        Ok((
            Question {
                name,
                qtype: safe_u16_read(buff, n)?.into(),
                class: safe_u16_read(buff, n + 2)?.into(),
            },
            size + 4,
        ))
    }

    /// Serialize the [Question] and append it tho the end of the provided `packet`
    #[inline]
    pub fn serialize(&self, packet: &mut Vec<u8>) {
        self.name.serialize(packet);
        push_u16(packet, self.qtype.into());
        push_u16(packet, self.class.into());
    }
}

/// A description of a resource that can be used as an answer to a question
/// or to provide additional information in the `authority` or `additional` fields
/// of a DNS packet.
///
/// ```text
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                                               |
///    /                                               /
///    /                      NAME                     /
///    |                                               |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                      TYPE                     |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                     CLASS                     |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                      TTL                      |
///    |                                               |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///    |                   RDLENGTH                    |
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
///    /                     RDATA                     /
///    /                                               /
///    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
#[derive(Debug, Clone)]
pub struct ResourceRecord<'a> {
    /// Contains general information that every [ResourceRecord] shares, like type or class.
    pub preamble: RecordPreamble<'a>,
    /// The RDATA section of a resource record in some DNS packet.
    pub data: RecordData<'a>,
}

impl From<ResourceRecord<'_>> for Vec<u8> {
    #[inline]
    fn from(rr: ResourceRecord<'_>) -> Self {
        let mut out = Vec::with_capacity(INIT_RR_SIZE);
        rr.serialize(&mut out);
        out
    }
}

impl<'a> ResourceRecord<'a> {
    /// Parse from the specified `buff`, starting at position `pos`.
    #[inline]
    pub fn parse(buff: &'a [u8], pos: usize) -> Result<(Self, usize), ParseError> {
        let (preamble, size) = RecordPreamble::parse(buff, pos)?;
        let (data, len) = RecordData::parse(buff, pos + size, &preamble)?;
        Ok((Self { preamble, data }, size + len))
    }

    /// Serialize the [ResourceRecord] and append it tho the end of the provided `packet`
    #[inline]
    pub fn serialize(&self, packet: &mut Vec<u8>) {
        self.preamble.serialize(packet);
        self.data.serialize(packet);
    }
}

/// The [ResourceRecord] preamble. Common data to all resource record types.
#[derive(Debug, Clone)]
pub struct RecordPreamble<'a> {
    /// The domain name the RR refers to.
    pub name: Name<'a>,
    /// The RR type.
    pub rrtype: Type,
    /// The RR class.
    pub class: Class,
    /// The time interval that the resource record may be cached before the source of the information should again be consulted.
    pub ttl: i32,
    /// The length of the RR data.
    pub rdlen: u16,
}

impl<'a> RecordPreamble<'a> {
    #[inline]
    fn parse(buff: &'a [u8], pos: usize) -> Result<(Self, usize), ParseError> {
        let (name, size) = Name::parse(buff, pos)?;
        let n = size + pos;
        Ok((
            RecordPreamble {
                name,
                rrtype: safe_u16_read(buff, n)?.into(),
                class: safe_u16_read(buff, n + 2)?.into(),
                ttl: safe_i32_read(buff, n + 4)?,
                rdlen: safe_u16_read(buff, n + 8)?,
            },
            size + 10,
        ))
    }

    #[inline]
    fn serialize(&self, packet: &mut Vec<u8>) {
        self.name.serialize(packet);
        push_u16(packet, self.rrtype.into());
        push_u16(packet, self.class.into());
        push_i32(packet, self.ttl);
        push_u16(packet, self.rdlen);
    }
}

/// The [ResourceRecord] data associated with the corresponding [Name].
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum RecordData<'a> {
    /// A host address.
    A(Ipv4Addr),
    /// An authoritative name server
    Ns(Name<'a>),
    /// The canonical name for an alias.
    Cname(Name<'a>),
    /// Mail exchange.
    Mx {
        /// The preference given to this RR among others at the same owner.
        preference: u16,
        /// A host willing to act as a mail exchange for the owner name.
        exchange: Name<'a>,
    },
    /// Text strings
    Txt(Cow<'a, str>),
    /// A host address IPv6
    Aaaa(Ipv6Addr),
    /// ?: A value has been received that does not correspond to any known type.
    Unknown(Cow<'a, [u8]>),
}

impl<'a> RecordData<'a> {
    #[inline]
    fn parse(
        buff: &'a [u8],
        pos: usize,
        rrpreamble: &RecordPreamble<'_>,
    ) -> Result<(Self, usize), ParseError> {
        match rrpreamble.rrtype {
            Type::A => Ok((Self::A(safe_ipv4_read(buff, pos)?), 4)),
            Type::Ns => {
                let (name, n) = Name::parse(buff, pos)?;
                Ok((Self::Ns(name), n))
            }
            Type::Cname => {
                let (name, n) = Name::parse(buff, pos)?;
                Ok((Self::Cname(name), n))
            }
            Type::Mx => {
                let (exchange, n) = Name::parse(buff, pos + 2)?;
                Ok((
                    Self::Mx {
                        preference: safe_u16_read(buff, pos)?,
                        exchange,
                    },
                    n + 2,
                ))
            }
            Type::Txt => {
                let len = safe_u8_read(buff, pos)?;
                let str_bytes = str::from_utf8(&buff[pos..pos + len as usize])?;
                Ok((Self::Txt(Cow::from(str_bytes)), len as _))
            }
            Type::Aaaa => Ok((Self::Aaaa(safe_ipv6_read(buff, pos)?), 16)),
            Type::Unknown(_) => {
                let len = rrpreamble.rdlen as _;
                let end = pos + len;
                if buff.len() < end {
                    Err(ParseError::OobRead(end))?
                }
                let cow_bytes = Cow::from(&buff[pos..end]);
                Ok((Self::Unknown(cow_bytes), len))
            }
        }
    }

    #[inline]
    fn serialize(&self, packet: &mut Vec<u8>) {
        use std::ops::Deref;
        match self {
            Self::A(ip) => packet.extend(ip.octets()),
            Self::Ns(name) => name.serialize(packet),
            Self::Cname(name) => name.serialize(packet),
            Self::Mx {
                preference,
                exchange,
            } => {
                push_u16(packet, *preference);
                exchange.serialize(packet);
            }
            Self::Txt(txt) => {
                // <character-string> is a single length octet followed by that number of characters.
                // <character-string> is treated as binary information, and can be up to 256 characters in
                // length (including the length octet).
                packet.push(txt.len() as _);
                packet.extend(txt.as_bytes());
            }
            Self::Aaaa(ip) => packet.extend(ip.octets()),
            Self::Unknown(buff) => packet.extend(buff.deref()),
        }
    }
}

types! {
    /// A host address (IPv4)
    A = 1
    /// An authoritative name server
    Ns = 2
    /// The canonical name for an alias
    Cname = 5
    /// A mail exchange
    Mx = 15
    /// Text strings
    Txt = 16
    /// A host address (IPv6)
    Aaaa = 28
}

/// An enumeration of the different available DNS Classes.
///
/// In practice should allways be `Class::IN`, but the rest are included for completeness.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd)]
pub enum Class {
    /// IN: the Internet
    IN,
    /// CS: the CSNET class (Obsolete)
    CS,
    /// CH: the CHAOS class
    CH,
    /// HS: Hesiod [Dyer 87]
    HS,
    /// *: any class
    Any,
    /// ?: A value has been received that does not correspond to any known class
    Unknown(u16),
}

impl From<u16> for Class {
    #[inline]
    fn from(value: u16) -> Self {
        match value {
            1 => Self::IN,
            2 => Self::CS,
            3 => Self::CH,
            4 => Self::HS,
            255 => Self::Any,
            _ => Self::Unknown(value),
        }
    }
}

impl From<Class> for u16 {
    #[inline]
    fn from(value: Class) -> Self {
        match value {
            Class::IN => 1,
            Class::CS => 2,
            Class::CH => 3,
            Class::HS => 4,
            Class::Any => 255,
            Class::Unknown(n) => n,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn class_transformations() {
        assert_eq!(Class::IN, From::from(1u16));
        assert_eq!(Class::CS, From::from(2u16));
        assert_eq!(Class::CH, From::from(3u16));
        assert_eq!(Class::HS, From::from(4u16));
        assert_eq!(Class::Any, From::from(255u16));
        assert_eq!(Class::Unknown(225u16), From::from(225u16));

        assert_eq!(1u16, From::from(Class::IN));
        assert_eq!(2u16, From::from(Class::CS));
        assert_eq!(3u16, From::from(Class::CH));
        assert_eq!(4u16, From::from(Class::HS));
        assert_eq!(255u16, From::from(Class::Any));
        assert_eq!(225u16, From::from(Class::Unknown(225u16)));
    }

    #[test]
    fn qtype_transformations() {
        assert_eq!(QType::A, From::from(1u16));
        assert_eq!(QType::Ns, From::from(2u16));
        assert_eq!(QType::Cname, From::from(5u16));
        assert_eq!(QType::Mx, From::from(15u16));
        assert_eq!(QType::All, From::from(255u16));
        assert_eq!(QType::Unknown(225u16), From::from(225u16));

        assert_eq!(1u16, From::from(QType::A));
        assert_eq!(2u16, From::from(QType::Ns));
        assert_eq!(5u16, From::from(QType::Cname));
        assert_eq!(15u16, From::from(QType::Mx));
        assert_eq!(255u16, From::from(QType::All));
        assert_eq!(225u16, From::from(QType::Unknown(225u16)));
    }
}