You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

571 lines
18 KiB

4 years ago
  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 master file format"""
  17. from io import StringIO
  18. import sys
  19. import dns.exception
  20. import dns.name
  21. import dns.ttl
  22. from ._compat import long, text_type, binary_type
  23. _DELIMITERS = {
  24. ' ': True,
  25. '\t': True,
  26. '\n': True,
  27. ';': True,
  28. '(': True,
  29. ')': True,
  30. '"': True}
  31. _QUOTING_DELIMITERS = {'"': True}
  32. EOF = 0
  33. EOL = 1
  34. WHITESPACE = 2
  35. IDENTIFIER = 3
  36. QUOTED_STRING = 4
  37. COMMENT = 5
  38. DELIMITER = 6
  39. class UngetBufferFull(dns.exception.DNSException):
  40. """An attempt was made to unget a token when the unget buffer was full."""
  41. class Token(object):
  42. """A DNS master file format token.
  43. ttype: The token type
  44. value: The token value
  45. has_escape: Does the token value contain escapes?
  46. """
  47. def __init__(self, ttype, value='', has_escape=False):
  48. """Initialize a token instance."""
  49. self.ttype = ttype
  50. self.value = value
  51. self.has_escape = has_escape
  52. def is_eof(self):
  53. return self.ttype == EOF
  54. def is_eol(self):
  55. return self.ttype == EOL
  56. def is_whitespace(self):
  57. return self.ttype == WHITESPACE
  58. def is_identifier(self):
  59. return self.ttype == IDENTIFIER
  60. def is_quoted_string(self):
  61. return self.ttype == QUOTED_STRING
  62. def is_comment(self):
  63. return self.ttype == COMMENT
  64. def is_delimiter(self):
  65. return self.ttype == DELIMITER
  66. def is_eol_or_eof(self):
  67. return self.ttype == EOL or self.ttype == EOF
  68. def __eq__(self, other):
  69. if not isinstance(other, Token):
  70. return False
  71. return (self.ttype == other.ttype and
  72. self.value == other.value)
  73. def __ne__(self, other):
  74. if not isinstance(other, Token):
  75. return True
  76. return (self.ttype != other.ttype or
  77. self.value != other.value)
  78. def __str__(self):
  79. return '%d "%s"' % (self.ttype, self.value)
  80. def unescape(self):
  81. if not self.has_escape:
  82. return self
  83. unescaped = ''
  84. l = len(self.value)
  85. i = 0
  86. while i < l:
  87. c = self.value[i]
  88. i += 1
  89. if c == '\\':
  90. if i >= l:
  91. raise dns.exception.UnexpectedEnd
  92. c = self.value[i]
  93. i += 1
  94. if c.isdigit():
  95. if i >= l:
  96. raise dns.exception.UnexpectedEnd
  97. c2 = self.value[i]
  98. i += 1
  99. if i >= l:
  100. raise dns.exception.UnexpectedEnd
  101. c3 = self.value[i]
  102. i += 1
  103. if not (c2.isdigit() and c3.isdigit()):
  104. raise dns.exception.SyntaxError
  105. c = chr(int(c) * 100 + int(c2) * 10 + int(c3))
  106. unescaped += c
  107. return Token(self.ttype, unescaped)
  108. # compatibility for old-style tuple tokens
  109. def __len__(self):
  110. return 2
  111. def __iter__(self):
  112. return iter((self.ttype, self.value))
  113. def __getitem__(self, i):
  114. if i == 0:
  115. return self.ttype
  116. elif i == 1:
  117. return self.value
  118. else:
  119. raise IndexError
  120. class Tokenizer(object):
  121. """A DNS master file format tokenizer.
  122. A token object is basically a (type, value) tuple. The valid
  123. types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING,
  124. COMMENT, and DELIMITER.
  125. file: The file to tokenize
  126. ungotten_char: The most recently ungotten character, or None.
  127. ungotten_token: The most recently ungotten token, or None.
  128. multiline: The current multiline level. This value is increased
  129. by one every time a '(' delimiter is read, and decreased by one every time
  130. a ')' delimiter is read.
  131. quoting: This variable is true if the tokenizer is currently
  132. reading a quoted string.
  133. eof: This variable is true if the tokenizer has encountered EOF.
  134. delimiters: The current delimiter dictionary.
  135. line_number: The current line number
  136. filename: A filename that will be returned by the where() method.
  137. """
  138. def __init__(self, f=sys.stdin, filename=None):
  139. """Initialize a tokenizer instance.
  140. f: The file to tokenize. The default is sys.stdin.
  141. This parameter may also be a string, in which case the tokenizer
  142. will take its input from the contents of the string.
  143. filename: the name of the filename that the where() method
  144. will return.
  145. """
  146. if isinstance(f, text_type):
  147. f = StringIO(f)
  148. if filename is None:
  149. filename = '<string>'
  150. elif isinstance(f, binary_type):
  151. f = StringIO(f.decode())
  152. if filename is None:
  153. filename = '<string>'
  154. else:
  155. if filename is None:
  156. if f is sys.stdin:
  157. filename = '<stdin>'
  158. else:
  159. filename = '<file>'
  160. self.file = f
  161. self.ungotten_char = None
  162. self.ungotten_token = None
  163. self.multiline = 0
  164. self.quoting = False
  165. self.eof = False
  166. self.delimiters = _DELIMITERS
  167. self.line_number = 1
  168. self.filename = filename
  169. def _get_char(self):
  170. """Read a character from input.
  171. """
  172. if self.ungotten_char is None:
  173. if self.eof:
  174. c = ''
  175. else:
  176. c = self.file.read(1)
  177. if c == '':
  178. self.eof = True
  179. elif c == '\n':
  180. self.line_number += 1
  181. else:
  182. c = self.ungotten_char
  183. self.ungotten_char = None
  184. return c
  185. def where(self):
  186. """Return the current location in the input.
  187. Returns a (string, int) tuple. The first item is the filename of
  188. the input, the second is the current line number.
  189. """
  190. return (self.filename, self.line_number)
  191. def _unget_char(self, c):
  192. """Unget a character.
  193. The unget buffer for characters is only one character large; it is
  194. an error to try to unget a character when the unget buffer is not
  195. empty.
  196. c: the character to unget
  197. raises UngetBufferFull: there is already an ungotten char
  198. """
  199. if self.ungotten_char is not None:
  200. raise UngetBufferFull
  201. self.ungotten_char = c
  202. def skip_whitespace(self):
  203. """Consume input until a non-whitespace character is encountered.
  204. The non-whitespace character is then ungotten, and the number of
  205. whitespace characters consumed is returned.
  206. If the tokenizer is in multiline mode, then newlines are whitespace.
  207. Returns the number of characters skipped.
  208. """
  209. skipped = 0
  210. while True:
  211. c = self._get_char()
  212. if c != ' ' and c != '\t':
  213. if (c != '\n') or not self.multiline:
  214. self._unget_char(c)
  215. return skipped
  216. skipped += 1
  217. def get(self, want_leading=False, want_comment=False):
  218. """Get the next token.
  219. want_leading: If True, return a WHITESPACE token if the
  220. first character read is whitespace. The default is False.
  221. want_comment: If True, return a COMMENT token if the
  222. first token read is a comment. The default is False.
  223. Raises dns.exception.UnexpectedEnd: input ended prematurely
  224. Raises dns.exception.SyntaxError: input was badly formed
  225. Returns a Token.
  226. """
  227. if self.ungotten_token is not None:
  228. token = self.ungotten_token
  229. self.ungotten_token = None
  230. if token.is_whitespace():
  231. if want_leading:
  232. return token
  233. elif token.is_comment():
  234. if want_comment:
  235. return token
  236. else:
  237. return token
  238. skipped = self.skip_whitespace()
  239. if want_leading and skipped > 0:
  240. return Token(WHITESPACE, ' ')
  241. token = ''
  242. ttype = IDENTIFIER
  243. has_escape = False
  244. while True:
  245. c = self._get_char()
  246. if c == '' or c in self.delimiters:
  247. if c == '' and self.quoting:
  248. raise dns.exception.UnexpectedEnd
  249. if token == '' and ttype != QUOTED_STRING:
  250. if c == '(':
  251. self.multiline += 1
  252. self.skip_whitespace()
  253. continue
  254. elif c == ')':
  255. if self.multiline <= 0:
  256. raise dns.exception.SyntaxError
  257. self.multiline -= 1
  258. self.skip_whitespace()
  259. continue
  260. elif c == '"':
  261. if not self.quoting:
  262. self.quoting = True
  263. self.delimiters = _QUOTING_DELIMITERS
  264. ttype = QUOTED_STRING
  265. continue
  266. else:
  267. self.quoting = False
  268. self.delimiters = _DELIMITERS
  269. self.skip_whitespace()
  270. continue
  271. elif c == '\n':
  272. return Token(EOL, '\n')
  273. elif c == ';':
  274. while 1:
  275. c = self._get_char()
  276. if c == '\n' or c == '':
  277. break
  278. token += c
  279. if want_comment:
  280. self._unget_char(c)
  281. return Token(COMMENT, token)
  282. elif c == '':
  283. if self.multiline:
  284. raise dns.exception.SyntaxError(
  285. 'unbalanced parentheses')
  286. return Token(EOF)
  287. elif self.multiline:
  288. self.skip_whitespace()
  289. token = ''
  290. continue
  291. else:
  292. return Token(EOL, '\n')
  293. else:
  294. # This code exists in case we ever want a
  295. # delimiter to be returned. It never produces
  296. # a token currently.
  297. token = c
  298. ttype = DELIMITER
  299. else:
  300. self._unget_char(c)
  301. break
  302. elif self.quoting:
  303. if c == '\\':
  304. c = self._get_char()
  305. if c == '':
  306. raise dns.exception.UnexpectedEnd
  307. if c.isdigit():
  308. c2 = self._get_char()
  309. if c2 == '':
  310. raise dns.exception.UnexpectedEnd
  311. c3 = self._get_char()
  312. if c == '':
  313. raise dns.exception.UnexpectedEnd
  314. if not (c2.isdigit() and c3.isdigit()):
  315. raise dns.exception.SyntaxError
  316. c = chr(int(c) * 100 + int(c2) * 10 + int(c3))
  317. elif c == '\n':
  318. raise dns.exception.SyntaxError('newline in quoted string')
  319. elif c == '\\':
  320. #
  321. # It's an escape. Put it and the next character into
  322. # the token; it will be checked later for goodness.
  323. #
  324. token += c
  325. has_escape = True
  326. c = self._get_char()
  327. if c == '' or c == '\n':
  328. raise dns.exception.UnexpectedEnd
  329. token += c
  330. if token == '' and ttype != QUOTED_STRING:
  331. if self.multiline:
  332. raise dns.exception.SyntaxError('unbalanced parentheses')
  333. ttype = EOF
  334. return Token(ttype, token, has_escape)
  335. def unget(self, token):
  336. """Unget a token.
  337. The unget buffer for tokens is only one token large; it is
  338. an error to try to unget a token when the unget buffer is not
  339. empty.
  340. token: the token to unget
  341. Raises UngetBufferFull: there is already an ungotten token
  342. """
  343. if self.ungotten_token is not None:
  344. raise UngetBufferFull
  345. self.ungotten_token = token
  346. def next(self):
  347. """Return the next item in an iteration.
  348. Returns a Token.
  349. """
  350. token = self.get()
  351. if token.is_eof():
  352. raise StopIteration
  353. return token
  354. __next__ = next
  355. def __iter__(self):
  356. return self
  357. # Helpers
  358. def get_int(self, base=10):
  359. """Read the next token and interpret it as an integer.
  360. Raises dns.exception.SyntaxError if not an integer.
  361. Returns an int.
  362. """
  363. token = self.get().unescape()
  364. if not token.is_identifier():
  365. raise dns.exception.SyntaxError('expecting an identifier')
  366. if not token.value.isdigit():
  367. raise dns.exception.SyntaxError('expecting an integer')
  368. return int(token.value, base)
  369. def get_uint8(self):
  370. """Read the next token and interpret it as an 8-bit unsigned
  371. integer.
  372. Raises dns.exception.SyntaxError if not an 8-bit unsigned integer.
  373. Returns an int.
  374. """
  375. value = self.get_int()
  376. if value < 0 or value > 255:
  377. raise dns.exception.SyntaxError(
  378. '%d is not an unsigned 8-bit integer' % value)
  379. return value
  380. def get_uint16(self, base=10):
  381. """Read the next token and interpret it as a 16-bit unsigned
  382. integer.
  383. Raises dns.exception.SyntaxError if not a 16-bit unsigned integer.
  384. Returns an int.
  385. """
  386. value = self.get_int(base=base)
  387. if value < 0 or value > 65535:
  388. if base == 8:
  389. raise dns.exception.SyntaxError(
  390. '%o is not an octal unsigned 16-bit integer' % value)
  391. else:
  392. raise dns.exception.SyntaxError(
  393. '%d is not an unsigned 16-bit integer' % value)
  394. return value
  395. def get_uint32(self):
  396. """Read the next token and interpret it as a 32-bit unsigned
  397. integer.
  398. Raises dns.exception.SyntaxError if not a 32-bit unsigned integer.
  399. Returns an int.
  400. """
  401. token = self.get().unescape()
  402. if not token.is_identifier():
  403. raise dns.exception.SyntaxError('expecting an identifier')
  404. if not token.value.isdigit():
  405. raise dns.exception.SyntaxError('expecting an integer')
  406. value = long(token.value)
  407. if value < 0 or value > long(4294967296):
  408. raise dns.exception.SyntaxError(
  409. '%d is not an unsigned 32-bit integer' % value)
  410. return value
  411. def get_string(self, origin=None):
  412. """Read the next token and interpret it as a string.
  413. Raises dns.exception.SyntaxError if not a string.
  414. Returns a string.
  415. """
  416. token = self.get().unescape()
  417. if not (token.is_identifier() or token.is_quoted_string()):
  418. raise dns.exception.SyntaxError('expecting a string')
  419. return token.value
  420. def get_identifier(self, origin=None):
  421. """Read the next token, which should be an identifier.
  422. Raises dns.exception.SyntaxError if not an identifier.
  423. Returns a string.
  424. """
  425. token = self.get().unescape()
  426. if not token.is_identifier():
  427. raise dns.exception.SyntaxError('expecting an identifier')
  428. return token.value
  429. def get_name(self, origin=None):
  430. """Read the next token and interpret it as a DNS name.
  431. Raises dns.exception.SyntaxError if not a name.
  432. Returns a dns.name.Name.
  433. """
  434. token = self.get()
  435. if not token.is_identifier():
  436. raise dns.exception.SyntaxError('expecting an identifier')
  437. return dns.name.from_text(token.value, origin)
  438. def get_eol(self):
  439. """Read the next token and raise an exception if it isn't EOL or
  440. EOF.
  441. Returns a string.
  442. """
  443. token = self.get()
  444. if not token.is_eol_or_eof():
  445. raise dns.exception.SyntaxError(
  446. 'expected EOL or EOF, got %d "%s"' % (token.ttype,
  447. token.value))
  448. return token.value
  449. def get_ttl(self):
  450. """Read the next token and interpret it as a DNS TTL.
  451. Raises dns.exception.SyntaxError or dns.ttl.BadTTL if not an
  452. identifier or badly formed.
  453. Returns an int.
  454. """
  455. token = self.get().unescape()
  456. if not token.is_identifier():
  457. raise dns.exception.SyntaxError('expecting an identifier')
  458. return dns.ttl.from_text(token.value)