scan.go 29 KB

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