Debian Codegraph @

scan.go

raw
1 package dns
2
3 import (
4 "fmt"
5 "io"
6 "io/fs"
7 "iter"
8 "math"
9 "os"
10 "path"
11 "path/filepath"
12 "strconv"
13 "strings"
14
15 "codeberg.org/miekg/dns/internal/dnslex"
16 "codeberg.org/miekg/dns/internal/dnsstring"
17 "codeberg.org/miekg/dns/rdata"
18 )
19
20 // The maximum depth of $INCLUDE directives supported by the ZoneParser API.
21 const maxIncludeDepth = 7
22
23 // Tokenize a RFC 1035 zone file. The tokenizer will normalize it:
24 // * Add ownernames if they are left blank;
25 // * Suppress sequences of spaces;
26 // * Make each RR fit on one line (_NEWLINE is send as last)
27 // * Handle comments: ;
28 // * Handle braces - anywhere.
29 const (
30 // Privatekey file
31 zValue uint8 = iota
32 zKey
33
34 zExpectOwnerDir uint8 = iota // Ownername
35 zExpectAny // Expect rrtype, ttl or class
36 zExpectAnyNoClass // Expect rrtype or ttl
37 zExpectAnyNoTTL // Expect rrtype or class
38 zExpectRrtype // Expect whitespace and rrtype
39 zExpectRdata // The first element of the rdata
40 zExpectDirTTL // Directive $TTL
41 zExpectDirOrigin // Directive $ORIGIN
42 zExpectDirInclude // Directive $INCLUDE
43 zExpectDirGenerate // Directive $GENERATE
44 )
45
46 // ParseError is a parsing error. It contains the parse error and the location in the io.Reader
47 // where the error occurred.
48 type ParseError struct {
49 file string
50 err string
51 wrappedErr error
52 lex dnslex.Lex
53 }
54
55 func (e *ParseError) Error() (s string) {
56 if e.file != "" {
57 s = e.file + ": "
58 }
59 if e.err == "" && e.wrappedErr != nil {
60 e.err = e.wrappedErr.Error()
61 }
62 s += "dns: " + e.err + ": " + strconv.QuoteToASCII(e.lex.Token) + " at line: " +
63 strconv.Itoa(int(e.lex.Line)) + ":" + strconv.Itoa(int(e.lex.Column))
64 return
65 }
66
67 func (e *ParseError) Unwrap() error { return e.wrappedErr }
68
69 const (
70 asRR uint8 = iota // parse the string as an RR.
71 asCode // parse the string as an EDNS RR.
72 asStateful // TODO, but parse the string as an DSO RR.
73 )
74
75 // ttlState describes the state necessary to fill in an omitted RR TTL.
76 type ttlState struct {
77 ttl uint32 // ttl is the current default TTL
78 isByDirective bool // isByDirective indicates whether ttl was set by a $TTL directive
79 }
80
81 // New reads the RR contained in the string s. Only the first RR is returned.
82 // If s contains no records, New will return nil with no error.
83 // The origin for resolving relative domain names defaults to the DNS root (.).
84 //
85 // The class defaults to IN and TTL defaults to 3600. The full zone file syntax
86 // like $TTL, $ORIGIN, etc. is supported.
87 //
88 // Note that building an RR directly from it Go structure is far more efficient, i.e.
89 //
90 // mx := &dns.MX{Hdr: dns.Header{Name: "miek.nl.", Class: dns.ClassINET, TTL: 3600}, MX: rdata.MX{Preference: 10, Mx: "mx.miek.nl."}}
91 //
92 // instead of:
93 //
94 // mx := New("miek.nl. 0 IN MX 10 mx.miek.nl.")
95 //
96 // In this library EDNS0 option codes have a presentation format, which you see when you print them. This
97 // presentation format is also parsed back to EDNS0. In other words you can get an ENDS0 option code just from
98 // a string.
99 //
100 // Or with [codeberg.org/miekg/dns/dnstest.New], if you are sure no error will occur.
101 //
102 // mx := dnstest.New("miek.nl. IN MX 10 mx.miek.nl.")
103 func New(s string) (RR, error) {
104 if s == "" {
105 return nil, &Error{err: "bad RR"}
106 }
107 return read(dnsstring.NewReader(s), "")
108 }
109
110 // Read behaves like [New] but reads from an io.Reader. Note the reader must include an ending newline,
111 // otherwise the parsing will fail.
112 func Read(r io.Reader) (RR, error) { return read(r, "") }
113
114 func read(r io.Reader, file string) (RR, error) {
115 zp := NewZoneParser(r, ".", file)
116 zp.SetDefaultTTL(3600)
117 rr, _ := zp.Next()
118 return rr, zp.Err()
119 }
120
121 // NewData parses s, but only for the [RDATA], i.e. when the full [RR] is "miek.nl. IN 3600 MX 10 mx.miek.nl.",
122 // NewData must get "10 mx.miek.nl." and optionally an origin. Leading spaces are not allowed.
123 // Examples can be found in [RDATA].
124 func NewData(rrtype uint16, s string, origin ...string) (RDATA, error) {
125 return readData(strings.NewReader(s), rrtype, origin...)
126 }
127
128 // ReadData behaves like [NewData] but reads from an io.Reader.
129 func ReadData(r io.Reader, rrtype uint16, origin ...string) (RDATA, error) {
130 return readData(r, rrtype, origin...)
131 }
132
133 func readData(r io.Reader, rrtype uint16, origin ...string) (RDATA, error) {
134 o := "."
135 if len(origin) > 0 {
136 o = origin[0]
137 }
138 return parseData(r, rrtype, o)
139 }
140
141 // ZoneParser is a parser for an RFC 1035 style zone file.
142 //
143 // Each parsed RR in the zone is returned sequentially from [ZoneParser.Next].
144 // Also see [ZoneParser.RRs] which is an iterator.
145 //
146 // The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are all supported.
147 // Note that $GENERATE's range support up to a maximum of 65535 steps.
148 //
149 // Basic usage pattern when reading from a string (z) containing the zone data:
150 //
151 // zp := NewZoneParser(strings.NewReader(z), "", "")
152 //
153 // for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
154 // // Do something with rr
155 // }
156 //
157 // if err := zp.Err(); err != nil {
158 // // log.Println(err)
159 // }
160 //
161 // Callers should not assume all returned data in a [RR] is
162 // syntactically correct, e.g. illegal base64 in [RRSIG]s will be returned as-is.
163 type ZoneParser struct {
164 h Header // rr header as we parse
165 t uint16 // type as we parse, not stored in the header
166
167 includeDepth uint8
168 generateDisallowed bool
169
170 r io.Reader
171 c *dnslex.Lexer
172
173 // IncludeAllowFunc tells if and how includes are allowed.
174 IncludeAllowFunc
175
176 // IncludeFS provides an [fs.FS] to use when looking for the target of $INCLUDE directives.
177 // If nil, [os.Open] will be used.
178 //
179 // When it is an on-disk FS, the ability of $INCLUDE to reach files from
180 // outside its root directory depends upon the FS implementation. For
181 // instance, [os.DirFS] will refuse to open paths like "../../etc/passwd",
182 // however it will still follow links which may point anywhere on the system.
183 //
184 // FS paths are slash-separated on all systems, even Windows. $INCLUDE paths
185 // containing other characters such as backslash and colon may be accepted as
186 // valid, but those characters will never be interpreted by an FS
187 // implementation as path element separators. See [fs.ValidPath] for more
188 // details.
189 IncludeFS fs.FS
190
191 origin string
192 file string
193 path string // full path of file
194
195 parseErr *ParseError
196 defttl *ttlState
197
198 // sub is used to parse $INCLUDE files and $GENERATE directives.
199 // Next, by calling subNext, forwards the resulting RRs from this
200 // sub parser to the calling code.
201 sub *ZoneParser
202 }
203
204 // NewZoneParser returns an RFC 1035 style zone file parser that reads from r.
205 //
206 // The string file is used in error reporting and to resolve relative $INCLUDE directives. The string origin
207 // is used as the initial origin, as if the file would start with an $ORIGIN directive.
208 // IncludeAllowFunc is set to [DefaultIncludeAllowFunc].
209 func NewZoneParser(r io.Reader, origin, file string) *ZoneParser {
210 var pe *ParseError
211 if origin != "" {
212 origin = dnsutilFqdn(origin)
213 if ok := dnsutilIsName(origin); !ok {
214 pe = &ParseError{file: file, err: "bad initial origin name"}
215 }
216 }
217
218 return &ZoneParser{
219 c: dnslex.New(r, StringToType, StringToCode, StringToClass),
220 IncludeAllowFunc: DefaultIncludeAllowFunc,
221 parseErr: pe,
222 origin: origin,
223 file: file,
224 path: func() string { p, _ := filepath.Abs(file); return p }(),
225 }
226 }
227
228 // SetDefaultTTL sets the parsers default TTL to ttl.
229 func (zp *ZoneParser) SetDefaultTTL(ttl uint32) {
230 zp.defttl = &ttlState{ttl, false}
231 }
232
233 // Err returns the first non-EOF error that was encountered by the ZoneParser.
234 func (zp *ZoneParser) Err() error {
235 if zp.parseErr != nil {
236 return zp.parseErr
237 }
238
239 if zp.sub != nil {
240 if err := zp.sub.Err(); err != nil {
241 return err
242 }
243 }
244
245 return zp.c.Err()
246 }
247
248 func (zp *ZoneParser) setParseError(err string, l dnslex.Lex) (RR, bool) {
249 zp.parseErr = &ParseError{file: zp.file, err: err, lex: l}
250 return nil, false
251 }
252
253 func (zp *ZoneParser) subNext() (RR, bool) {
254 if rr, ok := zp.sub.Next(); ok {
255 return rr, true
256 }
257
258 if zp.sub.r != nil {
259 if c, ok := zp.sub.r.(io.Closer); ok {
260 c.Close()
261 }
262 zp.sub.r = nil
263 }
264
265 if zp.sub.Err() != nil {
266 // We have errors to surface.
267 return nil, false
268 }
269
270 zp.sub = nil
271 return zp.Next()
272 }
273
274 // Next advances the parser to the next RR in the zone file and returns the ([RR], true).
275 // It will return (nil, false) when the parsing stops, either by reaching the end of the input or an
276 // error. After Next returns (nil, false), the Err method will return any error that occurred during parsing.
277 func (zp *ZoneParser) Next() (RR, bool) {
278 if zp.parseErr != nil {
279 return nil, false
280 }
281 if zp.sub != nil {
282 return zp.subNext()
283 }
284
285 setTTL := func(l dnslex.Lex) (uint32, bool) {
286 ttl, ok := stringToTTL(l.Token)
287 if !ok {
288 return 0, false
289 }
290 if zp.defttl == nil || !zp.defttl.isByDirective {
291 zp.defttl = &ttlState{ttl, false}
292 }
293 return ttl, true
294 }
295
296 // 6 possible beginnings of a line (_ is a space):
297 //
298 // 0. dnslex.Rrtype -> all omitted until the rrtype
299 // 1. dnslex.Owner _ dnslex.Rrtype -> class/ttl omitted
300 // 2. dnslex.Owner _ dnslex.String _ dnslex.Rrtype -> class omitted
301 // 3. dnslex.Owner _ dnslex.Class _ dnslex.Rrtype -> ttl omitted
302 // 4. dnslex.Owner _ dnslex.String _ dnslex.Class _ dnslex.Rrtype -> ttl/class
303 // 5. dnslex.Owner _ dnslex.Class _ dnslex.String _ dnslex.Rrtype -> class/ttl (reversed)
304 //
305 // After detecting these, we know the RR type so we can jump to functions handling the rdata for each.
306
307 st := zExpectOwnerDir // initial state
308
309 for l, ok := zp.c.Next(); ok; l, ok = zp.c.Next() {
310 // zlexer spotted an error already
311 if l.Value == dnslex.Error {
312 return zp.setParseError(l.Token, l)
313 }
314
315 switch st {
316 case zExpectOwnerDir:
317 // We can also expect a directive, like $TTL or $ORIGIN.
318 if zp.defttl != nil {
319 zp.h.TTL = zp.defttl.ttl
320 }
321
322 zp.h.Class = ClassINET
323
324 switch l.Value {
325 case dnslex.Newline:
326
327 st = zExpectOwnerDir
328 case dnslex.Owner:
329 name := dnsutilAbsolute(l.Token, zp.origin)
330 if name == "" {
331 return zp.setParseError("bad owner name", l)
332 }
333
334 zp.h.Name = name
335
336 if !zp.c.Blank() {
337 return zp.setParseError("no blank after owner name", l)
338 }
339
340 st = zExpectAny
341 case dnslex.DirTTL:
342 if !zp.c.Blank() {
343 return zp.setParseError("no blank after $TTL-directive", l)
344 }
345
346 st = zExpectDirTTL
347 case dnslex.DirOrigin:
348 if !zp.c.Blank() {
349 return zp.setParseError("no blank after $ORIGIN-directive", l)
350 }
351
352 st = zExpectDirOrigin
353 case dnslex.DirInclude:
354 if !zp.c.Blank() {
355 return zp.setParseError("no blank after $INCLUDE-directive", l)
356 }
357
358 st = zExpectDirInclude
359 case dnslex.DirGenerate:
360 if !zp.c.Blank() {
361 return zp.setParseError("no blank after $GENERATE-directive", l)
362 }
363
364 st = zExpectDirGenerate
365 case dnslex.Rrtype:
366 zp.t = l.Torc
367
368 st = zExpectRdata
369 case dnslex.Class:
370 zp.h.Class = l.Torc
371
372 if !zp.c.Blank() {
373 return zp.setParseError("no blank after class", l)
374 }
375
376 st = zExpectAnyNoClass
377 case dnslex.Blank:
378 // Discard, can happen when there is nothing on the line except the RR type.
379 case dnslex.String:
380 if zp.h.TTL, ok = setTTL(l); !ok {
381 return zp.setParseError("not a TTL", l)
382 }
383 if !zp.c.Blank() {
384 return zp.setParseError("no blank after TTL", l)
385 }
386
387 st = zExpectAnyNoTTL
388 default:
389 return zp.setParseError("syntax error at beginning", l)
390 }
391 case zExpectRrtype:
392 if l.Value != dnslex.Blank {
393 return zp.setParseError("no blank before RR type", l)
394 }
395
396 l, _ = zp.c.Next()
397 if l.Value != dnslex.Rrtype {
398 return zp.setParseError("unknown RR type", l)
399 }
400 zp.t = l.Torc
401
402 st = zExpectRdata
403 case zExpectRdata:
404 var (
405 rr RR
406 parseAsRFC3597 bool
407 )
408 switch l.As {
409 case asRR:
410 if newFn, ok := TypeToRR[zp.t]; ok {
411 rr = newFn()
412 *rr.Header() = zp.h
413
414 // We may be parsing a known RR type using the RFC3597 format. If so, we handle that here in a generic way.
415 // Custom RRs will need to be registered and will be called with processed []Tokens in
416 // parse.
417 if zp.c.Peek().Token == "\\#" {
418 parseAsRFC3597 = true
419 }
420 } else {
421 rr = &RFC3597{zp.h, rdata.RFC3597{RRType: zp.t}}
422 }
423 case asCode:
424 newFn, ok := CodeToRR[zp.t]
425 if !ok {
426 return zp.setParseError("unknown EDNS0 type", l)
427 }
428 rr = newFn()
429 *rr.Header() = zp.h
430 }
431
432 if zp.c.Peek().Token == "" {
433 // This is a dynamic update rr.
434 if err := dnslex.Discard(zp.c); err != nil {
435 return zp.setParseError(err.Err, err.Lex)
436 }
437
438 return rr, true
439 } else if l.Value == dnslex.Newline {
440 return zp.setParseError("unexpected newline", l)
441 }
442
443 parseAsRR := rr
444 if parseAsRFC3597 {
445 parseAsRR = &RFC3597{zp.h, rdata.RFC3597{RRType: zp.t}}
446 }
447
448 // This needs zparser which calls Parser for new types.
449 if err := parse(parseAsRR, zp.c, zp.origin); err != nil {
450 pe := err.(*ParseError)
451 // err is a concrete *ParseError without the file field set.
452 // The setParseError call below will construct a new
453 // *ParseError with file set to zp.file.
454
455 // err.lex may be nil in which case we substitute our current lex token.
456 if pe.lex == (dnslex.Lex{}) {
457 return zp.setParseError(pe.err, l)
458 }
459
460 return zp.setParseError(pe.err, pe.lex)
461 }
462
463 if parseAsRFC3597 {
464 err := parseAsRR.(*RFC3597).fromRFC3597(rr)
465 if err != nil {
466 return zp.setParseError(err.Error(), l)
467 }
468 }
469
470 return rr, true
471 case zExpectDirInclude:
472 if l.Value != dnslex.String {
473 return zp.setParseError("expecting $INCLUDE value, not this...", l)
474 }
475
476 neworigin := zp.origin // There may be optionally a new origin set after the filename, if not use current one
477 switch l, _ := zp.c.Next(); l.Value {
478 case dnslex.Blank:
479 l, _ := zp.c.Next()
480 if l.Value == dnslex.String {
481 name := dnsutilAbsolute(l.Token, zp.origin)
482 if name == "" {
483 return zp.setParseError("bad origin name", l)
484 }
485
486 neworigin = name
487 }
488 case dnslex.Newline, dnslex.EOF:
489 // Ok
490 default:
491 return zp.setParseError("garbage after $INCLUDE", l)
492 }
493
494 if !zp.IncludeAllowFunc(zp.path, l.Token) {
495 return zp.setParseError("$INCLUDE directive not allowed", l)
496 }
497 if zp.includeDepth >= maxIncludeDepth {
498 return zp.setParseError("too deeply nested $INCLUDE", l)
499 }
500
501 // Start with the new file
502 includePath := l.Token
503 var r1 io.Reader
504 var e1 error
505 if zp.IncludeFS != nil {
506 // fs.FS always uses / as separator, even on Windows, so use
507 // path instead of filepath here:
508 if !path.IsAbs(includePath) {
509 includePath = path.Join(path.Dir(zp.file), includePath)
510 }
511
512 // os.DirFS, and probably others, expect all paths to be
513 // relative, so clean the path and remove leading / if
514 // present:
515 includePath = strings.TrimLeft(path.Clean(includePath), "/")
516
517 r1, e1 = zp.IncludeFS.Open(includePath)
518 } else {
519 if !filepath.IsAbs(includePath) {
520 includePath = filepath.Join(filepath.Dir(zp.file), includePath)
521 }
522 r1, e1 = os.Open(includePath)
523 }
524 if e1 != nil {
525 var as string
526 if includePath != l.Token {
527 as = fmt.Sprintf(" as `%s'", includePath)
528 }
529 zp.parseErr = &ParseError{
530 file: zp.file,
531 wrappedErr: fmt.Errorf("failed to open `%s'%s: %w", l.Token, as, e1),
532 lex: l,
533 }
534 return nil, false
535 }
536
537 zp.sub = NewZoneParser(r1, neworigin, includePath)
538 zp.sub.defttl, zp.sub.includeDepth, zp.sub.r = zp.defttl, zp.includeDepth+1, r1
539 zp.sub.IncludeAllowFunc = zp.IncludeAllowFunc
540 zp.sub.IncludeFS = zp.IncludeFS
541 return zp.subNext()
542
543 case zExpectDirTTL:
544 if l.Value != dnslex.String {
545 return zp.setParseError("expecting $TTL value, not this...", l)
546 }
547
548 if err := dnslex.Discard(zp.c); err != nil {
549 return zp.setParseError(err.Err, err.Lex)
550 }
551
552 ttl, ok := stringToTTL(l.Token)
553 if !ok {
554 return zp.setParseError("expecting $TTL value, not this...", l)
555 }
556
557 zp.defttl = &ttlState{ttl, true}
558
559 st = zExpectOwnerDir
560 case zExpectDirOrigin:
561 if l.Value != dnslex.String {
562 return zp.setParseError("expecting $ORIGIN value, not this...", l)
563 }
564
565 if err := dnslex.Discard(zp.c); err != nil {
566 return zp.setParseError(err.Err, err.Lex)
567 }
568
569 name := dnsutilAbsolute(l.Token, zp.origin)
570 if name == "" {
571 return zp.setParseError("bad origin name", l)
572 }
573
574 zp.origin = name
575
576 st = zExpectOwnerDir
577 case zExpectDirGenerate:
578 if zp.generateDisallowed {
579 return zp.setParseError("nested $GENERATE directive not allowed", l)
580 }
581 if l.Value != dnslex.String {
582 return zp.setParseError("expecting $GENERATE value, not this...", l)
583 }
584
585 return zp.generate(l)
586 case zExpectAny:
587 switch l.Value {
588 case dnslex.Rrtype:
589 if zp.defttl == nil {
590 return zp.setParseError("missing TTL with no previous value", l)
591 }
592
593 zp.t = l.Torc
594
595 st = zExpectRdata
596 case dnslex.Class:
597 zp.h.Class = l.Torc
598
599 if !zp.c.Blank() {
600 return zp.setParseError("no blank after class", l)
601 }
602
603 st = zExpectAnyNoClass
604 case dnslex.String:
605 if zp.h.TTL, ok = setTTL(l); !ok {
606 return zp.setParseError("not a TTL", l)
607 }
608 if !zp.c.Blank() {
609 return zp.setParseError("no blank after TTL", l)
610 }
611
612 st = zExpectAnyNoTTL
613 default:
614 return zp.setParseError("expecting RR type, TTL or class, not this...", l)
615 }
616 case zExpectAnyNoTTL:
617 switch l.Value {
618 case dnslex.Class:
619 zp.h.Class = l.Torc
620
621 st = zExpectRrtype
622 case dnslex.Rrtype:
623 zp.t = l.Torc
624
625 st = zExpectRdata
626 default:
627 return zp.setParseError("expecting RR type or class, not this...", l)
628 }
629 case zExpectAnyNoClass:
630 switch l.Value {
631 case dnslex.String:
632 if zp.h.TTL, ok = setTTL(l); !ok {
633 return zp.setParseError("not a TTL", l)
634 }
635
636 st = zExpectRrtype
637 case dnslex.Rrtype:
638 zp.t = l.Torc
639
640 st = zExpectRdata
641 default:
642 return zp.setParseError("expecting RR type or TTL, not this...", l)
643 }
644 }
645 }
646
647 // If we get here, we and the h.Rrtype is still zero, we haven't parsed anything, this
648 // is not an error, because an empty zone file is still a zone file.
649 return nil, false
650 }
651
652 // RRs allows ranging over the RRs from the zone currently parsed. See [Msg.RRs] also.
653 func (zp *ZoneParser) RRs() iter.Seq2[RR, error] {
654 return func(yield func(RR, error) bool) {
655 for {
656 rr, ok := zp.Next()
657 if !yield(rr, zp.Err()) {
658 return
659 }
660 if !ok {
661 break
662 }
663 }
664 }
665 }
666
667 // stringToTTL parses things like 2w, 2m, etc, and returns the time in seconds.
668 func stringToTTL(token string) (uint32, bool) {
669 switch token {
670 case "300":
671 return 300, true
672 case "1800", "30m", "30M":
673 return 1800, true
674 case "3600", "1h", "1H":
675 return 3600, true
676 case "14400":
677 return 14400, true
678 case "86400", "1d", "1D":
679 return 86400, true
680 case "604800", "1w", "1W":
681 return 604800, true
682 }
683
684 var s, i uint64
685 for j := range token {
686 switch token[j] {
687 case 's', 'S':
688 s += i
689 i = 0
690 case 'm', 'M':
691 s += i * 60
692 i = 0
693 case 'h', 'H':
694 s += i * 60 * 60
695 i = 0
696 case 'd', 'D':
697 s += i * 60 * 60 * 24
698 i = 0
699 case 'w', 'W':
700 s += i * 60 * 60 * 24 * 7
701 i = 0
702 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
703 i *= 10
704 i += uint64(token[j]) - '0'
705 default:
706 return 0, false
707 }
708 }
709 if s+i > math.MaxUint32 {
710 return 0, false
711 }
712 return uint32(s + i), true
713 }
714
715 // stringgToCm parses LOC records' <digits>[.<digits>][mM] into a mantissa exponent format. Token should contain the entire
716 // string (i.e. no spaces allowed).
717 func stringToCm(token string) (e, m uint8, ok bool) {
718 if token[len(token)-1] == 'M' || token[len(token)-1] == 'm' {
719 token = token[0 : len(token)-1]
720 }
721
722 var (
723 meters, cmeters, val int
724 err error
725 )
726 mStr, cmStr, hasCM := strings.Cut(token, ".")
727 if hasCM {
728 // 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').
729 // So we simply reject it. We also make sure the first character is a digit to reject '+-' signs.
730 cmeters, err = strconv.Atoi(cmStr)
731 if err != nil || len(cmStr) > 2 || cmStr[0] < '0' || cmStr[0] > '9' {
732 return
733 }
734 if len(cmStr) == 1 {
735 // 'nn.1' must be treated as 'nn-meters and 10cm, not 1cm.
736 cmeters *= 10
737 }
738 }
739 // This slightly ugly condition will allow omitting the 'meter' part, like .01 (meaning 0.01m = 1cm).
740 if !hasCM || mStr != "" {
741 meters, err = strconv.Atoi(mStr)
742 // RFC1876 states the max value is 90000000.00. The latter two conditions enforce it.
743 if err != nil || mStr[0] < '0' || mStr[0] > '9' || meters > 90000000 || (meters == 90000000 && cmeters != 0) {
744 return
745 }
746 }
747
748 if meters > 0 {
749 e = 2
750 val = meters
751 } else {
752 e = 0
753 val = cmeters
754 }
755 for val >= 10 {
756 e++
757 val /= 10
758 }
759 return e, uint8(val), true
760 }
761
762 // LOC record helper function.
763 func locCheckNorth(token string, latitude uint32) (uint32, bool) {
764 if latitude > 90*1000*60*60 {
765 return latitude, false
766 }
767 switch token {
768 case "n", "N":
769 return LOCEquator + latitude, true
770 case "s", "S":
771 return LOCEquator - latitude, true
772 }
773 return latitude, false
774 }
775
776 // LOC record helper function.
777 func locCheckEast(token string, longitude uint32) (uint32, bool) {
778 if longitude > 180*1000*60*60 {
779 return longitude, false
780 }
781 switch token {
782 case "e", "E":
783 return LOCEquator + longitude, true
784 case "w", "W":
785 return LOCEquator - longitude, true
786 }
787 return longitude, false
788 }
789
790 // IncludeAllowFunc is a function that gets the full path of the original parsed file name and the included
791 // file path and returns true if the include is allowed.
792 type IncludeAllowFunc func(file, include string) bool
793
794 // DefaultIncludeAllowFunc returns true if the included file is on the same level or in a directory below.
795 var DefaultIncludeAllowFunc IncludeAllowFunc = defaultIncludeAllowFunc
796
797 func defaultIncludeAllowFunc(file, include string) bool {
798 up := ".." + string(os.PathSeparator)
799 rel, err := filepath.Rel(file, include)
800 if err != nil {
801 return false
802 }
803 if !strings.HasPrefix(rel, up) && rel != ".." {
804 return true
805 }
806 return false
807 }
808
809 func toParseError(err *dnslex.ScanError) error {
810 if err == nil {
811 return nil
812 }
813 return &ParseError{err: err.Err, lex: err.Lex}
814 }