Debian Codegraph @

scan.go

raw symbols SCIP
1 package dns
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "io/fs"
8 "math"
9 "os"
10 "path"
11 "path/filepath"
12 "strconv"
13 "strings"
14 )
15
16 const maxTok = 512 // Token buffer start size, and growth size amount.
17
18 // The maximum depth of $INCLUDE directives supported by the
19 // ZoneParser API.
20 const maxIncludeDepth = 7
21
22 // Tokenize a RFC 1035 zone file. The tokenizer will normalize it:
23 // * Add ownernames if they are left blank;
24 // * Suppress sequences of spaces;
25 // * Make each RR fit on one line (_NEWLINE is send as last)
26 // * Handle comments: ;
27 // * Handle braces - anywhere.
28 const (
29 // Zonefile
30 zEOF = iota
31 zString
32 zBlank
33 zQuote
34 zNewline
35 zRrtpe
36 zOwner
37 zClass
38 zDirOrigin // $ORIGIN
39 zDirTTL // $TTL
40 zDirInclude // $INCLUDE
41 zDirGenerate // $GENERATE
42
43 // Privatekey file
44 zValue
45 zKey
46
47 zExpectOwnerDir // Ownername
48 zExpectOwnerBl // Whitespace after the ownername
49 zExpectAny // Expect rrtype, ttl or class
50 zExpectAnyNoClass // Expect rrtype or ttl
51 zExpectAnyNoClassBl // The whitespace after _EXPECT_ANY_NOCLASS
52 zExpectAnyNoTTL // Expect rrtype or class
53 zExpectAnyNoTTLBl // Whitespace after _EXPECT_ANY_NOTTL
54 zExpectRrtype // Expect rrtype
55 zExpectRrtypeBl // Whitespace BEFORE rrtype
56 zExpectRdata // The first element of the rdata
57 zExpectDirTTLBl // Space after directive $TTL
58 zExpectDirTTL // Directive $TTL
59 zExpectDirOriginBl // Space after directive $ORIGIN
60 zExpectDirOrigin // Directive $ORIGIN
61 zExpectDirIncludeBl // Space after directive $INCLUDE
62 zExpectDirInclude // Directive $INCLUDE
63 zExpectDirGenerate // Directive $GENERATE
64 zExpectDirGenerateBl // Space after directive $GENERATE
65 )
66
67 // ParseError is a parsing error. It contains the parse error and the location in the io.Reader
68 // where the error occurred.
69 type ParseError struct {
70 file string
71 err string
72 wrappedErr error
73 lex lex
74 }
75
76 func (e *ParseError) Error() (s string) {
77 if e.file != "" {
78 s = e.file + ": "
79 }
80 if e.err == "" && e.wrappedErr != nil {
81 e.err = e.wrappedErr.Error()
82 }
83 s += "dns: " + e.err + ": " + strconv.QuoteToASCII(e.lex.token) + " at line: " +
84 strconv.Itoa(e.lex.line) + ":" + strconv.Itoa(e.lex.column)
85 return
86 }
87
88 func (e *ParseError) Unwrap() error { return e.wrappedErr }
89
90 type lex struct {
91 token string // text of the token
92 err bool // when true, token text has lexer error
93 value uint8 // value: zString, _BLANK, etc.
94 torc uint16 // type or class as parsed in the lexer, we only need to look this up in the grammar
95 line int // line in the file
96 column int // column in the file
97 }
98
99 // ttlState describes the state necessary to fill in an omitted RR TTL
100 type ttlState struct {
101 ttl uint32 // ttl is the current default TTL
102 isByDirective bool // isByDirective indicates whether ttl was set by a $TTL directive
103 }
104
105 // NewRR reads a string s and returns the first RR.
106 // If s contains no records, NewRR will return nil with no error.
107 //
108 // The class defaults to IN, TTL defaults to 3600, and
109 // origin for resolving relative domain names defaults to the DNS root (.).
110 // Full zone file syntax is supported, including directives like $TTL and $ORIGIN.
111 // All fields of the returned RR are set from the read data, except RR.Header().Rdlength which is set to 0.
112 // Is you need a partial resource record with no rdata - for instance - for dynamic updates, see the [ANY]
113 // documentation.
114 func NewRR(s string) (RR, error) {
115 if len(s) > 0 && s[len(s)-1] != '\n' { // We need a closing newline
116 return ReadRR(strings.NewReader(s+"\n"), "")
117 }
118 return ReadRR(strings.NewReader(s), "")
119 }
120
121 // ReadRR reads the RR contained in r.
122 //
123 // The string file is used in error reporting and to resolve relative
124 // $INCLUDE directives.
125 //
126 // See NewRR for more documentation.
127 func ReadRR(r io.Reader, file string) (RR, error) {
128 zp := NewZoneParser(r, ".", file)
129 zp.SetDefaultTTL(defaultTtl)
130 zp.SetIncludeAllowed(true)
131 rr, _ := zp.Next()
132 return rr, zp.Err()
133 }
134
135 // ZoneParser is a parser for an RFC 1035 style zonefile.
136 //
137 // Each parsed RR in the zone is returned sequentially from Next. An
138 // optional comment can be retrieved with Comment.
139 //
140 // The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are all
141 // supported. Although $INCLUDE is disabled by default.
142 // Note that $GENERATE's range support up to a maximum of 65535 steps.
143 //
144 // Basic usage pattern when reading from a string (z) containing the
145 // zone data:
146 //
147 // zp := NewZoneParser(strings.NewReader(z), "", "")
148 //
149 // for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
150 // // Do something with rr
151 // }
152 //
153 // if err := zp.Err(); err != nil {
154 // // log.Println(err)
155 // }
156 //
157 // Comments specified after an RR (and on the same line!) are
158 // returned too:
159 //
160 // foo. IN A 10.0.0.1 ; this is a comment
161 //
162 // The text "; this is comment" is returned from Comment. Comments inside
163 // the RR are returned concatenated along with the RR. Comments on a line
164 // by themselves are discarded.
165 //
166 // Callers should not assume all returned data in an Resource Record is
167 // syntactically correct, e.g. illegal base64 in RRSIGs will be returned as-is.
168 type ZoneParser struct {
169 c *zlexer
170
171 parseErr *ParseError
172
173 origin string
174 file string
175
176 defttl *ttlState
177
178 h RR_Header
179
180 // sub is used to parse $INCLUDE files and $GENERATE directives.
181 // Next, by calling subNext, forwards the resulting RRs from this
182 // sub parser to the calling code.
183 sub *ZoneParser
184 r io.Reader
185 fsys fs.FS
186
187 includeDepth uint8
188
189 includeAllowed bool
190 generateDisallowed bool
191 }
192
193 // NewZoneParser returns an RFC 1035 style zonefile parser that reads
194 // from r.
195 //
196 // The string file is used in error reporting and to resolve relative
197 // $INCLUDE directives. The string origin is used as the initial
198 // origin, as if the file would start with an $ORIGIN directive.
199 func NewZoneParser(r io.Reader, origin, file string) *ZoneParser {
200 var pe *ParseError
201 if origin != "" {
202 origin = Fqdn(origin)
203 if _, ok := IsDomainName(origin); !ok {
204 pe = &ParseError{file: file, err: "bad initial origin name"}
205 }
206 }
207
208 return &ZoneParser{
209 c: newZLexer(r),
210
211 parseErr: pe,
212
213 origin: origin,
214 file: file,
215 }
216 }
217
218 // SetDefaultTTL sets the parsers default TTL to ttl.
219 func (zp *ZoneParser) SetDefaultTTL(ttl uint32) {
220 zp.defttl = &ttlState{ttl, false}
221 }
222
223 // SetIncludeAllowed controls whether $INCLUDE directives are
224 // allowed. $INCLUDE directives are not supported by default.
225 //
226 // The $INCLUDE directive will open and read from a user controlled
227 // file on the system. Even if the file is not a valid zonefile, the
228 // contents of the file may be revealed in error messages, such as:
229 //
230 // /etc/passwd: dns: not a TTL: "root:x:0:0:root:/root:/bin/bash" at line: 1:31
231 // /etc/shadow: dns: not a TTL: "root:$6$<redacted>::0:99999:7:::" at line: 1:125
232 func (zp *ZoneParser) SetIncludeAllowed(v bool) {
233 zp.includeAllowed = v
234 }
235
236 // SetIncludeFS provides an [fs.FS] to use when looking for the target of
237 // $INCLUDE directives. ($INCLUDE must still be enabled separately by calling
238 // [ZoneParser.SetIncludeAllowed].) If fsys is nil, [os.Open] will be used.
239 //
240 // When fsys is an on-disk FS, the ability of $INCLUDE to reach files from
241 // outside its root directory depends upon the FS implementation. For
242 // instance, [os.DirFS] will refuse to open paths like "../../etc/passwd",
243 // however it will still follow links which may point anywhere on the system.
244 //
245 // FS paths are slash-separated on all systems, even Windows. $INCLUDE paths
246 // containing other characters such as backslash and colon may be accepted as
247 // valid, but those characters will never be interpreted by an FS
248 // implementation as path element separators. See [fs.ValidPath] for more
249 // details.
250 func (zp *ZoneParser) SetIncludeFS(fsys fs.FS) {
251 zp.fsys = fsys
252 }
253
254 // Err returns the first non-EOF error that was encountered by the
255 // ZoneParser.
256 func (zp *ZoneParser) Err() error {
257 if zp.parseErr != nil {
258 return zp.parseErr
259 }
260
261 if zp.sub != nil {
262 if err := zp.sub.Err(); err != nil {
263 return err
264 }
265 }
266
267 return zp.c.Err()
268 }
269
270 func (zp *ZoneParser) setParseError(err string, l lex) (RR, bool) {
271 zp.parseErr = &ParseError{file: zp.file, err: err, lex: l}
272 return nil, false
273 }
274
275 // Comment returns an optional text comment that occurred alongside
276 // the RR.
277 func (zp *ZoneParser) Comment() string {
278 if zp.parseErr != nil {
279 return ""
280 }
281
282 if zp.sub != nil {
283 return zp.sub.Comment()
284 }
285
286 return zp.c.Comment()
287 }
288
289 func (zp *ZoneParser) subNext() (RR, bool) {
290 if rr, ok := zp.sub.Next(); ok {
291 return rr, true
292 }
293
294 if zp.sub.r != nil {
295 if c, ok := zp.sub.r.(io.Closer); ok {
296 c.Close()
297 }
298 zp.sub.r = nil
299 }
300
301 if zp.sub.Err() != nil {
302 // We have errors to surface.
303 return nil, false
304 }
305
306 zp.sub = nil
307 return zp.Next()
308 }
309
310 // Next advances the parser to the next RR in the zonefile and
311 // returns the (RR, true). It will return (nil, false) when the
312 // parsing stops, either by reaching the end of the input or an
313 // error. After Next returns (nil, false), the Err method will return
314 // any error that occurred during parsing.
315 func (zp *ZoneParser) Next() (RR, bool) {
316 if zp.parseErr != nil {
317 return nil, false
318 }
319 if zp.sub != nil {
320 return zp.subNext()
321 }
322
323 // 6 possible beginnings of a line (_ is a space):
324 //
325 // 0. zRRTYPE -> all omitted until the rrtype
326 // 1. zOwner _ zRrtype -> class/ttl omitted
327 // 2. zOwner _ zString _ zRrtype -> class omitted
328 // 3. zOwner _ zString _ zClass _ zRrtype -> ttl/class
329 // 4. zOwner _ zClass _ zRrtype -> ttl omitted
330 // 5. zOwner _ zClass _ zString _ zRrtype -> class/ttl (reversed)
331 //
332 // After detecting these, we know the zRrtype so we can jump to functions
333 // handling the rdata for each of these types.
334
335 st := zExpectOwnerDir // initial state
336 h := &zp.h
337
338 for l, ok := zp.c.Next(); ok; l, ok = zp.c.Next() {
339 // zlexer spotted an error already
340 if l.err {
341 return zp.setParseError(l.token, l)
342 }
343
344 switch st {
345 case zExpectOwnerDir:
346 // We can also expect a directive, like $TTL or $ORIGIN
347 if zp.defttl != nil {
348 h.Ttl = zp.defttl.ttl
349 }
350
351 h.Class = ClassINET
352
353 switch l.value {
354 case zNewline:
355 st = zExpectOwnerDir
356 case zOwner:
357 name, ok := toAbsoluteName(l.token, zp.origin)
358 if !ok {
359 return zp.setParseError("bad owner name", l)
360 }
361
362 h.Name = name
363
364 st = zExpectOwnerBl
365 case zDirTTL:
366 st = zExpectDirTTLBl
367 case zDirOrigin:
368 st = zExpectDirOriginBl
369 case zDirInclude:
370 st = zExpectDirIncludeBl
371 case zDirGenerate:
372 st = zExpectDirGenerateBl
373 case zRrtpe:
374 h.Rrtype = l.torc
375
376 st = zExpectRdata
377 case zClass:
378 h.Class = l.torc
379
380 st = zExpectAnyNoClassBl
381 case zBlank:
382 // Discard, can happen when there is nothing on the
383 // line except the RR type
384 case zString:
385 ttl, ok := stringToTTL(l.token)
386 if !ok {
387 return zp.setParseError("not a TTL", l)
388 }
389
390 h.Ttl = ttl
391
392 if zp.defttl == nil || !zp.defttl.isByDirective {
393 zp.defttl = &ttlState{ttl, false}
394 }
395
396 st = zExpectAnyNoTTLBl
397 default:
398 return zp.setParseError("syntax error at beginning", l)
399 }
400 case zExpectDirIncludeBl:
401 if l.value != zBlank {
402 return zp.setParseError("no blank after $INCLUDE-directive", l)
403 }
404
405 st = zExpectDirInclude
406 case zExpectDirInclude:
407 if l.value != zString {
408 return zp.setParseError("expecting $INCLUDE value, not this...", l)
409 }
410
411 neworigin := zp.origin // There may be optionally a new origin set after the filename, if not use current one
412 switch l, _ := zp.c.Next(); l.value {
413 case zBlank:
414 l, _ := zp.c.Next()
415 if l.value == zString {
416 name, ok := toAbsoluteName(l.token, zp.origin)
417 if !ok {
418 return zp.setParseError("bad origin name", l)
419 }
420
421 neworigin = name
422 }
423 case zNewline, zEOF:
424 // Ok
425 default:
426 return zp.setParseError("garbage after $INCLUDE", l)
427 }
428
429 if !zp.includeAllowed {
430 return zp.setParseError("$INCLUDE directive not allowed", l)
431 }
432 if zp.includeDepth >= maxIncludeDepth {
433 return zp.setParseError("too deeply nested $INCLUDE", l)
434 }
435
436 // Start with the new file
437 includePath := l.token
438 var r1 io.Reader
439 var e1 error
440 if zp.fsys != nil {
441 // fs.FS always uses / as separator, even on Windows, so use
442 // path instead of filepath here:
443 if !path.IsAbs(includePath) {
444 includePath = path.Join(path.Dir(zp.file), includePath)
445 }
446
447 // os.DirFS, and probably others, expect all paths to be
448 // relative, so clean the path and remove leading / if
449 // present:
450 includePath = strings.TrimLeft(path.Clean(includePath), "/")
451
452 r1, e1 = zp.fsys.Open(includePath)
453 } else {
454 if !filepath.IsAbs(includePath) {
455 includePath = filepath.Join(filepath.Dir(zp.file), includePath)
456 }
457 r1, e1 = os.Open(includePath)
458 }
459 if e1 != nil {
460 var as string
461 if includePath != l.token {
462 as = fmt.Sprintf(" as `%s'", includePath)
463 }
464 zp.parseErr = &ParseError{
465 file: zp.file,
466 wrappedErr: fmt.Errorf("failed to open `%s'%s: %w", l.token, as, e1),
467 lex: l,
468 }
469 return nil, false
470 }
471
472 zp.sub = NewZoneParser(r1, neworigin, includePath)
473 zp.sub.defttl, zp.sub.includeDepth, zp.sub.r = zp.defttl, zp.includeDepth+1, r1
474 zp.sub.SetIncludeAllowed(true)
475 zp.sub.SetIncludeFS(zp.fsys)
476 return zp.subNext()
477 case zExpectDirTTLBl:
478 if l.value != zBlank {
479 return zp.setParseError("no blank after $TTL-directive", l)
480 }
481
482 st = zExpectDirTTL
483 case zExpectDirTTL:
484 if l.value != zString {
485 return zp.setParseError("expecting $TTL value, not this...", l)
486 }
487
488 if err := slurpRemainder(zp.c); err != nil {
489 return zp.setParseError(err.err, err.lex)
490 }
491
492 ttl, ok := stringToTTL(l.token)
493 if !ok {
494 return zp.setParseError("expecting $TTL value, not this...", l)
495 }
496
497 zp.defttl = &ttlState{ttl, true}
498
499 st = zExpectOwnerDir
500 case zExpectDirOriginBl:
501 if l.value != zBlank {
502 return zp.setParseError("no blank after $ORIGIN-directive", l)
503 }
504
505 st = zExpectDirOrigin
506 case zExpectDirOrigin:
507 if l.value != zString {
508 return zp.setParseError("expecting $ORIGIN value, not this...", l)
509 }
510
511 if err := slurpRemainder(zp.c); err != nil {
512 return zp.setParseError(err.err, err.lex)
513 }
514
515 name, ok := toAbsoluteName(l.token, zp.origin)
516 if !ok {
517 return zp.setParseError("bad origin name", l)
518 }
519
520 zp.origin = name
521
522 st = zExpectOwnerDir
523 case zExpectDirGenerateBl:
524 if l.value != zBlank {
525 return zp.setParseError("no blank after $GENERATE-directive", l)
526 }
527
528 st = zExpectDirGenerate
529 case zExpectDirGenerate:
530 if zp.generateDisallowed {
531 return zp.setParseError("nested $GENERATE directive not allowed", l)
532 }
533 if l.value != zString {
534 return zp.setParseError("expecting $GENERATE value, not this...", l)
535 }
536
537 return zp.generate(l)
538 case zExpectOwnerBl:
539 if l.value != zBlank {
540 return zp.setParseError("no blank after owner", l)
541 }
542
543 st = zExpectAny
544 case zExpectAny:
545 switch l.value {
546 case zRrtpe:
547 if zp.defttl == nil {
548 return zp.setParseError("missing TTL with no previous value", l)
549 }
550
551 h.Rrtype = l.torc
552
553 st = zExpectRdata
554 case zClass:
555 h.Class = l.torc
556
557 st = zExpectAnyNoClassBl
558 case zString:
559 ttl, ok := stringToTTL(l.token)
560 if !ok {
561 return zp.setParseError("not a TTL", l)
562 }
563
564 h.Ttl = ttl
565
566 if zp.defttl == nil || !zp.defttl.isByDirective {
567 zp.defttl = &ttlState{ttl, false}
568 }
569
570 st = zExpectAnyNoTTLBl
571 default:
572 return zp.setParseError("expecting RR type, TTL or class, not this...", l)
573 }
574 case zExpectAnyNoClassBl:
575 if l.value != zBlank {
576 return zp.setParseError("no blank before class", l)
577 }
578
579 st = zExpectAnyNoClass
580 case zExpectAnyNoTTLBl:
581 if l.value != zBlank {
582 return zp.setParseError("no blank before TTL", l)
583 }
584
585 st = zExpectAnyNoTTL
586 case zExpectAnyNoTTL:
587 switch l.value {
588 case zClass:
589 h.Class = l.torc
590
591 st = zExpectRrtypeBl
592 case zRrtpe:
593 h.Rrtype = l.torc
594
595 st = zExpectRdata
596 default:
597 return zp.setParseError("expecting RR type or class, not this...", l)
598 }
599 case zExpectAnyNoClass:
600 switch l.value {
601 case zString:
602 ttl, ok := stringToTTL(l.token)
603 if !ok {
604 return zp.setParseError("not a TTL", l)
605 }
606
607 h.Ttl = ttl
608
609 if zp.defttl == nil || !zp.defttl.isByDirective {
610 zp.defttl = &ttlState{ttl, false}
611 }
612
613 st = zExpectRrtypeBl
614 case zRrtpe:
615 h.Rrtype = l.torc
616
617 st = zExpectRdata
618 default:
619 return zp.setParseError("expecting RR type or TTL, not this...", l)
620 }
621 case zExpectRrtypeBl:
622 if l.value != zBlank {
623 return zp.setParseError("no blank before RR type", l)
624 }
625
626 st = zExpectRrtype
627 case zExpectRrtype:
628 if l.value != zRrtpe {
629 return zp.setParseError("unknown RR type", l)
630 }
631
632 h.Rrtype = l.torc
633
634 st = zExpectRdata
635 case zExpectRdata:
636 var (
637 rr RR
638 parseAsRFC3597 bool
639 )
640 if newFn, ok := TypeToRR[h.Rrtype]; ok {
641 rr = newFn()
642 *rr.Header() = *h
643
644 // We may be parsing a known RR type using the RFC3597 format.
645 // If so, we handle that here in a generic way.
646 //
647 // This is also true for PrivateRR types which will have the
648 // RFC3597 parsing done for them and the Unpack method called
649 // to populate the RR instead of simply deferring to Parse.
650 if zp.c.Peek().token == "\\#" {
651 parseAsRFC3597 = true
652 }
653 } else {
654 rr = &RFC3597{Hdr: *h}
655 }
656
657 _, isPrivate := rr.(*PrivateRR)
658 if !isPrivate && zp.c.Peek().token == "" {
659 // This is a dynamic update rr.
660
661 if err := slurpRemainder(zp.c); err != nil {
662 return zp.setParseError(err.err, err.lex)
663 }
664
665 return rr, true
666 } else if l.value == zNewline {
667 return zp.setParseError("unexpected newline", l)
668 }
669
670 parseAsRR := rr
671 if parseAsRFC3597 {
672 parseAsRR = &RFC3597{Hdr: *h}
673 }
674
675 if err := parseAsRR.parse(zp.c, zp.origin); err != nil {
676 // err is a concrete *ParseError without the file field set.
677 // The setParseError call below will construct a new
678 // *ParseError with file set to zp.file.
679
680 // err.lex may be nil in which case we substitute our current
681 // lex token.
682 if err.lex == (lex{}) {
683 return zp.setParseError(err.err, l)
684 }
685
686 return zp.setParseError(err.err, err.lex)
687 }
688
689 if parseAsRFC3597 {
690 err := parseAsRR.(*RFC3597).fromRFC3597(rr)
691 if err != nil {
692 return zp.setParseError(err.Error(), l)
693 }
694 }
695
696 return rr, true
697 }
698 }
699
700 // If we get here, we and the h.Rrtype is still zero, we haven't parsed anything, this
701 // is not an error, because an empty zone file is still a zone file.
702 return nil, false
703 }
704
705 type zlexer struct {
706 br io.ByteReader
707
708 readErr error
709
710 line int
711 column int
712
713 comBuf string
714 comment string
715
716 l lex
717 cachedL *lex
718
719 brace int
720 quote bool
721 space bool
722 commt bool
723 rrtype bool
724 owner bool
725
726 nextL bool
727
728 eol bool // end-of-line
729 }
730
731 func newZLexer(r io.Reader) *zlexer {
732 br, ok := r.(io.ByteReader)
733 if !ok {
734 br = bufio.NewReaderSize(r, 1024)
735 }
736
737 return &zlexer{
738 br: br,
739
740 line: 1,
741
742 owner: true,
743 }
744 }
745
746 func (zl *zlexer) Err() error {
747 if zl.readErr == io.EOF {
748 return nil
749 }
750
751 return zl.readErr
752 }
753
754 // readByte returns the next byte from the input
755 func (zl *zlexer) readByte() (byte, bool) {
756 if zl.readErr != nil {
757 return 0, false
758 }
759
760 c, err := zl.br.ReadByte()
761 if err != nil {
762 zl.readErr = err
763 return 0, false
764 }
765
766 // delay the newline handling until the next token is delivered,
767 // fixes off-by-one errors when reporting a parse error.
768 if zl.eol {
769 zl.line++
770 zl.column = 0
771 zl.eol = false
772 }
773
774 if c == '\n' {
775 zl.eol = true
776 } else {
777 zl.column++
778 }
779
780 return c, true
781 }
782
783 func (zl *zlexer) Peek() lex {
784 if zl.nextL {
785 return zl.l
786 }
787
788 l, ok := zl.Next()
789 if !ok {
790 return l
791 }
792
793 if zl.nextL {
794 // Cache l. Next returns zl.cachedL then zl.l.
795 zl.cachedL = &l
796 } else {
797 // In this case l == zl.l, so we just tell Next to return zl.l.
798 zl.nextL = true
799 }
800
801 return l
802 }
803
804 func (zl *zlexer) Next() (lex, bool) {
805 l := &zl.l
806 switch {
807 case zl.cachedL != nil:
808 l, zl.cachedL = zl.cachedL, nil
809 return *l, true
810 case zl.nextL:
811 zl.nextL = false
812 return *l, true
813 case l.err:
814 // Parsing errors should be sticky.
815 return lex{value: zEOF}, false
816 }
817
818 var (
819 str = make([]byte, maxTok) // Hold string text
820 com = make([]byte, maxTok) // Hold comment text
821
822 stri int // Offset in str (0 means empty)
823 comi int // Offset in com (0 means empty)
824
825 escape bool
826 )
827
828 if zl.comBuf != "" {
829 comi = copy(com[:], zl.comBuf)
830 zl.comBuf = ""
831 }
832
833 zl.comment = ""
834
835 for x, ok := zl.readByte(); ok; x, ok = zl.readByte() {
836 l.line, l.column = zl.line, zl.column
837
838 if stri >= len(str) {
839 // if buffer length is insufficient, increase it.
840 str = append(str[:], make([]byte, maxTok)...)
841 }
842 if comi >= len(com) {
843 // if buffer length is insufficient, increase it.
844 com = append(com[:], make([]byte, maxTok)...)
845 }
846
847 switch x {
848 case ' ', '\t':
849 if escape || zl.quote {
850 // Inside quotes or escaped this is legal.
851 str[stri] = x
852 stri++
853
854 escape = false
855 break
856 }
857
858 if zl.commt {
859 com[comi] = x
860 comi++
861 break
862 }
863
864 var retL lex
865 if stri == 0 {
866 // Space directly in the beginning, handled in the grammar
867 } else if zl.owner {
868 // If we have a string and it's the first, make it an owner
869 l.value = zOwner
870 l.token = string(str[:stri])
871
872 // escape $... start with a \ not a $, so this will work
873 switch strings.ToUpper(l.token) {
874 case "$TTL":
875 l.value = zDirTTL
876 case "$ORIGIN":
877 l.value = zDirOrigin
878 case "$INCLUDE":
879 l.value = zDirInclude
880 case "$GENERATE":
881 l.value = zDirGenerate
882 }
883
884 retL = *l
885 } else {
886 l.value = zString
887 l.token = string(str[:stri])
888
889 if !zl.rrtype {
890 tokenUpper := strings.ToUpper(l.token)
891 if t, ok := StringToType[tokenUpper]; ok {
892 l.value = zRrtpe
893 l.torc = t
894
895 zl.rrtype = true
896 } else if strings.HasPrefix(tokenUpper, "TYPE") {
897 t, ok := typeToInt(l.token)
898 if !ok {
899 l.token = "unknown RR type"
900 l.err = true
901 return *l, true
902 }
903
904 l.value = zRrtpe
905 l.torc = t
906
907 zl.rrtype = true
908 }
909
910 if t, ok := StringToClass[tokenUpper]; ok {
911 l.value = zClass
912 l.torc = t
913 } else if strings.HasPrefix(tokenUpper, "CLASS") {
914 t, ok := classToInt(l.token)
915 if !ok {
916 l.token = "unknown class"
917 l.err = true
918 return *l, true
919 }
920
921 l.value = zClass
922 l.torc = t
923 }
924 }
925
926 retL = *l
927 }
928
929 zl.owner = false
930
931 if !zl.space {
932 zl.space = true
933
934 l.value = zBlank
935 l.token = " "
936
937 if retL == (lex{}) {
938 return *l, true
939 }
940
941 zl.nextL = true
942 }
943
944 if retL != (lex{}) {
945 return retL, true
946 }
947 case ';':
948 if escape || zl.quote {
949 // Inside quotes or escaped this is legal.
950 str[stri] = x
951 stri++
952
953 escape = false
954 break
955 }
956
957 zl.commt = true
958 zl.comBuf = ""
959
960 if comi > 1 {
961 // A newline was previously seen inside a comment that
962 // was inside braces and we delayed adding it until now.
963 com[comi] = ' ' // convert newline to space
964 comi++
965 if comi >= len(com) {
966 l.token = "comment length insufficient for parsing"
967 l.err = true
968 return *l, true
969 }
970 }
971
972 com[comi] = ';'
973 comi++
974
975 if stri > 0 {
976 zl.comBuf = string(com[:comi])
977
978 l.value = zString
979 l.token = string(str[:stri])
980 return *l, true
981 }
982 case '\r':
983 escape = false
984
985 if zl.quote {
986 str[stri] = x
987 stri++
988 }
989
990 // discard if outside of quotes
991 case '\n':
992 escape = false
993
994 // Escaped newline
995 if zl.quote {
996 str[stri] = x
997 stri++
998 break
999 }
1000
1001 if zl.commt {
1002 // Reset a comment
1003 zl.commt = false
1004 zl.rrtype = false
1005
1006 // If not in a brace this ends the comment AND the RR
1007 if zl.brace == 0 {
1008 zl.owner = true
1009
1010 l.value = zNewline
1011 l.token = "\n"
1012 zl.comment = string(com[:comi])
1013 return *l, true
1014 }
1015
1016 zl.comBuf = string(com[:comi])
1017 break
1018 }
1019
1020 if zl.brace == 0 {
1021 // If there is previous text, we should output it here
1022 var retL lex
1023 if stri != 0 {
1024 l.value = zString
1025 l.token = string(str[:stri])
1026
1027 if !zl.rrtype {
1028 tokenUpper := strings.ToUpper(l.token)
1029 if t, ok := StringToType[tokenUpper]; ok {
1030 zl.rrtype = true
1031
1032 l.value = zRrtpe
1033 l.torc = t
1034 }
1035 }
1036
1037 retL = *l
1038 }
1039
1040 l.value = zNewline
1041 l.token = "\n"
1042
1043 zl.comment = zl.comBuf
1044 zl.comBuf = ""
1045 zl.rrtype = false
1046 zl.owner = true
1047
1048 if retL != (lex{}) {
1049 zl.nextL = true
1050 return retL, true
1051 }
1052
1053 return *l, true
1054 }
1055 case '\\':
1056 // comments do not get escaped chars, everything is copied
1057 if zl.commt {
1058 com[comi] = x
1059 comi++
1060 break
1061 }
1062
1063 // something already escaped must be in string
1064 if escape {
1065 str[stri] = x
1066 stri++
1067
1068 escape = false
1069 break
1070 }
1071
1072 // something escaped outside of string gets added to string
1073 str[stri] = x
1074 stri++
1075
1076 escape = true
1077 case '"':
1078 if zl.commt {
1079 com[comi] = x
1080 comi++
1081 break
1082 }
1083
1084 if escape {
1085 str[stri] = x
1086 stri++
1087
1088 escape = false
1089 break
1090 }
1091
1092 zl.space = false
1093
1094 // send previous gathered text and the quote
1095 var retL lex
1096 if stri != 0 {
1097 l.value = zString
1098 l.token = string(str[:stri])
1099
1100 retL = *l
1101 }
1102
1103 // send quote itself as separate token
1104 l.value = zQuote
1105 l.token = "\""
1106
1107 zl.quote = !zl.quote
1108
1109 if retL != (lex{}) {
1110 zl.nextL = true
1111 return retL, true
1112 }
1113
1114 return *l, true
1115 case '(', ')':
1116 if zl.commt {
1117 com[comi] = x
1118 comi++
1119 break
1120 }
1121
1122 if escape || zl.quote {
1123 // Inside quotes or escaped this is legal.
1124 str[stri] = x
1125 stri++
1126
1127 escape = false
1128 break
1129 }
1130
1131 switch x {
1132 case ')':
1133 zl.brace--
1134
1135 if zl.brace < 0 {
1136 l.token = "extra closing brace"
1137 l.err = true
1138 return *l, true
1139 }
1140 case '(':
1141 zl.brace++
1142 }
1143 default:
1144 escape = false
1145
1146 if zl.commt {
1147 com[comi] = x
1148 comi++
1149 break
1150 }
1151
1152 str[stri] = x
1153 stri++
1154
1155 zl.space = false
1156 }
1157 }
1158
1159 if zl.readErr != nil && zl.readErr != io.EOF {
1160 // Don't return any tokens after a read error occurs.
1161 return lex{value: zEOF}, false
1162 }
1163
1164 var retL lex
1165 if stri > 0 {
1166 // Send remainder of str
1167 l.value = zString
1168 l.token = string(str[:stri])
1169 retL = *l
1170
1171 if comi <= 0 {
1172 return retL, true
1173 }
1174 }
1175
1176 if comi > 0 {
1177 // Send remainder of com
1178 l.value = zNewline
1179 l.token = "\n"
1180 zl.comment = string(com[:comi])
1181
1182 if retL != (lex{}) {
1183 zl.nextL = true
1184 return retL, true
1185 }
1186
1187 return *l, true
1188 }
1189
1190 if zl.brace != 0 {
1191 l.token = "unbalanced brace"
1192 l.err = true
1193 return *l, true
1194 }
1195
1196 return lex{value: zEOF}, false
1197 }
1198
1199 func (zl *zlexer) Comment() string {
1200 if zl.l.err {
1201 return ""
1202 }
1203
1204 return zl.comment
1205 }
1206
1207 // Extract the class number from CLASSxx
1208 func classToInt(token string) (uint16, bool) {
1209 offset := 5
1210 if len(token) < offset+1 {
1211 return 0, false
1212 }
1213 class, err := strconv.ParseUint(token[offset:], 10, 16)
1214 if err != nil {
1215 return 0, false
1216 }
1217 return uint16(class), true
1218 }
1219
1220 // Extract the rr number from TYPExxx
1221 func typeToInt(token string) (uint16, bool) {
1222 offset := 4
1223 if len(token) < offset+1 {
1224 return 0, false
1225 }
1226 typ, err := strconv.ParseUint(token[offset:], 10, 16)
1227 if err != nil {
1228 return 0, false
1229 }
1230 return uint16(typ), true
1231 }
1232
1233 // stringToTTL parses things like 2w, 2m, etc, and returns the time in seconds.
1234 func stringToTTL(token string) (uint32, bool) {
1235 var s, i uint
1236 for _, c := range token {
1237 switch c {
1238 case 's', 'S':
1239 s += i
1240 i = 0
1241 case 'm', 'M':
1242 s += i * 60
1243 i = 0
1244 case 'h', 'H':
1245 s += i * 60 * 60
1246 i = 0
1247 case 'd', 'D':
1248 s += i * 60 * 60 * 24
1249 i = 0
1250 case 'w', 'W':
1251 s += i * 60 * 60 * 24 * 7
1252 i = 0
1253 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
1254 i *= 10
1255 i += uint(c) - '0'
1256 default:
1257 return 0, false
1258 }
1259 }
1260 if s+i > math.MaxUint32 {
1261 return 0, false
1262 }
1263 return uint32(s + i), true
1264 }
1265
1266 // Parse LOC records' <digits>[.<digits>][mM] into a
1267 // mantissa exponent format. Token should contain the entire
1268 // string (i.e. no spaces allowed)
1269 func stringToCm(token string) (e, m uint8, ok bool) {
1270 if token[len(token)-1] == 'M' || token[len(token)-1] == 'm' {
1271 token = token[0 : len(token)-1]
1272 }
1273
1274 var (
1275 meters, cmeters, val int
1276 err error
1277 )
1278 mStr, cmStr, hasCM := strings.Cut(token, ".")
1279 if hasCM {
1280 // There's no point in having more than 2 digits in this part, and would rather make the implementation complicated ('123' should be treated as '12').
1281 // So we simply reject it.
1282 // We also make sure the first character is a digit to reject '+-' signs.
1283 cmeters, err = strconv.Atoi(cmStr)
1284 if err != nil || len(cmStr) > 2 || cmStr[0] < '0' || cmStr[0] > '9' {
1285 return
1286 }
1287 if len(cmStr) == 1 {
1288 // 'nn.1' must be treated as 'nn-meters and 10cm, not 1cm.
1289 cmeters *= 10
1290 }
1291 }
1292 // This slightly ugly condition will allow omitting the 'meter' part, like .01 (meaning 0.01m = 1cm).
1293 if !hasCM || mStr != "" {
1294 meters, err = strconv.Atoi(mStr)
1295 // RFC1876 states the max value is 90000000.00. The latter two conditions enforce it.
1296 if err != nil || mStr[0] < '0' || mStr[0] > '9' || meters > 90000000 || (meters == 90000000 && cmeters != 0) {
1297 return
1298 }
1299 }
1300
1301 if meters > 0 {
1302 e = 2
1303 val = meters
1304 } else {
1305 e = 0
1306 val = cmeters
1307 }
1308 for val >= 10 {
1309 e++
1310 val /= 10
1311 }
1312 return e, uint8(val), true
1313 }
1314
1315 func toAbsoluteName(name, origin string) (absolute string, ok bool) {
1316 // check for an explicit origin reference
1317 if name == "@" {
1318 // require a nonempty origin
1319 if origin == "" {
1320 return "", false
1321 }
1322 return origin, true
1323 }
1324
1325 // this can happen when we have a comment after a RR that has a domain, '... MX 20 ; this is wrong'.
1326 // technically a newline can be in a domain name, but this is clearly an error and the newline only shows
1327 // because of the scanning and the comment.
1328 if name == "\n" {
1329 return "", false
1330 }
1331
1332 // require a valid domain name
1333 _, ok = IsDomainName(name)
1334 if !ok || name == "" {
1335 return "", false
1336 }
1337
1338 // check if name is already absolute
1339 if IsFqdn(name) {
1340 return name, true
1341 }
1342
1343 // require a nonempty origin
1344 if origin == "" {
1345 return "", false
1346 }
1347 return appendOrigin(name, origin), true
1348 }
1349
1350 func appendOrigin(name, origin string) string {
1351 if origin == "." {
1352 return name + origin
1353 }
1354 return name + "." + origin
1355 }
1356
1357 // LOC record helper function
1358 func locCheckNorth(token string, latitude uint32) (uint32, bool) {
1359 if latitude > 90*1000*60*60 {
1360 return latitude, false
1361 }
1362 switch token {
1363 case "n", "N":
1364 return LOC_EQUATOR + latitude, true
1365 case "s", "S":
1366 return LOC_EQUATOR - latitude, true
1367 }
1368 return latitude, false
1369 }
1370
1371 // LOC record helper function
1372 func locCheckEast(token string, longitude uint32) (uint32, bool) {
1373 if longitude > 180*1000*60*60 {
1374 return longitude, false
1375 }
1376 switch token {
1377 case "e", "E":
1378 return LOC_EQUATOR + longitude, true
1379 case "w", "W":
1380 return LOC_EQUATOR - longitude, true
1381 }
1382 return longitude, false
1383 }
1384
1385 // "Eat" the rest of the "line"
1386 func slurpRemainder(c *zlexer) *ParseError {
1387 l, _ := c.Next()
1388 switch l.value {
1389 case zBlank:
1390 l, _ = c.Next()
1391 if l.value != zNewline && l.value != zEOF {
1392 return &ParseError{err: "garbage after rdata", lex: l}
1393 }
1394 case zNewline:
1395 case zEOF:
1396 default:
1397 return &ParseError{err: "garbage after rdata", lex: l}
1398 }
1399 return nil
1400 }
1401
1402 // Parse a 64 bit-like ipv6 address: "0014:4fff:ff20:ee64"
1403 // Used for NID and L64 record.
1404 func stringToNodeID(l lex) (uint64, *ParseError) {
1405 if len(l.token) < 19 {
1406 return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l}
1407 }
1408 // There must be three colons at fixes positions, if not its a parse error
1409 if l.token[4] != ':' && l.token[9] != ':' && l.token[14] != ':' {
1410 return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l}
1411 }
1412 s := l.token[0:4] + l.token[5:9] + l.token[10:14] + l.token[15:19]
1413 u, err := strconv.ParseUint(s, 16, 64)
1414 if err != nil {
1415 return 0, &ParseError{file: l.token, err: "bad NID/L64 NodeID/Locator64", lex: l}
1416 }
1417 return u, nil
1418 }