Skip to main content

hickory_proto/serialize/txt/
zone.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use alloc::{
9    borrow::Cow,
10    collections::btree_map::{BTreeMap, Entry},
11    string::String,
12    vec::Vec,
13};
14use core::{mem, str::FromStr};
15use std::{
16    fs,
17    path::{Path, PathBuf},
18};
19
20use crate::{
21    rr::{DNSClass, LowerName, Name, RData, Record, RecordSet, RecordType, RrKey},
22    serialize::txt::{
23        ParseError, ParseResult, parse_ttl,
24        zone_lex::{Lexer, Token},
25    },
26};
27
28/// ```text
29/// 5. ZONE FILES
30///
31/// Zone files are text files that contain RRs in text form.  Since the
32/// contents of a zone can be expressed in the form of a list of RRs a
33/// Zone File is most often used to define a zone, though it can be used
34/// to list a cache's contents.  Hence, this section first discusses the
35/// format of RRs in a Zone File, and then the special considerations when
36/// a Zone File is used to create a zone in some name server.
37///
38/// 5.1. Format
39///
40/// The format of these files is a sequence of entries.  Entries are
41/// predominantly line-oriented, though parentheses can be used to continue
42/// a list of items across a line boundary, and text literals can contain
43/// CRLF within the text.  Any combination of tabs and spaces act as a
44/// delimiter between the separate items that make up an entry.  The end of
45/// any line in the Zone File can end with a comment.  The comment starts
46/// with a ";" (semicolon).
47///
48/// The following entries are defined:
49///
50///     <blank>[<comment>]
51///
52///     $ORIGIN <domain-name> [<comment>]
53///
54///     $INCLUDE <file-name> [<domain-name>] [<comment>]
55///
56///     <domain-name><rr> [<comment>]
57///
58///     <blank><rr> [<comment>]
59///
60/// Blank lines, with or without comments, are allowed anywhere in the file.
61///
62/// Two control entries are defined: $ORIGIN and $INCLUDE.  $ORIGIN is
63/// followed by a domain name, and resets the current origin for relative
64/// domain names to the stated name.  $INCLUDE inserts the named file into
65/// the current file, and may optionally specify a domain name that sets the
66/// relative domain name origin for the included file.  $INCLUDE may also
67/// have a comment.  Note that a $INCLUDE entry never changes the relative
68/// origin of the parent file, regardless of changes to the relative origin
69/// made within the included file.
70///
71/// The last two forms represent RRs.  If an entry for an RR begins with a
72/// blank, then the RR is assumed to be owned by the last stated owner.  If
73/// an RR entry begins with a <domain-name>, then the owner name is reset.
74///
75/// <rr> contents take one of the following forms:
76///
77///     [<TTL>] [<class>] <type> <RDATA>
78///
79///     [<class>] [<TTL>] <type> <RDATA>
80///
81/// The RR begins with optional TTL and class fields, followed by a type and
82/// RDATA field appropriate to the type and class.  Class and type use the
83/// standard mnemonics, TTL is a decimal integer.  Omitted class and TTL
84/// values are default to the last explicitly stated values.  Since type and
85/// class mnemonics are disjoint, the parse is unique.  (Note that this
86/// order is different from the order used in examples and the order used in
87/// the actual RRs; the given order allows easier parsing and defaulting.)
88///
89/// <domain-name>s make up a large share of the data in the Zone File.
90/// The labels in the domain name are expressed as character strings and
91/// separated by dots.  Quoting conventions allow arbitrary characters to be
92/// stored in domain names.  Domain names that end in a dot are called
93/// absolute, and are taken as complete.  Domain names which do not end in a
94/// dot are called relative; the actual domain name is the concatenation of
95/// the relative part with an origin specified in a $ORIGIN, $INCLUDE, or as
96/// an argument to the Zone File loading routine.  A relative name is an
97/// error when no origin is available.
98///
99/// <character-string> is expressed in one or two ways: as a contiguous set
100/// of characters without interior spaces, or as a string beginning with a "
101/// and ending with a ".  Inside a " delimited string any character can
102/// occur, except for a " itself, which must be quoted using \ (back slash).
103///
104/// Because these files are text files several special encodings are
105/// necessary to allow arbitrary data to be loaded.  In particular:
106///
107///                 of the root.
108///
109/// @               A free standing @ is used to denote the current origin.
110///
111/// \X              where X is any character other than a digit (0-9), is
112///                 used to quote that character so that its special meaning
113///                 does not apply.  For example, "\." can be used to place
114///                 a dot character in a label.
115///
116/// \DDD            where each D is a digit is the octet corresponding to
117///                 the decimal number described by DDD.  The resulting
118///                 octet is assumed to be text and is not checked for
119///                 special meaning.
120///
121/// ( )             Parentheses are used to group data that crosses a line
122///                 boundary.  In effect, line terminations are not
123///                 recognized within parentheses.
124///
125/// ;               Semicolon is used to start a comment; the remainder of
126///                 the line is ignored.
127/// ```
128pub struct Parser<'a> {
129    lexers: Vec<(Lexer<'a>, Option<PathBuf>)>,
130    origin: Option<Name>,
131}
132
133impl<'a> Parser<'a> {
134    /// Returns a new Zone file parser
135    ///
136    /// The `path` argument's parent directory is used to resolve relative `$INCLUDE` paths.
137    /// Relative `$INCLUDE` paths will yield an error if `path` is `None`.
138    pub fn new(
139        input: impl Into<Cow<'a, str>>,
140        path: Option<PathBuf>,
141        mut origin: Option<Name>,
142    ) -> Self {
143        if let Some(origin) = &mut origin {
144            origin.set_fqdn(true);
145        }
146        Self {
147            lexers: vec![(Lexer::new(input), path)],
148            origin,
149        }
150    }
151
152    /// Parse a file from the Lexer
153    ///
154    /// # Return
155    ///
156    /// A pair of the Zone origin name and a map of all Keys to RecordSets
157    pub fn parse(mut self) -> ParseResult<(Name, BTreeMap<RrKey, RecordSet>)> {
158        let mut cx = Context::new(self.origin);
159        let mut state = State::StartLine;
160        let mut stack = self.lexers.len();
161
162        'outer: while let Some((lexer, path)) = self.lexers.last_mut() {
163            while let Some(t) = lexer.next_token()? {
164                state = match state {
165                    State::StartLine => {
166                        // current_name is not reset on the next line b/c it might be needed from the previous
167                        cx.rtype = None;
168
169                        match t {
170                            // if Dollar, then $INCLUDE or $ORIGIN
171                            Token::Include => State::Include(None),
172                            Token::Origin => State::Origin,
173                            Token::Ttl => State::Ttl,
174
175                            // if CharData, then Name then ttl_class_type
176                            Token::CharData(data) => {
177                                cx.current_name = Some(Name::parse(&data, cx.origin.as_ref())?);
178                                State::TtlClassType { rr_started: true }
179                            }
180
181                            // @ is a placeholder for specifying the current origin
182                            Token::At => {
183                                cx.current_name.clone_from(&cx.origin); // TODO a COW or RC would reduce copies...
184                                State::TtlClassType { rr_started: true }
185                            }
186
187                            // if blank, then nothing or ttl_class_type
188                            Token::Blank => State::TtlClassType { rr_started: false },
189                            Token::EOL => State::StartLine, // probably a comment
190                            _ => return Err(ParseError::UnexpectedToken(t)),
191                        }
192                    }
193                    State::Ttl => match t {
194                        Token::CharData(data) => {
195                            cx.ttl.default = Some(parse_ttl(&data)?);
196                            State::StartLine
197                        }
198                        _ => return Err(ParseError::UnexpectedToken(t)),
199                    },
200                    State::Origin => {
201                        match t {
202                            Token::CharData(data) => {
203                                // a relative name is relative to the current origin (RFC 1035 section 5.1)
204                                cx.origin = Some(Name::parse(&data, cx.origin.as_ref())?);
205                                State::StartLine
206                            }
207                            _ => return Err(ParseError::UnexpectedToken(t)),
208                        }
209                    }
210                    State::Include(include_path) => match (t, include_path) {
211                        (Token::CharData(data), None) => State::Include(Some(data)),
212                        (Token::EOL, Some(include_path)) => {
213                            // RFC1035 (section 5) does not specify how filename for $INCLUDE
214                            // should be resolved into file path. The underlying code implements the
215                            // following:
216                            // * if the path is absolute (relies on Path::is_absolute), it uses normalized path
217                            // * otherwise, it joins the path with parent root of the current file
218                            //
219                            // TODO: Inlining files specified using non-relative path might potentially introduce
220                            // security issue in some cases (e.g. when working with zone files from untrusted sources)
221                            // and should probably be configurable by user.
222
223                            if stack > MAX_INCLUDE_LEVEL {
224                                return Err(ParseError::Message(
225                                    "Max depth level for nested $INCLUDE is reached",
226                                ));
227                            }
228
229                            let include = Path::new(&include_path);
230                            let include = match (include.is_absolute(), path) {
231                                (true, _) => include.to_path_buf(),
232                                (false, Some(path)) => path
233                                    .parent()
234                                    .expect("file has to have parent folder")
235                                    .join(include),
236                                (false, None) => {
237                                    return Err(ParseError::Message(
238                                        "Relative $INCLUDE is not supported",
239                                    ));
240                                }
241                            };
242
243                            let input = fs::read_to_string(&include)?;
244                            let lexer = Lexer::new(input);
245                            self.lexers.push((lexer, Some(include)));
246                            stack += 1;
247                            state = State::StartLine;
248                            continue 'outer;
249                        }
250                        (Token::CharData(_), Some(_)) => {
251                            return Err(ParseError::Message(
252                                "Domain name for $INCLUDE is not supported",
253                            ));
254                        }
255                        (t, _) => {
256                            return Err(ParseError::UnexpectedToken(t));
257                        }
258                    },
259                    State::TtlClassType { rr_started } => {
260                        match t {
261                            // if number, TTL
262                            // Token::Number(num) => ttl = Some(*num),
263                            // One of Class or Type (these cannot be overlapping!)
264                            Token::CharData(mut data) => {
265                                // if it's a number it's a ttl
266                                let result: ParseResult<u32> = parse_ttl(&data);
267                                if let Ok(ttl) = result {
268                                    cx.ttl.this = Some(ttl);
269                                    State::TtlClassType { rr_started: true } // hm, should this go to just ClassType?
270                                } else {
271                                    // if can parse DNSClass, then class
272                                    data.make_ascii_uppercase();
273                                    let result = DNSClass::from_str(&data);
274                                    if let Ok(parsed) = result {
275                                        // RFC 1035 section 3.6: NONE and ANY (`*`) are only
276                                        // valid as QCLASS values, not as the class of a record.
277                                        if matches!(parsed, DNSClass::NONE | DNSClass::ANY) {
278                                            return Err(ParseError::from(format!(
279                                                "query-only class {data} is not allowed in a zone file"
280                                            )));
281                                        }
282                                        cx.class = parsed;
283                                        State::TtlClassType { rr_started: true }
284                                    } else {
285                                        // if can parse RecordType, then RecordType
286                                        cx.rtype = Some(RecordType::from_str(&data)?);
287                                        State::Record(vec![])
288                                    }
289                                }
290                            }
291                            // could be nothing if started with blank and is a comment, i.e. EOL
292                            Token::EOL if !rr_started => State::StartLine,
293                            // an owner, TTL or class was given, but no type
294                            Token::EOL => {
295                                return Err(ParseError::from("record type not specified"));
296                            }
297                            _ => return Err(ParseError::UnexpectedToken(t)),
298                        }
299                    }
300                    State::Record(record_parts) => {
301                        // b/c of ownership rules, perhaps, just collect all the RData components as a list of
302                        //  tokens to pass into the processor
303                        match t {
304                            Token::EOL => {
305                                cx.insert(record_parts)?;
306                                State::StartLine
307                            }
308                            Token::CharData(part) => {
309                                let mut record_parts = record_parts;
310                                record_parts.push(part);
311                                State::Record(record_parts)
312                            }
313                            // TODO: we should not tokenize the list...
314                            Token::List(list) => {
315                                let mut record_parts = record_parts;
316                                record_parts.extend(list);
317                                State::Record(record_parts)
318                            }
319                            _ => return Err(ParseError::UnexpectedToken(t)),
320                        }
321                    }
322                };
323            }
324
325            // Extra flush at the end for the case of missing endline
326            match mem::replace(&mut state, State::StartLine) {
327                State::Record(record_parts) => cx.insert(record_parts)?,
328                State::TtlClassType { rr_started: true } => {
329                    return Err(ParseError::from("record type not specified"));
330                }
331                _ => {}
332            }
333
334            stack -= 1;
335            self.lexers.pop();
336        }
337
338        //
339        // build the Authority and return.
340        let origin = cx
341            .origin
342            .ok_or(ParseError::Message("$ORIGIN was not specified"))?;
343        Ok((origin, cx.records))
344    }
345}
346
347#[derive(Default)]
348struct Ttl {
349    default: Option<u32>,
350    last: Option<u32>,
351    this: Option<u32>,
352}
353
354impl Ttl {
355    fn take(&mut self) -> Option<u32> {
356        if let Some(ttl) = self.this.take() {
357            self.last.replace(ttl);
358            return Some(ttl);
359        }
360        if let Some(ttl) = self.default {
361            return Some(ttl);
362        }
363        if let Some(ttl) = self.last {
364            return Some(ttl);
365        }
366
367        None
368    }
369}
370
371struct Context {
372    origin: Option<Name>,
373    records: BTreeMap<RrKey, RecordSet>,
374    class: DNSClass,
375    current_name: Option<Name>,
376    rtype: Option<RecordType>,
377    ttl: Ttl,
378}
379
380impl Context {
381    fn new(origin: Option<Name>) -> Self {
382        Self {
383            origin,
384            records: BTreeMap::default(),
385            class: DNSClass::IN,
386            current_name: None,
387            rtype: None,
388            ttl: Ttl::default(),
389        }
390    }
391
392    fn insert(&mut self, record_parts: Vec<String>) -> ParseResult<()> {
393        // call out to parsers for difference record types
394        // all tokens as part of the Record should be chardata...
395        let rtype = self
396            .rtype
397            .ok_or_else(|| ParseError::from("record type not specified"))?;
398
399        let rdata = RData::from_tokens(
400            rtype,
401            record_parts.iter().map(AsRef::as_ref),
402            self.origin.as_ref(),
403        )?;
404
405        // verify that we have everything we need for the record
406        // TODO COW or RC would reduce mem usage, perhaps Name should have an intern()...
407        //  might want to wait until RC.weak() stabilizes, as that would be needed for global
408        //  memory where you want
409        let mut name = self
410            .current_name
411            .clone()
412            .ok_or_else(|| ParseError::from("record name not specified"))?;
413
414        let ttl = self
415            .ttl
416            .take()
417            .ok_or_else(|| ParseError::from("record ttl not specified"))?;
418
419        // TODO: validate record, e.g. the name of SRV record allows _ but others do not.
420
421        // move the rdata into record...
422        name.set_fqdn(true);
423        let mut record = Record::from_rdata(name, ttl, rdata);
424        record.dns_class = self.class;
425
426        // add to the map
427        let entry = self.records.entry(RrKey::new(
428            LowerName::new(&record.name),
429            record.record_type(),
430        ));
431        match (rtype, entry) {
432            (RecordType::SOA, Entry::Occupied(_)) => {
433                return Err(ParseError::from("SOA is already specified"));
434            }
435            (_, Entry::Vacant(entry)) => {
436                entry.insert(RecordSet::from(record));
437            }
438            (_, Entry::Occupied(mut entry)) => {
439                entry.get_mut().insert(record, 0);
440            }
441        };
442
443        Ok(())
444    }
445}
446
447enum State {
448    StartLine, // start of line, @, $<WORD>, Name, Blank
449    // [<TTL>] [<class>] <type>; `rr_started` is set once an owner, TTL or class was given
450    TtlClassType { rr_started: bool },
451    Ttl, // $TTL <time>
452    Record(Vec<String>),
453    Include(Option<String>), // $INCLUDE <filename>
454    Origin,
455}
456
457/// Max traversal depth for $INCLUDE files
458const MAX_INCLUDE_LEVEL: usize = 256;
459
460#[cfg(test)]
461mod tests {
462    use alloc::string::ToString;
463
464    use super::*;
465
466    #[test]
467    #[allow(clippy::uninlined_format_args)]
468    fn test_zone_parse() {
469        let domain = Name::from_str("parameter.origin.org.").unwrap();
470
471        let zone_data = r#"$ORIGIN parsed.zone.origin.org.
472 faulty-record-type 60 IN A 1.2.3.4
473"#;
474
475        let result = Parser::new(zone_data, None, Some(domain)).parse();
476        assert!(
477            result.is_err()
478                & result
479                    .as_ref()
480                    .unwrap_err()
481                    .to_string()
482                    .contains("FAULTY-RECORD-TYPE"),
483            "unexpected success: {:#?}",
484            result
485        );
486    }
487
488    #[test]
489    fn test_missing_record_type() {
490        // https://github.com/hickory-dns/hickory-dns/issues/3952
491        for rr in [
492            "www 3600 IN",
493            "www IN",
494            "www 3600",
495            "www",
496            "@ 3600 IN",
497            " 3600 IN",
498            "www 3600 IN ; comment",
499        ] {
500            for eol in ["\n", ""] {
501                let zone_data = format!("$ORIGIN example.com.\n$TTL 3600\n{rr}{eol}");
502                let result = Parser::new(zone_data, None, None).parse();
503                assert!(
504                    result
505                        .as_ref()
506                        .is_err_and(|e| e.to_string().contains("record type not specified")),
507                    "unexpected result for {rr:?}: {result:#?}"
508                );
509            }
510        }
511    }
512
513    #[test]
514    fn test_relative_origin() {
515        let zone_data = "$ORIGIN example.com.
516$TTL 3600
517$ORIGIN sub
518www IN A 192.0.2.1
519$ORIGIN deeper
520@ IN A 192.0.2.2
521";
522        let (_, records) = Parser::new(zone_data, None, None).parse().unwrap();
523        let owners = records
524            .values()
525            .map(|rrset| rrset.name().to_string())
526            .collect::<Vec<_>>();
527        assert_eq!(
528            owners,
529            ["deeper.sub.example.com.", "www.sub.example.com."],
530            "unexpected owners: {owners:?}"
531        );
532    }
533
534    #[test]
535    fn test_blank_and_comment_lines() {
536        let zone_data = [
537            "$ORIGIN example.com.",
538            "$TTL 3600",
539            "",
540            "\t ",
541            "; comment",
542            "   ; indented comment",
543            "www 3600 IN A 192.0.2.1",
544            " \t",
545        ]
546        .join("\n");
547        let (origin, records) = Parser::new(zone_data, None, None).parse().unwrap();
548        assert_eq!(origin, Name::from_str("example.com.").unwrap());
549        assert_eq!(records.len(), 1);
550        let rrset = records.values().next().unwrap();
551        assert_eq!(rrset.name(), &Name::from_str("www.example.com.").unwrap());
552        assert_eq!(rrset.record_type(), RecordType::A);
553    }
554
555    #[test]
556    fn test_query_only_class_is_rejected() {
557        // https://github.com/hickory-dns/hickory-dns/issues/3956
558        for rr in [
559            "www 3600 ANY A 192.0.2.1",
560            "www 3600 * A 192.0.2.1",
561            "www 3600 NONE A 192.0.2.1",
562            "www ANY 3600 A 192.0.2.1",
563            "www 3600 any A 192.0.2.1",
564        ] {
565            let zone_data = format!("$ORIGIN example.com.\n{rr}\n");
566            let result = Parser::new(zone_data, None, None).parse();
567            assert!(
568                result
569                    .as_ref()
570                    .is_err_and(|e| e.to_string().contains("query-only class")),
571                "unexpected result for {rr:?}: {result:#?}"
572            );
573        }
574
575        for rr in ["www 3600 IN A 192.0.2.1", "www 3600 CH A 192.0.2.1"] {
576            let zone_data = format!("$ORIGIN example.com.\n{rr}\n");
577            Parser::new(zone_data, None, None).parse().unwrap();
578        }
579    }
580
581    #[test]
582    fn empty_txt_record_is_rejected() {
583        let domain = Name::from_str("example.com.").unwrap();
584
585        let zone_data = r#"$ORIGIN example.com.
586empty 300 IN TXT
587"#;
588
589        let result = Parser::new(zone_data, None, Some(domain)).parse();
590
591        assert!(
592            result.is_err(),
593            "an empty TXT record should be rejected: {:#?}",
594            result
595        );
596    }
597}