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
use std::borrow::Cow;
use std::convert::TryFrom;
use std::net::{Ipv4Addr, Ipv6Addr};

/// flag_enum creates enum which may be either known or unknown(yet) flag.
macro_rules! flag_enum {
    (
        $name:ident, $any_name:ident: $val_ty:ty {
             $(
                $variant_name:ident = $variant_val:tt
             ),*
        }

    ) => {
        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
        pub enum $name {
            $(
                $variant_name = ($variant_val) as isize
            ),*
        }

        impl $name {
            // deprecate this fn?
            #[inline]
            pub fn try_from_num(n: $val_ty) -> Result<Self, ()> {
                Self::try_from(n)
            }

            #[inline]
            pub fn into_num(self) -> $val_ty {
                self.into()
            }
        }

        impl Into<$val_ty> for $name {
            #[inline]
            fn into(self) -> $val_ty {
                match self {
                    $(
                        Self::$variant_name => $variant_val
                    ),*
                }
            }
        }

        impl TryFrom<$val_ty> for $name {
            type Error = ();

            #[inline]
            fn try_from(val: $val_ty) -> Result<Self, Self::Error> {
                match val {
                    $(
                        $variant_val => Ok(Self::$variant_name),
                    )*
                    _ => Err(()),
                }
            }
        }

        /*
        impl Into<$any_name> for $name {
            fn into(self) -> $any_name {
                $any_name::Known(self)
            }
        }
        */

        impl From<$name> for $any_name {
            fn from(data: $name) -> $any_name {
                $any_name::Known(data)
            }
        }

        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
        pub enum $any_name {
            Known($name),
            Unknown($val_ty)
        }

        impl $any_name {
            pub fn into_canonical(self) -> Self {
                match self {
                    Self::Known(v) => Self::Known(v),
                    Self::Unknown(v) => match $name::try_from(v) {
                        Ok(new_v) => Self::Known(new_v),
                        Err(_) => Self::Unknown(v),
                    }
                }
            }
        }

        impl Into<$val_ty> for $any_name {
            #[inline]
            fn into(self) -> $val_ty {
                match self {
                    Self::Known(v) => v.into(),
                    Self::Unknown(v) => v,
                }
            }
        }

        impl From<$val_ty> for $any_name {
            #[inline]
            fn from(val: $val_ty) -> Self {
                Self::Unknown(val).into_canonical()
            }
        }
    }
}

/// MaybeValidString contains either `&str` or `&[u8]` in case parser was not able to parse it.
/// Both types are wrapped in cows
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[derive(From, TryInto)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum MaybeValidString<'a> {
    Parsed(Cow<'a, str>),
    Raw(Cow<'a, [u8]>),
}

impl<'a> From<&'a str> for MaybeValidString<'a> {
    fn from(text: &'a str) -> Self {
        MaybeValidString::Parsed(Cow::Borrowed(text))
    }
}

impl<'a> From<&'a [u8]> for MaybeValidString<'a> {
    fn from(data: &'a [u8]) -> Self {
        MaybeValidString::Raw(Cow::Borrowed(data))
    }
}

impl<'a> MaybeValidString<'a> {
    pub fn into_canonical(self) -> Self {
        match self {
            MaybeValidString::Parsed(text) => Self::Parsed(text),
            MaybeValidString::Raw(data) => {
                match data {
                    Cow::Borrowed(v) => match std::str::from_utf8(v) {
                        Ok(v) => Self::Parsed(Cow::Borrowed(v)),
                        Err(_) => Self::Raw(data),
                    }
                    Cow::Owned(v) => {
                        // for performance reason we are going to use some unsafe glue here

                        // Note: in fact what is done here is done already in STD lib:
                        //      1. run check
                        //      2. If it passes return Ok from unsafe function result else return Err

                        // 0. if v is not valid str return self as-is without changes
                        if let Ok(text) = std::str::from_utf8(&v) {
                            Self::Parsed(Cow::Owned(text.to_string()))
                        } else {
                            Self::Raw(Cow::Owned(v))
                        }
                    }
                }
            }
        }
    }

    pub fn into_owned(self) -> MaybeValidString<'static> {
        match self {
            MaybeValidString::Parsed(a) => MaybeValidString::Parsed(Cow::Owned(a.into_owned())),
            MaybeValidString::Raw(a) => MaybeValidString::Raw(Cow::Owned(a.into_owned())),
        }
    }
}

flag_enum!(
    DnsType, AnyDnsType: u16 {
        A = 1,
        NS = 2,
        CNAME = 5,
        SOA = 6,
        PTR = 12,
        HINFO = 13,
        MINFO = 14,
        MX = 15,
        TXT = 16,
        AAAA = 28,
        SRV = 33
    }
);

flag_enum!(
    DnsClass, AnyDnsClass: u16 {
        IN = 1,
        CS = 2,
        CH = 3,
        HS = 4
    }
);

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SrvData<'a> {
    pub target: MaybeValidString<'a>,
    pub port: u16,
    pub priority: u16,
    pub weight: u16,
}

