tokenizer.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """Tokenize DNS zone file format"""
  17. import io
  18. import sys
  19. import dns.exception
  20. import dns.name
  21. import dns.ttl
  22. _DELIMITERS = {' ', '\t', '\n', ';', '(', ')', '"'}
  23. _QUOTING_DELIMITERS = {'"'}
  24. EOF = 0
  25. EOL = 1
  26. WHITESPACE = 2
  27. IDENTIFIER = 3
  28. QUOTED_STRING = 4
  29. COMMENT = 5
  30. DELIMITER = 6
  31. class UngetBufferFull(dns.exception.DNSException):
  32. """An attempt was made to unget a token when the unget buffer was full."""
  33. class Token:
  34. """A DNS zone file format token.
  35. ttype: The token type
  36. value: The token value
  37. has_escape: Does the token value contain escapes?
  38. """
  39. def __init__(self, ttype, value='', has_escape=False, comment=None):
  40. """Initialize a token instance."""
  41. self.ttype = ttype
  42. self.value = value
  43. self.has_escape = has_escape
  44. self.comment = comment
  45. def is_eof(self):
  46. return self.ttype == EOF
  47. def is_eol(self):
  48. return self.ttype == EOL
  49. def is_whitespace(self):
  50. return self.ttype == WHITESPACE
  51. def is_identifier(self):
  52. return self.ttype == IDENTIFIER
  53. def is_quoted_string(self):
  54. return self.ttype == QUOTED_STRING
  55. def is_comment(self):
  56. return self.ttype == COMMENT
  57. def is_delimiter(self): # pragma: no cover (we don't return delimiters yet)
  58. return self.ttype == DELIMITER
  59. def is_eol_or_eof(self):
  60. return self.ttype == EOL or self.ttype == EOF
  61. def __eq__(self, other):
  62. if not isinstance(other, Token):
  63. return False
  64. return (self.ttype == other.ttype and
  65. self.value == other.value)
  66. def __ne__(self, other):
  67. if not isinstance(other, Token):
  68. return True
  69. return (self.ttype != other.ttype or
  70. self.value != other.value)
  71. def __str__(self):
  72. return '%d "%s"' % (self.ttype, self.value)
  73. def unescape(self):
  74. if not self.has_escape:
  75. return self
  76. unescaped = ''
  77. l = len(self.value)
  78. i = 0
  79. while i < l:
  80. c = self.value[i]
  81. i += 1
  82. if c == '\\':
  83. if i >= l: # pragma: no cover (can't happen via get())
  84. raise dns.exception.UnexpectedEnd
  85. c = self.value[i]
  86. i += 1
  87. if c.isdigit():
  88. if i >= l:
  89. raise dns.exception.UnexpectedEnd
  90. c2 = self.value[i]
  91. i += 1
  92. if i >= l:
  93. raise dns.exception.UnexpectedEnd
  94. c3 = self.value[i]
  95. i += 1
  96. if not (c2.isdigit() and c3.isdigit()):
  97. raise dns.exception.SyntaxError
  98. codepoint = int(c) * 100 + int(c2) * 10 + int(c3)
  99. if codepoint > 255:
  100. raise dns.exception.SyntaxError
  101. c = chr(codepoint)
  102. unescaped += c
  103. return Token(self.ttype, unescaped)
  104. def unescape_to_bytes(self):
  105. # We used to use unescape() for TXT-like records, but this
  106. # caused problems as we'd process DNS escapes into Unicode code
  107. # points instead of byte values, and then a to_text() of the
  108. # processed data would not equal the original input. For
  109. # example, \226 in the TXT record would have a to_text() of
  110. # \195\162 because we applied UTF-8 encoding to Unicode code
  111. # point 226.
  112. #
  113. # We now apply escapes while converting directly to bytes,
  114. # avoiding this double encoding.
  115. #
  116. # This code also handles cases where the unicode input has
  117. # non-ASCII code-points in it by converting it to UTF-8. TXT
  118. # records aren't defined for Unicode, but this is the best we
  119. # can do to preserve meaning. For example,
  120. #
  121. # foo\u200bbar
  122. #
  123. # (where \u200b is Unicode code point 0x200b) will be treated
  124. # as if the input had been the UTF-8 encoding of that string,
  125. # namely:
  126. #
  127. # foo\226\128\139bar
  128. #
  129. unescaped = b''
  130. l = len(self.value)
  131. i = 0
  132. while i < l:
  133. c = self.value[i]
  134. i += 1
  135. if c == '\\':
  136. if i >= l: # pragma: no cover (can't happen via get())
  137. raise dns.exception.UnexpectedEnd
  138. c = self.value[i]
  139. i += 1
  140. if c.isdigit():
  141. if i >= l:
  142. raise dns.exception.UnexpectedEnd
  143. c2 = self.value[i]
  144. i += 1
  145. if i >= l:
  146. raise dns.exception.UnexpectedEnd
  147. c3 = self.value[i]
  148. i += 1
  149. if not (c2.isdigit() and c3.isdigit()):
  150. raise dns.exception.SyntaxError
  151. codepoint = int(c) * 100 + int(c2) * 10 + int(c3)
  152. if codepoint > 255:
  153. raise dns.exception.SyntaxError
  154. unescaped += b'%c' % (codepoint)
  155. else:
  156. # Note that as mentioned above, if c is a Unicode
  157. # code point outside of the ASCII range, then this
  158. # += is converting that code point to its UTF-8
  159. # encoding and appending multiple bytes to
  160. # unescaped.
  161. unescaped += c.encode()
  162. else:
  163. unescaped += c.encode()
  164. return Token(self.ttype, bytes(unescaped))
  165. class Tokenizer:
  166. """A DNS zone file format tokenizer.
  167. A token object is basically a (type, value) tuple. The valid
  168. types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING,
  169. COMMENT, and DELIMITER.
  170. file: The file to tokenize
  171. ungotten_char: The most recently ungotten character, or None.
  172. ungotten_token: The most recently ungotten token, or None.
  173. multiline: The current multiline level. This value is increased
  174. by one every time a '(' delimiter is read, and decreased by one every time
  175. a ')' delimiter is read.
  176. quoting: This variable is true if the tokenizer is currently
  177. reading a quoted string.
  178. eof: This variable is true if the tokenizer has encountered EOF.
  179. delimiters: The current delimiter dictionary.
  180. line_number: The current line number
  181. filename: A filename that will be returned by the where() method.
  182. idna_codec: A dns.name.IDNACodec, specifies the IDNA
  183. encoder/decoder. If None, the default IDNA 2003
  184. encoder/decoder is used.
  185. """
  186. def __init__(self, f=sys.stdin, filename=None, idna_codec=None):
  187. """Initialize a tokenizer instance.
  188. f: The file to tokenize. The default is sys.stdin.
  189. This parameter may also be a string, in which case the tokenizer
  190. will take its input from the contents of the string.
  191. filename: the name of the filename that the where() method
  192. will return.
  193. idna_codec: A dns.name.IDNACodec, specifies the IDNA
  194. encoder/decoder. If None, the default IDNA 2003
  195. encoder/decoder is used.
  196. """
  197. if isinstance(f, str):
  198. f = io.StringIO(f)
  199. if filename is None:
  200. filename = '<string>'
  201. elif isinstance(f, bytes):
  202. f = io.StringIO(f.decode())
  203. if filename is None:
  204. filename = '<string>'
  205. else:
  206. if filename is None:
  207. if f is sys.stdin:
  208. filename = '<stdin>'
  209. else:
  210. filename = '<file>'
  211. self.file = f
  212. self.ungotten_char = None
  213. self.ungotten_token = None
  214. self.multiline = 0
  215. self.quoting = False
  216. self.eof = False
  217. self.delimiters = _DELIMITERS
  218. self.line_number = 1
  219. self.filename = filename
  220. if idna_codec is None:
  221. idna_codec = dns.name.IDNA_2003
  222. self.idna_codec = idna_codec
  223. def _get_char(self):
  224. """Read a character from input.
  225. """
  226. if self.ungotten_char is None:
  227. if self.eof:
  228. c = ''
  229. else:
  230. c = self.file.read(1)
  231. if c == '':
  232. self.eof = True
  233. elif c == '\n':
  234. self.line_number += 1
  235. else:
  236. c = self.ungotten_char
  237. self.ungotten_char = None
  238. return c
  239. def where(self):
  240. """Return the current location in the input.
  241. Returns a (string, int) tuple. The first item is the filename of
  242. the input, the second is the current line number.
  243. """
  244. return (self.filename, self.line_number)
  245. def _unget_char(self, c):
  246. """Unget a character.
  247. The unget buffer for characters is only one character large; it is
  248. an error to try to unget a character when the unget buffer is not
  249. empty.
  250. c: the character to unget
  251. raises UngetBufferFull: there is already an ungotten char
  252. """
  253. if self.ungotten_char is not None:
  254. # this should never happen!
  255. raise UngetBufferFull # pragma: no cover
  256. self.ungotten_char = c
  257. def skip_whitespace(self):
  258. """Consume input until a non-whitespace character is encountered.
  259. The non-whitespace character is then ungotten, and the number of
  260. whitespace characters consumed is returned.
  261. If the tokenizer is in multiline mode, then newlines are whitespace.
  262. Returns the number of characters skipped.
  263. """
  264. skipped = 0
  265. while True:
  266. c = self._get_char()
  267. if c != ' ' and c != '\t':
  268. if (c != '\n') or not self.multiline:
  269. self._unget_char(c)
  270. return skipped
  271. skipped += 1
  272. def get(self, want_leading=False, want_comment=False):
  273. """Get the next token.
  274. want_leading: If True, return a WHITESPACE token if the
  275. first character read is whitespace. The default is False.
  276. want_comment: If True, return a COMMENT token if the
  277. first token read is a comment. The default is False.
  278. Raises dns.exception.UnexpectedEnd: input ended prematurely
  279. Raises dns.exception.SyntaxError: input was badly formed
  280. Returns a Token.
  281. """
  282. if self.ungotten_token is not None:
  283. token = self.ungotten_token
  284. self.ungotten_token = None
  285. if token.is_whitespace():
  286. if want_leading:
  287. return token
  288. elif token.is_comment():
  289. if want_comment:
  290. return token
  291. else:
  292. return token
  293. skipped = self.skip_whitespace()
  294. if want_leading and skipped > 0:
  295. return Token(WHITESPACE, ' ')
  296. token = ''
  297. ttype = IDENTIFIER
  298. has_escape = False
  299. while True:
  300. c = self._get_char()
  301. if c == '' or c in self.delimiters:
  302. if c == '' and self.quoting:
  303. raise dns.exception.UnexpectedEnd
  304. if token == '' and ttype != QUOTED_STRING:
  305. if c == '(':
  306. self.multiline += 1
  307. self.skip_whitespace()
  308. continue
  309. elif c == ')':
  310. if self.multiline <= 0:
  311. raise dns.exception.SyntaxError
  312. self.multiline -= 1
  313. self.skip_whitespace()
  314. continue
  315. elif c == '"':
  316. if not self.quoting:
  317. self.quoting = True
  318. self.delimiters = _QUOTING_DELIMITERS
  319. ttype = QUOTED_STRING
  320. continue
  321. else:
  322. self.quoting = False
  323. self.delimiters = _DELIMITERS
  324. self.skip_whitespace()
  325. continue
  326. elif c == '\n':
  327. return Token(EOL, '\n')
  328. elif c == ';':
  329. while 1:
  330. c = self._get_char()
  331. if c == '\n' or c == '':
  332. break
  333. token += c
  334. if want_comment:
  335. self._unget_char(c)
  336. return Token(COMMENT, token)
  337. elif c == '':
  338. if self.multiline:
  339. raise dns.exception.SyntaxError(
  340. 'unbalanced parentheses')
  341. return Token(EOF, comment=token)
  342. elif self.multiline:
  343. self.skip_whitespace()
  344. token = ''
  345. continue
  346. else:
  347. return Token(EOL, '\n', comment=token)
  348. else:
  349. # This code exists in case we ever want a
  350. # delimiter to be returned. It never produces
  351. # a token currently.
  352. token = c
  353. ttype = DELIMITER
  354. else:
  355. self._unget_char(c)
  356. break
  357. elif self.quoting and c == '\n':
  358. raise dns.exception.SyntaxError('newline in quoted string')
  359. elif c == '\\':
  360. #
  361. # It's an escape. Put it and the next character into
  362. # the token; it will be checked later for goodness.
  363. #
  364. token += c
  365. has_escape = True
  366. c = self._get_char()
  367. if c == '' or (c == '\n' and not self.quoting):
  368. raise dns.exception.UnexpectedEnd
  369. token += c
  370. if token == '' and ttype != QUOTED_STRING:
  371. if self.multiline:
  372. raise dns.exception.SyntaxError('unbalanced parentheses')
  373. ttype = EOF
  374. return Token(ttype, token, has_escape)
  375. def unget(self, token):
  376. """Unget a token.
  377. The unget buffer for tokens is only one token large; it is
  378. an error to try to unget a token when the unget buffer is not
  379. empty.
  380. token: the token to unget
  381. Raises UngetBufferFull: there is already an ungotten token
  382. """
  383. if self.ungotten_token is not None:
  384. raise UngetBufferFull
  385. self.ungotten_token = token
  386. def next(self):
  387. """Return the next item in an iteration.
  388. Returns a Token.
  389. """
  390. token = self.get()
  391. if token.is_eof():
  392. raise StopIteration
  393. return token
  394. __next__ = next
  395. def __iter__(self):
  396. return self
  397. # Helpers
  398. def get_int(self, base=10):
  399. """Read the next token and interpret it as an unsigned integer.
  400. Raises dns.exception.SyntaxError if not an unsigned integer.
  401. Returns an int.
  402. """
  403. token = self.get().unescape()
  404. if not token.is_identifier():
  405. raise dns.exception.SyntaxError('expecting an identifier')
  406. if not token.value.isdigit():
  407. raise dns.exception.SyntaxError('expecting an integer')
  408. return int(token.value, base)
  409. def get_uint8(self):
  410. """Read the next token and interpret it as an 8-bit unsigned
  411. integer.
  412. Raises dns.exception.SyntaxError if not an 8-bit unsigned integer.
  413. Returns an int.
  414. """
  415. value = self.get_int()
  416. if value < 0 or value > 255:
  417. raise dns.exception.SyntaxError(
  418. '%d is not an unsigned 8-bit integer' % value)
  419. return value
  420. def get_uint16(self, base=10):
  421. """Read the next token and interpret it as a 16-bit unsigned
  422. integer.
  423. Raises dns.exception.SyntaxError if not a 16-bit unsigned integer.
  424. Returns an int.
  425. """
  426. value = self.get_int(base=base)
  427. if value < 0 or value > 65535:
  428. if base == 8:
  429. raise dns.exception.SyntaxError(
  430. '%o is not an octal unsigned 16-bit integer' % value)
  431. else:
  432. raise dns.exception.SyntaxError(
  433. '%d is not an unsigned 16-bit integer' % value)
  434. return value
  435. def get_uint32(self, base=10):
  436. """Read the next token and interpret it as a 32-bit unsigned
  437. integer.
  438. Raises dns.exception.SyntaxError if not a 32-bit unsigned integer.
  439. Returns an int.
  440. """
  441. value = self.get_int(base=base)
  442. if value < 0 or value > 4294967295:
  443. raise dns.exception.SyntaxError(
  444. '%d is not an unsigned 32-bit integer' % value)
  445. return value
  446. def get_uint48(self, base=10):
  447. """Read the next token and interpret it as a 48-bit unsigned
  448. integer.
  449. Raises dns.exception.SyntaxError if not a 48-bit unsigned integer.
  450. Returns an int.
  451. """
  452. value = self.get_int(base=base)
  453. if value < 0 or value > 281474976710655:
  454. raise dns.exception.SyntaxError(
  455. '%d is not an unsigned 48-bit integer' % value)
  456. return value
  457. def get_string(self, max_length=None):
  458. """Read the next token and interpret it as a string.
  459. Raises dns.exception.SyntaxError if not a string.
  460. Raises dns.exception.SyntaxError if token value length
  461. exceeds max_length (if specified).
  462. Returns a string.
  463. """
  464. token = self.get().unescape()
  465. if not (token.is_identifier() or token.is_quoted_string()):
  466. raise dns.exception.SyntaxError('expecting a string')
  467. if max_length and len(token.value) > max_length:
  468. raise dns.exception.SyntaxError("string too long")
  469. return token.value
  470. def get_identifier(self):
  471. """Read the next token, which should be an identifier.
  472. Raises dns.exception.SyntaxError if not an identifier.
  473. Returns a string.
  474. """
  475. token = self.get().unescape()
  476. if not token.is_identifier():
  477. raise dns.exception.SyntaxError('expecting an identifier')
  478. return token.value
  479. def get_remaining(self, max_tokens=None):
  480. """Return the remaining tokens on the line, until an EOL or EOF is seen.
  481. max_tokens: If not None, stop after this number of tokens.
  482. Returns a list of tokens.
  483. """
  484. tokens = []
  485. while True:
  486. token = self.get()
  487. if token.is_eol_or_eof():
  488. self.unget(token)
  489. break
  490. tokens.append(token)
  491. if len(tokens) == max_tokens:
  492. break
  493. return tokens
  494. def concatenate_remaining_identifiers(self, allow_empty=False):
  495. """Read the remaining tokens on the line, which should be identifiers.
  496. Raises dns.exception.SyntaxError if there are no remaining tokens,
  497. unless `allow_empty=True` is given.
  498. Raises dns.exception.SyntaxError if a token is seen that is not an
  499. identifier.
  500. Returns a string containing a concatenation of the remaining
  501. identifiers.
  502. """
  503. s = ""
  504. while True:
  505. token = self.get().unescape()
  506. if token.is_eol_or_eof():
  507. self.unget(token)
  508. break
  509. if not token.is_identifier():
  510. raise dns.exception.SyntaxError
  511. s += token.value
  512. if not (allow_empty or s):
  513. raise dns.exception.SyntaxError('expecting another identifier')
  514. return s
  515. def as_name(self, token, origin=None, relativize=False, relativize_to=None):
  516. """Try to interpret the token as a DNS name.
  517. Raises dns.exception.SyntaxError if not a name.
  518. Returns a dns.name.Name.
  519. """
  520. if not token.is_identifier():
  521. raise dns.exception.SyntaxError('expecting an identifier')
  522. name = dns.name.from_text(token.value, origin, self.idna_codec)
  523. return name.choose_relativity(relativize_to or origin, relativize)
  524. def get_name(self, origin=None, relativize=False, relativize_to=None):
  525. """Read the next token and interpret it as a DNS name.
  526. Raises dns.exception.SyntaxError if not a name.
  527. Returns a dns.name.Name.
  528. """
  529. token = self.get()
  530. return self.as_name(token, origin, relativize, relativize_to)
  531. def get_eol_as_token(self):
  532. """Read the next token and raise an exception if it isn't EOL or
  533. EOF.
  534. Returns a string.
  535. """
  536. token = self.get()
  537. if not token.is_eol_or_eof():
  538. raise dns.exception.SyntaxError(
  539. 'expected EOL or EOF, got %d "%s"' % (token.ttype,
  540. token.value))
  541. return token
  542. def get_eol(self):
  543. return self.get_eol_as_token().value
  544. def get_ttl(self):
  545. """Read the next token and interpret it as a DNS TTL.
  546. Raises dns.exception.SyntaxError or dns.ttl.BadTTL if not an
  547. identifier or badly formed.
  548. Returns an int.
  549. """
  550. token = self.get().unescape()
  551. if not token.is_identifier():
  552. raise dns.exception.SyntaxError('expecting an identifier')
  553. return dns.ttl.from_text(token.value)