Debian Codegraph @

internal/dnslex/lex.go

raw
1 package dnslex
2
3 import (
4 "bufio"
5 "io"
6 "strconv"
7 "strings"
8 )
9
10 // ScanError is a scanning error, it has no presentation format, it is expected that ParseError will be
11 // wrapping this error, and uses Err and Lex directly.
12 type ScanError struct {
13 Err string
14 Lex Lex
15 }
16
17 func (e *ScanError) Error() string { return "" }
18
19 // Tokenize a RFC 1035 zone file. The tokenizer will normalize it:
20 // * Add ownernames if they are left blank;
21 // * Suppress sequences of spaces;
22 // * Make each RR fit on one line ([Newline] is send as last)
23 // * Handle braces - anywhere.
24 const (
25 // Zone file
26 EOF uint8 = iota
27 Error
28 String
29 Blank
30 Quote
31 Newline
32 Rrtype
33 Owner
34 Class
35 DirOrigin // $ORIGIN
36 DirTTL // $TTL
37 DirInclude // $INCLUDE
38 DirGenerate // $GENERATE
39 )
40
41 type Lex struct {
42 Token string // text of the token
43 As uint8 // create an RR (asRR), an EDNS0 (asCode) or DSO RR (asStateful)
44 Value uint8 // value: String, Blank, etc.
45 Line uint32 // line in the file
46 Column uint16 // column in the file
47 Torc uint16 // type or class as parsed in the lexer, we only need to look this up in the grammar
48 }
49
50 const (
51 asRR uint8 = iota // parse the string as an RR.
52 asCode // parse the string as an EDNS RR.
53 asStateful // TODO, but parse the string as an DSO RR.
54 )
55
56 // Lexer tokenizes the zone data, so that the grammar implemented in ZoneParser can parse RRs out of an RFC
57 // 1035 styled text file.
58 type Lexer struct {
59 line uint32 // yes this overflows for insane zone files...
60 column uint16
61 brace uint8
62 keys uint8 // bit0: kQuote, bit1: kSpace, bit2: kCommt, bit3: kRRtype, bit4: kOwner, bit5: kNextL, bit6: kEol
63 tok []byte
64
65 br io.ByteReader
66 readErr error
67
68 // Current or peek token.
69 l Lex
70 cachedL *Lex // used when finding a token, but delaying it's return.
71
72 stringToType map[string]uint16
73 stringToCode map[string]uint16
74 stringToClass map[string]uint16
75 }
76
77 // Key bit definitions.
78 const (
79 kQuote uint8 = 1 << iota
80 kSpace
81 kCommt
82 kRRtype
83 kOwner
84 kNextL
85 kEOL
86 )
87
88 func (zl *Lexer) SetKey(key uint8) { zl.keys |= key }
89 func (zl *Lexer) ClearKey(key uint8) { zl.keys &^= key }
90 func (zl *Lexer) Key(key uint8) bool { return zl.keys&key != 0 }
91
92 // New returns a pointer to a new Lexer.
93 func New(r io.Reader, StringToType, StringToCode, StringToClass map[string]uint16) *Lexer {
94 br, ok := r.(io.ByteReader)
95 if !ok {
96 br = bufio.NewReaderSize(r, 1024)
97 }
98
99 zl := &Lexer{
100 br: br,
101 tok: make([]byte, 512),
102 line: 1,
103 stringToType: StringToType,
104 stringToCode: StringToCode,
105 stringToClass: StringToClass,
106 }
107 zl.SetKey(kOwner)
108 return zl
109 }
110
111 func (zl *Lexer) Err() error {
112 if zl.readErr == io.EOF {
113 return nil
114 }
115
116 return zl.readErr
117 }
118
119 // readByte returns the next byte from the input.
120 func (zl *Lexer) readByte() (byte, bool) {
121 if zl.readErr != nil {
122 return 0, false
123 }
124
125 c, err := zl.br.ReadByte()
126 if err != nil {
127 zl.readErr = err
128 return 0, false
129 }
130
131 // delay the newline handling until the next token is delivered,
132 // fixes off-by-one errors when reporting a parse error.
133 if zl.Key(kEOL) {
134 zl.line++
135 zl.column = 0
136 zl.ClearKey(kEOL)
137 }
138
139 if c == '\n' {
140 zl.SetKey(kEOL)
141 return c, true
142 }
143
144 zl.column++
145 return c, true
146 }
147
148 // Blank consumes the next token and returns false if the token was not a blacnk
149 func (zl *Lexer) Blank() bool { l, _ := zl.Next(); return l.Value == Blank }
150
151 func (zl *Lexer) Peek() Lex {
152 if zl.Key(kNextL) {
153 return zl.l
154 }
155
156 l, ok := zl.Next()
157 if !ok {
158 return l
159 }
160
161 if zl.Key(kNextL) {
162 // Cache l. Next returns zl.cachedL then zl.l.
163 zl.cachedL = &l
164 return l
165 }
166
167 // In this case l == zl.l, so we just tell Next to return zl.l.
168 zl.SetKey(kNextL)
169 return l
170 }
171
172 func (zl *Lexer) Next() (Lex, bool) {
173 l := &zl.l
174 switch {
175 case zl.cachedL != nil:
176 l, zl.cachedL = zl.cachedL, nil
177 return *l, true
178 case zl.Key(kNextL):
179 zl.ClearKey(kNextL)
180 return *l, true
181 case l.Value == Error:
182 // Parsing errors should be sticky.
183 return Lex{Value: EOF}, false
184 }
185
186 zl.tok = zl.tok[:0]
187 escape := false
188 l.As = asRR
189
190 for x, ok := zl.readByte(); ok; x, ok = zl.readByte() {
191 l.Line, l.Column = zl.line, zl.column
192
193 switch x {
194 case ' ', '\t':
195 if escape || zl.Key(kQuote) {
196 zl.tok = append(zl.tok, x)
197 escape = false
198 continue
199 }
200
201 if zl.Key(kCommt) {
202 continue
203 }
204
205 var retL Lex
206 if len(zl.tok) > 0 {
207 if zl.Key(kOwner) {
208
209 l.Token = string(zl.tok)
210 l.Value = directive(l.Token)
211
212 retL = *l
213 } else {
214 l.Value = String
215 l.Token = string(zl.tok)
216
217 if !zl.Key(kRRtype) {
218 zl.typeOrCodeOrClass(l)
219 }
220 retL = *l
221 }
222 }
223
224 zl.ClearKey(kOwner)
225
226 if !zl.Key(kSpace) {
227 zl.SetKey(kSpace)
228
229 l.Value = Blank
230 l.Token = " "
231
232 if retL.Value == EOF { // empty
233 return *l, true
234 }
235
236 zl.SetKey(kNextL)
237 }
238
239 if retL.Value != EOF { // not empty
240 return retL, true
241 }
242 case ';':
243 if escape || zl.Key(kQuote) {
244 // Inside quotes or escaped this is legal.
245 zl.tok = append(zl.tok, x)
246 escape = false
247 continue
248 }
249
250 zl.SetKey(kCommt)
251
252 if len(zl.tok) > 0 {
253 l.Value = String
254 l.Token = string(zl.tok)
255 return *l, true
256 }
257 case '\r':
258 escape = false
259
260 if zl.Key(kQuote) {
261 zl.tok = append(zl.tok, x)
262 }
263
264 // discard if outside of quotes
265 case '\n':
266 escape = false
267
268 // Escaped newline
269 if zl.Key(kQuote) {
270 zl.tok = append(zl.tok, x)
271 continue
272 }
273
274 if zl.Key(kCommt) {
275 zl.ClearKey(kCommt)
276 zl.ClearKey(kRRtype)
277
278 if zl.brace == 0 {
279 zl.SetKey(kOwner)
280
281 l.Value = Newline
282 l.Token = "\n"
283 return *l, true
284 }
285 continue
286 }
287
288 if zl.brace == 0 {
289 // If there is previous text, we should output it here
290 var retL Lex
291 if len(zl.tok) != 0 {
292 l.Value = String
293 l.Token = string(zl.tok)
294
295 if !zl.Key(kRRtype) {
296 zl.typeOrCodeOrClass(l)
297 }
298
299 retL = *l
300 }
301
302 l.Value = Newline
303 l.Token = "\n"
304
305 zl.ClearKey(kRRtype)
306 zl.SetKey(kOwner)
307
308 if retL.Value != EOF { // not empty
309 zl.SetKey(kNextL)
310 return retL, true
311 }
312
313 return *l, true
314 }
315 case '\\':
316 // comments do not get escaped chars, everything is copied
317 if zl.Key(kCommt) {
318 continue
319 }
320
321 // something already escaped must be in string
322 if escape {
323 zl.tok = append(zl.tok, x)
324 escape = false
325 continue
326 }
327
328 // something escaped outside of string gets added to string
329 zl.tok = append(zl.tok, x)
330 escape = true
331 case '"':
332 if zl.Key(kCommt) {
333 continue
334 }
335
336 if escape {
337 zl.tok = append(zl.tok, x)
338 escape = false
339 continue
340 }
341
342 zl.ClearKey(kSpace)
343
344 // send previous gathered text and the quote
345 var retL Lex
346 if len(zl.tok) != 0 {
347 l.Value = String
348 l.Token = string(zl.tok)
349
350 retL = *l
351 }
352
353 // send quote itself as separate token
354 l.Value = Quote
355 l.Token = "\""
356
357 if zl.Key(kQuote) {
358 zl.ClearKey(kQuote)
359 } else {
360 zl.SetKey(kQuote)
361 }
362
363 if retL.Value == String {
364 zl.SetKey(kNextL)
365 return retL, true
366 }
367
368 return *l, true
369 case '(', ')':
370 if zl.Key(kCommt) {
371 continue
372 }
373
374 if escape || zl.Key(kQuote) {
375 // Inside quotes or escaped this is legal.
376 zl.tok = append(zl.tok, x)
377 escape = false
378 continue
379 }
380
381 switch x {
382 case ')':
383 if zl.brace == 0 {
384 l.Token = "extra closing brace"
385 l.Value = Error
386 return *l, true
387 }
388 zl.brace--
389
390 case '(':
391 zl.brace++
392 if zl.brace > 10 {
393 l.Token = "excessive opening braces"
394 l.Value = Error
395 return *l, true
396 }
397 }
398 default:
399 escape = false
400 if !zl.Key(kCommt) {
401 zl.tok = append(zl.tok, x)
402 zl.ClearKey(kSpace)
403 }
404 }
405 }
406
407 if zl.readErr != nil && zl.readErr != io.EOF {
408 // Don't return any tokens after a read error occurs.
409 return Lex{Value: EOF}, false
410 }
411
412 if len(zl.tok) > 0 {
413 // Send remainder of str
414 l.Value = String
415 l.Token = string(zl.tok)
416 return *l, true
417 }
418
419 if zl.brace != 0 {
420 l.Token = "unbalanced brace"
421 l.Value = Error
422 return *l, true
423 }
424
425 return Lex{Value: EOF}, false
426 }
427
428 // Extract the class number from CLASSxx
429 func classToInt(token string) (uint16, bool) {
430 class, err := strconv.Atoi(token[5:])
431 return uint16(class), err == nil && class >= 0
432 }
433
434 // Extract the rr number from TYPExxx. There is no length check, it is assumed the caller has checked the
435 // prefix is at least "TYPE" (4)
436 func TypeToInt(token string) (uint16, bool) {
437 typ, err := strconv.Atoi(token[4:])
438 return uint16(typ), err == nil && typ >= 0
439 }
440
441 // Discard discards the rest of the "line".
442 func Discard(c *Lexer) *ScanError {
443 l, _ := c.Next()
444 switch l.Value {
445 case Blank:
446 l, _ = c.Next()
447 if l.Value != Newline && l.Value != EOF {
448 return &ScanError{Err: "garbage after rdata", Lex: l}
449 }
450 case Newline:
451 case EOF:
452 default:
453 return &ScanError{Err: "garbage after rdata", Lex: l}
454 }
455 return nil
456 }
457
458 // Tokens is used to gather up the remaining tokens and hand them to a custom Scan method for external RRs.
459 func Tokens(c *Lexer) []string {
460 tokens := []string{}
461 for {
462 l, _ := c.Next()
463 switch l.Value {
464 case Blank:
465 case Newline, EOF:
466 return tokens
467 default:
468 tokens = append(tokens, l.Token)
469 }
470 }
471 }
472
473 // upperLookup will defer strings.ToUpper in the map lookup, until after the lookup has occurred and nothing
474 // was found.
475 func upperLookup(s string, m map[string]uint16) (uint16, bool) {
476 if t, ok := m[s]; ok {
477 return t, true
478 }
479 t, ok := m[strings.ToUpper(s)]
480 return t, ok
481 }
482
483 // typeOrCodeOrClass returns the type, or code, or TYPExxxx, or class, or CLASSxxxx, from the current token in
484 // l. The check happens in that order.
485 func (zl *Lexer) typeOrCodeOrClass(l *Lex) {
486 if t, ok := upperLookup(l.Token, zl.stringToType); ok {
487 l.Value = Rrtype
488 l.Torc = t
489 zl.SetKey(kRRtype)
490 return
491 }
492
493 if t, ok := zl.stringToClass[l.Token]; ok {
494 l.Value = Class
495 l.Torc = t
496 return
497 }
498
499 if strings.HasPrefix(l.Token, "TYPE") {
500 t, ok := TypeToInt(l.Token)
501 if !ok {
502 l.Token = "unknown RR type"
503 l.Value = Error
504 return
505 }
506 l.Value = Rrtype
507 l.Torc = t
508 zl.SetKey(kRRtype)
509 return
510 }
511
512 if strings.HasPrefix(l.Token, "CLASS") {
513 t, ok := classToInt(l.Token)
514 if !ok {
515 l.Token = "unknown class"
516 l.Value = Error
517 return
518 }
519 l.Value = Class
520 l.Torc = t
521 }
522
523 if t, ok := zl.stringToCode[l.Token]; ok {
524 l.As = asCode
525 l.Value = Rrtype
526 l.Torc = t
527 zl.SetKey(kRRtype)
528 return
529 }
530 }
531
532 func directive(s string) uint8 {
533 if s[0] != '$' {
534 return Owner
535 }
536 dir, ok := dirMap[s]
537 if ok {
538 return dir
539 }
540 return Owner
541 }
542
543 var dirMap = map[string]uint8{
544 "$TTL": DirTTL,
545 "$ORIGIN": DirOrigin,
546 "$INCLUDE": DirInclude,
547 "$GENERATE": DirGenerate,
548 }