impl<'a> SrvData<'a> {
    pub fn into_owned(self) -> SrvData<'static> {
        SrvData {
            target: self.target.into_owned(),
            port: self.port,
            priority: self.priority,
            weight: self.weight,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct SoaData<'a> {
    pub mname: MaybeValidString<'a>,
    pub rname: MaybeValidString<'a>,
    pub serial: u32,
    pub refresh: i32,
    pub retry: i32,
    pub expire: i32,
    pub minimum: u32,
}

impl<'a> SoaData<'a> {
    pub fn into_owned(self) -> SoaData<'static> {
        SoaData {
            mname: self.mname.into_owned(),
            rname: self.rname.into_owned(),
            serial: self.serial,
            refresh: self.refresh,
            retry: self.retry,
            expire: self.expire,
            minimum: self.minimum,
        }
    }
}

/// DNSRecord represents single DNS dns.packet that this library is able to parse
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum DnsRecord<'a> {
    A(Ipv4Addr),
    AAAA(Ipv6Addr),

    // CPU, OS fields
    HINFO(MaybeValidString<'a>, MaybeValidString<'a>),
    // RMAILBX, EMAILBX fields
    MINFO(MaybeValidString<'a>, MaybeValidString<'a>),

    CNAME(MaybeValidString<'a>),
    TXT(MaybeValidString<'a>),
    PTR(MaybeValidString<'a>),
    MX(MaybeValidString<'a>, u16),
    NS(MaybeValidString<'a>),
    SRV(SrvData<'a>),
    SOA(SoaData<'a>),
}

impl<'a> DnsRecord<'a> {
    pub fn into_owned(self) -> DnsRecord<'static> {
        match self {
            DnsRecord::A(a) => DnsRecord::A(a),
            DnsRecord::AAAA(a) => DnsRecord::AAAA(a),
            DnsRecord::HINFO(cpu, os) =>
                DnsRecord::HINFO(cpu.into_owned(), os.into_owned()),
            DnsRecord::MINFO(rmailbx, emailbx) =>
                DnsRecord::MINFO(rmailbx.into_owned(), emailbx.into_owned()),
            DnsRecord::CNAME(name) => DnsRecord::CNAME(name.into_owned()),
            DnsRecord::TXT(txt) => DnsRecord::TXT(txt.into_owned()),
            DnsRecord::PTR(ptr) => DnsRecord::PTR(ptr.into_owned()),
            DnsRecord::MX(name, priority) => DnsRecord::MX(name.into_owned(), priority),
            DnsRecord::NS(ns) => DnsRecord::NS(ns.into_owned()),
            DnsRecord::SRV(data) => DnsRecord::SRV(data.into_owned()),
            DnsRecord::SOA(data) => DnsRecord::SOA(data.into_owned())
        }
    }
}

flag_enum!(
    QueryKind, AnyQueryKind: u8 {
        StandardQuery = 0,
        InverseQuery = 1,
        ServerStatusRequest = 2
    }
);

flag_enum!(
    ResponseCode, AnyResponseCode: u8 {
        NoErrorCondition = 0,
        FormatError = 1,
        ServerFailure = 2,
        NameError = 3,
        NotImplemented = 4,
        Refused = 5
    }
);

/// DNSResponse is parsed response of DNS server.
/// It contains multiple `DnsAnswer`s
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DnsResponse<'a> {
    pub id: u16,
    pub answers: Vec<DnsAnswer<'a>>,

    /// query_kind is set dependent on opcode in query and it specifies kind of requested data
    pub query_kind: AnyQueryKind,

    /// response indicates if response was success or error
    pub response_code: AnyResponseCode,
}

impl<'a> DnsResponse<'a> {
    /// into_owned copies data if required in order to make struct lifetime `'static`
    pub fn into_owned(self) -> DnsResponse<'static> {
        DnsResponse {
            id: self.id,
            answers: self.answers.into_iter().map(|a| a.into_owned()).collect(),
            query_kind: self.query_kind,
            response_code: self.response_code,
        }
    }
}

/// DnsRequest is parsed(or manually constructed) dns request
/// which may be serialized and sent to DNS server.
///
/// Right now the only serialization destination format is DNS binary but it may be serialized
/// to some JSON specific for DNS resolver platform.
///
/// # Note
/// It does not contain fields which are.
pub struct DnsRequest<'a> {
    pub id: u16,

    /// query_name is domain name represented as string
    pub query_name: Cow<'a, str>,
    pub query_kind: AnyQueryKind,

    pub ty: AnyDnsType,
    pub cls: AnyDnsClass,
}

impl<'a> DnsRequest<'a> {
    /// make_simple constructs request with reasonable defaults to resolve given record type for given domain
    pub fn make_simple(ty: AnyDnsType, domain: &'a str) -> Self {
        DnsRequest {
            id: 0,
            query_name: Cow::Borrowed(domain),
            query_kind: AnyQueryKind::Known(QueryKind::StandardQuery),
            ty,
            cls: AnyDnsClass::Known(DnsClass::IN),
        }
    }
}

/// DNSResponse contains single response for given dns packet
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub struct DnsAnswer<'a> {
    pub record: Option<DnsRecord<'a>>,
    pub ty: AnyDnsType,
    pub cls: AnyDnsClass,
    pub ttl: u32,
    pub name: MaybeValidString<'a>,
}

impl<'a> DnsAnswer<'a> {
    pub fn into_owned(self) -> DnsAnswer<'static> {
        DnsAnswer {
            record: self.record.map(|r| r.into_owned()),
            ty: self.ty,
            cls: self.cls,
            ttl: self.ttl,
            name: self.name.into_owned(),
        }
    }
}