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
use crate::error::*;
use crate::message::header::{Header, HeaderInternal, Section};
use crate::message::name::Name;
use crate::message::question::Question;
use crate::message::resource::{unpack_resource_body, Resource, ResourceBody, ResourceHeader};
use crate::message::{DnsClass, DnsType};

// A Parser allows incrementally parsing a DNS message.
//
// When parsing is started, the Header is parsed. Next, each question can be
// either parsed or skipped. Alternatively, all Questions can be skipped at
// once. When all Questions have been parsed, attempting to parse Questions
// will return (nil, nil) and attempting to skip Questions will return
// (true, nil). After all Questions have been either parsed or skipped, all
// Answers, Authorities and Additionals can be either parsed or skipped in the
// same way, and each type of Resource must be fully parsed or skipped before
// proceeding to the next type of Resource.
//
// Note that there is no requirement to fully skip or parse the message.
#[derive(Default)]
pub struct Parser<'a> {
    pub msg: &'a [u8],
    pub header: HeaderInternal,

    pub section: Section,
    pub off: usize,
    pub index: usize,
    pub res_header_valid: bool,
    pub res_header: ResourceHeader,
}

impl<'a> Parser<'a> {
    // start parses the header and enables the parsing of Questions.
    pub fn start(&mut self, msg: &'a [u8]) -> Result<Header> {
        *self = Parser {
            msg,
            ..Default::default()
        };
        self.off = self.header.unpack(msg, 0)?;
        self.section = Section::Questions;
        Ok(self.header.header())
    }

    fn check_advance(&mut self, sec: Section) -> Result<()> {
        if self.section < sec {
            return Err(Error::ErrNotStarted);
        }
        if self.section > sec {
            return Err(Error::ErrSectionDone);
        }
        self.res_header_valid = false;
        if self.index == self.header.count(sec) as usize {
            self.index = 0;
            self.section = Section::from(1 + self.section as u8);
            return Err(Error::ErrSectionDone);
        }
        Ok(())
    }

    fn resource(&mut self, sec: Section) -> Result<Resource> {
        let header = self.resource_header(sec)?;
        self.res_header_valid = false;
        let (body, off) =
            unpack_resource_body(header.typ, self.msg, self.off, header.length as usize)?;
        self.off = off;
        self.index += 1;
        Ok(Resource {
            header,
            body: Some(body),
        })
    }

    fn resource_header(&mut self, sec: Section) -> Result<ResourceHeader> {
        if self.res_header_valid {
            return Ok(self.res_header.clone());
        }
        self.check_advance(sec)?;
        let mut hdr = ResourceHeader::default();
        let off = hdr.unpack(self.msg, self.off, 0)?;

        self.res_header_valid = true;
        self.res_header = hdr.clone();
        self.off = off;
        Ok(hdr)
    }

    fn skip_resource(&mut self, sec: Section) -> Result<()> {
        if self.res_header_valid {
            let new_off = self.off + self.res_header.length as usize;
            if new_off > self.msg.len() {
                return Err(Error::ErrResourceLen);
            }
            self.off = new_off;
            self.res_header_valid = false;
            self.index += 1;
            return Ok(());
        }
        self.check_advance(sec)?;

        self.off = Resource::skip(self.msg, self.off)?;
        self.index += 1;
        Ok(())
    }

    // question parses a single question.
    pub fn question(&mut self) -> Result<Question> {
        self.check_advance(Section::Questions)?;
        let mut name = Name::new("")?;
        let mut off = name.unpack(self.msg, self.off)?;
        let mut typ = DnsType::Unsupported;
        off = typ.unpack(self.msg, off)?;
        let mut class = DnsClass::default();
        off = class.unpack(self.msg, off)?;
        self.off = off;
        self.index += 1;
        Ok(Question { name, typ, class })
    }

    // all_questions parses all Questions.
    pub fn all_questions(&mut self) -> Result<Vec<Question>> {
        // Multiple questions are valid according to the spec,
        // but servers don't actually support them. There will
        // be at most one question here.
        //
        // Do not pre-allocate based on info in self.header, since
        // the data is untrusted.
        let mut qs = vec![];
        loop {
            match self.question() {
                Err(err) => {
                    if Error::ErrSectionDone == err {
                        return Ok(qs);
                    } else {
                        return Err(err);
                    }
                }
                Ok(q) => qs.push(q),
            }
        }
    }

    // skip_question skips a single question.
    pub fn skip_question(&mut self) -> Result<()> {
        self.check_advance(Section::Questions)?;
        let mut off = Name::skip(self.msg, self.off)?;
        off = DnsType::skip(self.msg, off)?;
        off = DnsClass::skip(self.msg, off)?;
        self.off = off;
        self.index += 1;
        Ok(())
    }

    // skip_all_questions skips all Questions.
    pub fn skip_all_questions(&mut self) -> Result<()> {
        loop {
            if let Err(err) = self.skip_question() {
                if Error::ErrSectionDone == err {
                    return Ok(());
                } else {
                    return Err(err);
                }
            }
        }
    }

    // answer_header parses a single answer ResourceHeader.
    pub fn answer_header(&mut self) -> Result<ResourceHeader> {
        self.resource_header(Section::Answers)
    }

    // answer parses a single answer Resource.
    pub fn answer(&mut self) -> Result<Resource> {
        self.resource(Section::Answers)
    }

    // all_answers parses all answer Resources.
    pub fn all_answers(&mut self) -> Result<Vec<Resource>> {
        // The most common query is for A/AAAA, which usually returns
        // a handful of IPs.
        //
        // Pre-allocate up to a certain limit, since self.header is
        // untrusted data.
        let mut n = self.header.answers as usize;
        if n > 20 {
            n = 20
        }
        let mut a = Vec::with_capacity(n);
        loop {
            match self.answer() {
                Err(err) => {
                    if Error::ErrSectionDone == err {
                        return Ok(a);
                    } else {
                        return Err(err);
                    }
                }
                Ok(r) => a.push(r),
            }
        }
    }

    // skip_answer skips a single answer Resource.
    pub fn skip_answer(&mut self) -> Result<()> {
        self.skip_resource(Section::Answers)
    }

    // skip_all_answers skips all answer Resources.
    pub fn skip_all_answers(&mut self) -> Result<()> {
        loop {
            if let Err(err) = self.skip_answer() {
                if Error::ErrSectionDone == err {
                    return Ok(());
                } else {
                    return Err(err);
                }
            }
        }
    }

    // authority_header parses a single authority ResourceHeader.
    pub fn authority_header(&mut self) -> Result<ResourceHeader> {
        self.resource_header(Section::Authorities)
    }

    // authority parses a single authority Resource.
    pub fn authority(&mut self) -> Result<Resource> {
        self.resource(Section::Authorities)
    }

    // all_authorities parses all authority Resources.
    pub fn all_authorities(&mut self) -> Result<Vec<Resource>> {
        // Authorities contains SOA in case of NXDOMAIN and friends,
        // otherwise it is empty.
        //
        // Pre-allocate up to a certain limit, since self.header is
        // untrusted data.
        let mut n = self.header.authorities as usize;
        if n > 10 {
            n = 10;
        }
        let mut a = Vec::with_capacity(n);
        loop {
            match self.authority() {
                Err(err) => {
                    if Error::ErrSectionDone == err {
                        return Ok(a);
                    } else {
                        return Err(err);
                    }
                }
                Ok(r) => a.push(r),
            }
        }
    }

    // skip_authority skips a single authority Resource.
    pub fn skip_authority(&mut self) -> Result<()> {
        self.skip_resource(Section::Authorities)
    }

    // skip_all_authorities skips all authority Resources.
    pub fn skip_all_authorities(&mut self) -> Result<()> {
        loop {
            if let Err(err) = self.skip_authority() {
                if Error::ErrSectionDone == err {
                    return Ok(());
                } else {
                    return Err(err);
                }
            }
        }
    }

    // additional_header parses a single additional ResourceHeader.
    pub fn additional_header(&mut self) -> Result<ResourceHeader> {
        self.resource_header(Section::Additionals)
    }

    // additional parses a single additional Resource.
    pub fn additional(&mut self) -> Result<Resource> {
        self.resource(Section::Additionals)
    }

    // all_additionals parses all additional Resources.
    pub fn all_additionals(&mut self) -> Result<Vec<Resource>> {
        // Additionals usually contain OPT, and sometimes A/AAAA
        // glue records.
        //
        // Pre-allocate up to a certain limit, since self.header is
        // untrusted data.
        let mut n = self.header.additionals as usize;
        if n > 10 {
            n = 10;
        }
        let mut a = Vec::with_capacity(n);
        loop {
            match self.additional() {
                Err(err) => {
                    if Error::ErrSectionDone == err {
                        return Ok(a);
                    } else {
                        return Err(err);
                    }
                }
                Ok(r) => a.push(r),
            }
        }
    }

    // skip_additional skips a single additional Resource.
    pub fn skip_additional(&mut self) -> Result<()> {
        self.skip_resource(Section::Additionals)
    }

    // skip_all_additionals skips all additional Resources.
    pub fn skip_all_additionals(&mut self) -> Result<()> {
        loop {
            if let Err(err) = self.skip_additional() {
                if Error::ErrSectionDone == err {
                    return Ok(());
                } else {
                    return Err(err);
                }
            }
        }
    }

    // resource_body parses a single resource_boy.
    //
    // One of the XXXHeader methods must have been called before calling this
    // method.
    pub fn resource_body(&mut self) -> Result<Box<dyn ResourceBody>> {
        if !self.res_header_valid {
            return Err(Error::ErrNotStarted);
        }
        let (rb, _off) = unpack_resource_body(
            self.res_header.typ,
            self.msg,
            self.off,
            self.res_header.length as usize,
        )?;
        self.off += self.res_header.length as usize;
        self.res_header_valid = false;
        self.index += 1;
        Ok(rb)
    }
}