zonefile.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2007, 2009-2011 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. """DNS Zones."""
  17. import re
  18. import sys
  19. from typing import Any, Iterable, List, Optional, Set, Tuple, Union
  20. import dns.exception
  21. import dns.grange
  22. import dns.name
  23. import dns.node
  24. import dns.rdata
  25. import dns.rdataclass
  26. import dns.rdatatype
  27. import dns.rdtypes.ANY.SOA
  28. import dns.rrset
  29. import dns.tokenizer
  30. import dns.transaction
  31. import dns.ttl
  32. class UnknownOrigin(dns.exception.DNSException):
  33. """Unknown origin"""
  34. class CNAMEAndOtherData(dns.exception.DNSException):
  35. """A node has a CNAME and other data"""
  36. def _check_cname_and_other_data(txn, name, rdataset):
  37. rdataset_kind = dns.node.NodeKind.classify_rdataset(rdataset)
  38. node = txn.get_node(name)
  39. if node is None:
  40. # empty nodes are neutral.
  41. return
  42. node_kind = node.classify()
  43. if (
  44. node_kind == dns.node.NodeKind.CNAME
  45. and rdataset_kind == dns.node.NodeKind.REGULAR
  46. ):
  47. raise CNAMEAndOtherData("rdataset type is not compatible with a CNAME node")
  48. elif (
  49. node_kind == dns.node.NodeKind.REGULAR
  50. and rdataset_kind == dns.node.NodeKind.CNAME
  51. ):
  52. raise CNAMEAndOtherData(
  53. "CNAME rdataset is not compatible with a regular data node"
  54. )
  55. # Otherwise at least one of the node and the rdataset is neutral, so
  56. # adding the rdataset is ok
  57. SavedStateType = Tuple[
  58. dns.tokenizer.Tokenizer,
  59. Optional[dns.name.Name], # current_origin
  60. Optional[dns.name.Name], # last_name
  61. Optional[Any], # current_file
  62. int, # last_ttl
  63. bool, # last_ttl_known
  64. int, # default_ttl
  65. bool,
  66. ] # default_ttl_known
  67. def _upper_dollarize(s):
  68. s = s.upper()
  69. if not s.startswith("$"):
  70. s = "$" + s
  71. return s
  72. class Reader:
  73. """Read a DNS zone file into a transaction."""
  74. def __init__(
  75. self,
  76. tok: dns.tokenizer.Tokenizer,
  77. rdclass: dns.rdataclass.RdataClass,
  78. txn: dns.transaction.Transaction,
  79. allow_include: bool = False,
  80. allow_directives: Union[bool, Iterable[str]] = True,
  81. force_name: Optional[dns.name.Name] = None,
  82. force_ttl: Optional[int] = None,
  83. force_rdclass: Optional[dns.rdataclass.RdataClass] = None,
  84. force_rdtype: Optional[dns.rdatatype.RdataType] = None,
  85. default_ttl: Optional[int] = None,
  86. ):
  87. self.tok = tok
  88. (self.zone_origin, self.relativize, _) = txn.manager.origin_information()
  89. self.current_origin = self.zone_origin
  90. self.last_ttl = 0
  91. self.last_ttl_known = False
  92. if force_ttl is not None:
  93. default_ttl = force_ttl
  94. if default_ttl is None:
  95. self.default_ttl = 0
  96. self.default_ttl_known = False
  97. else:
  98. self.default_ttl = default_ttl
  99. self.default_ttl_known = True
  100. self.last_name = self.current_origin
  101. self.zone_rdclass = rdclass
  102. self.txn = txn
  103. self.saved_state: List[SavedStateType] = []
  104. self.current_file: Optional[Any] = None
  105. self.allowed_directives: Set[str]
  106. if allow_directives is True:
  107. self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"}
  108. if allow_include:
  109. self.allowed_directives.add("$INCLUDE")
  110. elif allow_directives is False:
  111. # allow_include was ignored in earlier releases if allow_directives was
  112. # False, so we continue that.
  113. self.allowed_directives = set()
  114. else:
  115. # Note that if directives are explicitly specified, then allow_include
  116. # is ignored.
  117. self.allowed_directives = set(_upper_dollarize(d) for d in allow_directives)
  118. self.force_name = force_name
  119. self.force_ttl = force_ttl
  120. self.force_rdclass = force_rdclass
  121. self.force_rdtype = force_rdtype
  122. self.txn.check_put_rdataset(_check_cname_and_other_data)
  123. def _eat_line(self):
  124. while 1:
  125. token = self.tok.get()
  126. if token.is_eol_or_eof():
  127. break
  128. def _get_identifier(self):
  129. token = self.tok.get()
  130. if not token.is_identifier():
  131. raise dns.exception.SyntaxError
  132. return token
  133. def _rr_line(self):
  134. """Process one line from a DNS zone file."""
  135. token = None
  136. # Name
  137. if self.force_name is not None:
  138. name = self.force_name
  139. else:
  140. if self.current_origin is None:
  141. raise UnknownOrigin
  142. token = self.tok.get(want_leading=True)
  143. if not token.is_whitespace():
  144. self.last_name = self.tok.as_name(token, self.current_origin)
  145. else:
  146. token = self.tok.get()
  147. if token.is_eol_or_eof():
  148. # treat leading WS followed by EOL/EOF as if they were EOL/EOF.
  149. return
  150. self.tok.unget(token)
  151. name = self.last_name
  152. if not name.is_subdomain(self.zone_origin):
  153. self._eat_line()
  154. return
  155. if self.relativize:
  156. name = name.relativize(self.zone_origin)
  157. # TTL
  158. if self.force_ttl is not None:
  159. ttl = self.force_ttl
  160. self.last_ttl = ttl
  161. self.last_ttl_known = True
  162. else:
  163. token = self._get_identifier()
  164. ttl = None
  165. try:
  166. ttl = dns.ttl.from_text(token.value)
  167. self.last_ttl = ttl
  168. self.last_ttl_known = True
  169. token = None
  170. except dns.ttl.BadTTL:
  171. self.tok.unget(token)
  172. # Class
  173. if self.force_rdclass is not None:
  174. rdclass = self.force_rdclass
  175. else:
  176. token = self._get_identifier()
  177. try:
  178. rdclass = dns.rdataclass.from_text(token.value)
  179. except dns.exception.SyntaxError:
  180. raise
  181. except Exception:
  182. rdclass = self.zone_rdclass
  183. self.tok.unget(token)
  184. if rdclass != self.zone_rdclass:
  185. raise dns.exception.SyntaxError("RR class is not zone's class")
  186. if ttl is None:
  187. # support for <class> <ttl> <type> syntax
  188. token = self._get_identifier()
  189. ttl = None
  190. try:
  191. ttl = dns.ttl.from_text(token.value)
  192. self.last_ttl = ttl
  193. self.last_ttl_known = True
  194. token = None
  195. except dns.ttl.BadTTL:
  196. if self.default_ttl_known:
  197. ttl = self.default_ttl
  198. elif self.last_ttl_known:
  199. ttl = self.last_ttl
  200. self.tok.unget(token)
  201. # Type
  202. if self.force_rdtype is not None:
  203. rdtype = self.force_rdtype
  204. else:
  205. token = self._get_identifier()
  206. try:
  207. rdtype = dns.rdatatype.from_text(token.value)
  208. except Exception:
  209. raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'")
  210. try:
  211. rd = dns.rdata.from_text(
  212. rdclass,
  213. rdtype,
  214. self.tok,
  215. self.current_origin,
  216. self.relativize,
  217. self.zone_origin,
  218. )
  219. except dns.exception.SyntaxError:
  220. # Catch and reraise.
  221. raise
  222. except Exception:
  223. # All exceptions that occur in the processing of rdata
  224. # are treated as syntax errors. This is not strictly
  225. # correct, but it is correct almost all of the time.
  226. # We convert them to syntax errors so that we can emit
  227. # helpful filename:line info.
  228. (ty, va) = sys.exc_info()[:2]
  229. raise dns.exception.SyntaxError(f"caught exception {str(ty)}: {str(va)}")
  230. if not self.default_ttl_known and rdtype == dns.rdatatype.SOA:
  231. # The pre-RFC2308 and pre-BIND9 behavior inherits the zone default
  232. # TTL from the SOA minttl if no $TTL statement is present before the
  233. # SOA is parsed.
  234. self.default_ttl = rd.minimum
  235. self.default_ttl_known = True
  236. if ttl is None:
  237. # if we didn't have a TTL on the SOA, set it!
  238. ttl = rd.minimum
  239. # TTL check. We had to wait until now to do this as the SOA RR's
  240. # own TTL can be inferred from its minimum.
  241. if ttl is None:
  242. raise dns.exception.SyntaxError("Missing default TTL value")
  243. self.txn.add(name, ttl, rd)
  244. def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]:
  245. # Here we catch everything in '{' '}' in a group so we can replace it
  246. # with ''.
  247. is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$")
  248. is_generate2 = re.compile(r"^.*\$({(\+|-?)(\d+)}).*$")
  249. is_generate3 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+)}).*$")
  250. # Sometimes there are modifiers in the hostname. These come after
  251. # the dollar sign. They are in the form: ${offset[,width[,base]]}.
  252. # Make names
  253. mod = ""
  254. sign = "+"
  255. offset = "0"
  256. width = "0"
  257. base = "d"
  258. g1 = is_generate1.match(side)
  259. if g1:
  260. mod, sign, offset, width, base = g1.groups()
  261. if sign == "":
  262. sign = "+"
  263. else:
  264. g2 = is_generate2.match(side)
  265. if g2:
  266. mod, sign, offset = g2.groups()
  267. if sign == "":
  268. sign = "+"
  269. width = "0"
  270. base = "d"
  271. else:
  272. g3 = is_generate3.match(side)
  273. if g3:
  274. mod, sign, offset, width = g3.groups()
  275. if sign == "":
  276. sign = "+"
  277. base = "d"
  278. ioffset = int(offset)
  279. iwidth = int(width)
  280. if sign not in ["+", "-"]:
  281. raise dns.exception.SyntaxError(f"invalid offset sign {sign}")
  282. if base not in ["d", "o", "x", "X", "n", "N"]:
  283. raise dns.exception.SyntaxError(f"invalid type {base}")
  284. return mod, sign, ioffset, iwidth, base
  285. def _generate_line(self):
  286. # range lhs [ttl] [class] type rhs [ comment ]
  287. """Process one line containing the GENERATE statement from a DNS
  288. zone file."""
  289. if self.current_origin is None:
  290. raise UnknownOrigin
  291. token = self.tok.get()
  292. # Range (required)
  293. try:
  294. start, stop, step = dns.grange.from_text(token.value)
  295. token = self.tok.get()
  296. if not token.is_identifier():
  297. raise dns.exception.SyntaxError
  298. except Exception:
  299. raise dns.exception.SyntaxError
  300. # lhs (required)
  301. try:
  302. lhs = token.value
  303. token = self.tok.get()
  304. if not token.is_identifier():
  305. raise dns.exception.SyntaxError
  306. except Exception:
  307. raise dns.exception.SyntaxError
  308. # TTL
  309. try:
  310. ttl = dns.ttl.from_text(token.value)
  311. self.last_ttl = ttl
  312. self.last_ttl_known = True
  313. token = self.tok.get()
  314. if not token.is_identifier():
  315. raise dns.exception.SyntaxError
  316. except dns.ttl.BadTTL:
  317. if not (self.last_ttl_known or self.default_ttl_known):
  318. raise dns.exception.SyntaxError("Missing default TTL value")
  319. if self.default_ttl_known:
  320. ttl = self.default_ttl
  321. elif self.last_ttl_known:
  322. ttl = self.last_ttl
  323. # Class
  324. try:
  325. rdclass = dns.rdataclass.from_text(token.value)
  326. token = self.tok.get()
  327. if not token.is_identifier():
  328. raise dns.exception.SyntaxError
  329. except dns.exception.SyntaxError:
  330. raise dns.exception.SyntaxError
  331. except Exception:
  332. rdclass = self.zone_rdclass
  333. if rdclass != self.zone_rdclass:
  334. raise dns.exception.SyntaxError("RR class is not zone's class")
  335. # Type
  336. try:
  337. rdtype = dns.rdatatype.from_text(token.value)
  338. token = self.tok.get()
  339. if not token.is_identifier():
  340. raise dns.exception.SyntaxError
  341. except Exception:
  342. raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'")
  343. # rhs (required)
  344. rhs = token.value
  345. def _calculate_index(counter: int, offset_sign: str, offset: int) -> int:
  346. """Calculate the index from the counter and offset."""
  347. if offset_sign == "-":
  348. offset *= -1
  349. return counter + offset
  350. def _format_index(index: int, base: str, width: int) -> str:
  351. """Format the index with the given base, and zero-fill it
  352. to the given width."""
  353. if base in ["d", "o", "x", "X"]:
  354. return format(index, base).zfill(width)
  355. # base can only be n or N here
  356. hexa = _format_index(index, "x", width)
  357. nibbles = ".".join(hexa[::-1])[:width]
  358. if base == "N":
  359. nibbles = nibbles.upper()
  360. return nibbles
  361. lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs)
  362. rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs)
  363. for i in range(start, stop + 1, step):
  364. # +1 because bind is inclusive and python is exclusive
  365. lindex = _calculate_index(i, lsign, loffset)
  366. rindex = _calculate_index(i, rsign, roffset)
  367. lzfindex = _format_index(lindex, lbase, lwidth)
  368. rzfindex = _format_index(rindex, rbase, rwidth)
  369. name = lhs.replace(f"${lmod}", lzfindex)
  370. rdata = rhs.replace(f"${rmod}", rzfindex)
  371. self.last_name = dns.name.from_text(
  372. name, self.current_origin, self.tok.idna_codec
  373. )
  374. name = self.last_name
  375. if not name.is_subdomain(self.zone_origin):
  376. self._eat_line()
  377. return
  378. if self.relativize:
  379. name = name.relativize(self.zone_origin)
  380. try:
  381. rd = dns.rdata.from_text(
  382. rdclass,
  383. rdtype,
  384. rdata,
  385. self.current_origin,
  386. self.relativize,
  387. self.zone_origin,
  388. )
  389. except dns.exception.SyntaxError:
  390. # Catch and reraise.
  391. raise
  392. except Exception:
  393. # All exceptions that occur in the processing of rdata
  394. # are treated as syntax errors. This is not strictly
  395. # correct, but it is correct almost all of the time.
  396. # We convert them to syntax errors so that we can emit
  397. # helpful filename:line info.
  398. (ty, va) = sys.exc_info()[:2]
  399. raise dns.exception.SyntaxError(
  400. f"caught exception {str(ty)}: {str(va)}"
  401. )
  402. self.txn.add(name, ttl, rd)
  403. def read(self) -> None:
  404. """Read a DNS zone file and build a zone object.
  405. @raises dns.zone.NoSOA: No SOA RR was found at the zone origin
  406. @raises dns.zone.NoNS: No NS RRset was found at the zone origin
  407. """
  408. try:
  409. while 1:
  410. token = self.tok.get(True, True)
  411. if token.is_eof():
  412. if self.current_file is not None:
  413. self.current_file.close()
  414. if len(self.saved_state) > 0:
  415. (
  416. self.tok,
  417. self.current_origin,
  418. self.last_name,
  419. self.current_file,
  420. self.last_ttl,
  421. self.last_ttl_known,
  422. self.default_ttl,
  423. self.default_ttl_known,
  424. ) = self.saved_state.pop(-1)
  425. continue
  426. break
  427. elif token.is_eol():
  428. continue
  429. elif token.is_comment():
  430. self.tok.get_eol()
  431. continue
  432. elif token.value[0] == "$" and len(self.allowed_directives) > 0:
  433. # Note that we only run directive processing code if at least
  434. # one directive is allowed in order to be backwards compatible
  435. c = token.value.upper()
  436. if c not in self.allowed_directives:
  437. raise dns.exception.SyntaxError(
  438. f"zone file directive '{c}' is not allowed"
  439. )
  440. if c == "$TTL":
  441. token = self.tok.get()
  442. if not token.is_identifier():
  443. raise dns.exception.SyntaxError("bad $TTL")
  444. self.default_ttl = dns.ttl.from_text(token.value)
  445. self.default_ttl_known = True
  446. self.tok.get_eol()
  447. elif c == "$ORIGIN":
  448. self.current_origin = self.tok.get_name()
  449. self.tok.get_eol()
  450. if self.zone_origin is None:
  451. self.zone_origin = self.current_origin
  452. self.txn._set_origin(self.current_origin)
  453. elif c == "$INCLUDE":
  454. token = self.tok.get()
  455. filename = token.value
  456. token = self.tok.get()
  457. new_origin: Optional[dns.name.Name]
  458. if token.is_identifier():
  459. new_origin = dns.name.from_text(
  460. token.value, self.current_origin, self.tok.idna_codec
  461. )
  462. self.tok.get_eol()
  463. elif not token.is_eol_or_eof():
  464. raise dns.exception.SyntaxError("bad origin in $INCLUDE")
  465. else:
  466. new_origin = self.current_origin
  467. self.saved_state.append(
  468. (
  469. self.tok,
  470. self.current_origin,
  471. self.last_name,
  472. self.current_file,
  473. self.last_ttl,
  474. self.last_ttl_known,
  475. self.default_ttl,
  476. self.default_ttl_known,
  477. )
  478. )
  479. self.current_file = open(filename)
  480. self.tok = dns.tokenizer.Tokenizer(self.current_file, filename)
  481. self.current_origin = new_origin
  482. elif c == "$GENERATE":
  483. self._generate_line()
  484. else:
  485. raise dns.exception.SyntaxError(
  486. f"Unknown zone file directive '{c}'"
  487. )
  488. continue
  489. self.tok.unget(token)
  490. self._rr_line()
  491. except dns.exception.SyntaxError as detail:
  492. (filename, line_number) = self.tok.where()
  493. if detail is None:
  494. detail = "syntax error"
  495. ex = dns.exception.SyntaxError(
  496. "%s:%d: %s" % (filename, line_number, detail)
  497. )
  498. tb = sys.exc_info()[2]
  499. raise ex.with_traceback(tb) from None
  500. class RRsetsReaderTransaction(dns.transaction.Transaction):
  501. def __init__(self, manager, replacement, read_only):
  502. assert not read_only
  503. super().__init__(manager, replacement, read_only)
  504. self.rdatasets = {}
  505. def _get_rdataset(self, name, rdtype, covers):
  506. return self.rdatasets.get((name, rdtype, covers))
  507. def _get_node(self, name):
  508. rdatasets = []
  509. for (rdataset_name, _, _), rdataset in self.rdatasets.items():
  510. if name == rdataset_name:
  511. rdatasets.append(rdataset)
  512. if len(rdatasets) == 0:
  513. return None
  514. node = dns.node.Node()
  515. node.rdatasets = rdatasets
  516. return node
  517. def _put_rdataset(self, name, rdataset):
  518. self.rdatasets[(name, rdataset.rdtype, rdataset.covers)] = rdataset
  519. def _delete_name(self, name):
  520. # First remove any changes involving the name
  521. remove = []
  522. for key in self.rdatasets:
  523. if key[0] == name:
  524. remove.append(key)
  525. if len(remove) > 0:
  526. for key in remove:
  527. del self.rdatasets[key]
  528. def _delete_rdataset(self, name, rdtype, covers):
  529. try:
  530. del self.rdatasets[(name, rdtype, covers)]
  531. except KeyError:
  532. pass
  533. def _name_exists(self, name):
  534. for n, _, _ in self.rdatasets:
  535. if n == name:
  536. return True
  537. return False
  538. def _changed(self):
  539. return len(self.rdatasets) > 0
  540. def _end_transaction(self, commit):
  541. if commit and self._changed():
  542. rrsets = []
  543. for (name, _, _), rdataset in self.rdatasets.items():
  544. rrset = dns.rrset.RRset(
  545. name, rdataset.rdclass, rdataset.rdtype, rdataset.covers
  546. )
  547. rrset.update(rdataset)
  548. rrsets.append(rrset)
  549. self.manager.set_rrsets(rrsets)
  550. def _set_origin(self, origin):
  551. pass
  552. def _iterate_rdatasets(self):
  553. raise NotImplementedError # pragma: no cover
  554. def _iterate_names(self):
  555. raise NotImplementedError # pragma: no cover
  556. class RRSetsReaderManager(dns.transaction.TransactionManager):
  557. def __init__(
  558. self, origin=dns.name.root, relativize=False, rdclass=dns.rdataclass.IN
  559. ):
  560. self.origin = origin
  561. self.relativize = relativize
  562. self.rdclass = rdclass
  563. self.rrsets = []
  564. def reader(self): # pragma: no cover
  565. raise NotImplementedError
  566. def writer(self, replacement=False):
  567. assert replacement is True
  568. return RRsetsReaderTransaction(self, True, False)
  569. def get_class(self):
  570. return self.rdclass
  571. def origin_information(self):
  572. if self.relativize:
  573. effective = dns.name.empty
  574. else:
  575. effective = self.origin
  576. return (self.origin, self.relativize, effective)
  577. def set_rrsets(self, rrsets):
  578. self.rrsets = rrsets
  579. def read_rrsets(
  580. text: Any,
  581. name: Optional[Union[dns.name.Name, str]] = None,
  582. ttl: Optional[int] = None,
  583. rdclass: Optional[Union[dns.rdataclass.RdataClass, str]] = dns.rdataclass.IN,
  584. default_rdclass: Union[dns.rdataclass.RdataClass, str] = dns.rdataclass.IN,
  585. rdtype: Optional[Union[dns.rdatatype.RdataType, str]] = None,
  586. default_ttl: Optional[Union[int, str]] = None,
  587. idna_codec: Optional[dns.name.IDNACodec] = None,
  588. origin: Optional[Union[dns.name.Name, str]] = dns.name.root,
  589. relativize: bool = False,
  590. ) -> List[dns.rrset.RRset]:
  591. """Read one or more rrsets from the specified text, possibly subject
  592. to restrictions.
  593. *text*, a file object or a string, is the input to process.
  594. *name*, a string, ``dns.name.Name``, or ``None``, is the owner name of
  595. the rrset. If not ``None``, then the owner name is "forced", and the
  596. input must not specify an owner name. If ``None``, then any owner names
  597. are allowed and must be present in the input.
  598. *ttl*, an ``int``, string, or None. If not ``None``, the the TTL is
  599. forced to be the specified value and the input must not specify a TTL.
  600. If ``None``, then a TTL may be specified in the input. If it is not
  601. specified, then the *default_ttl* will be used.
  602. *rdclass*, a ``dns.rdataclass.RdataClass``, string, or ``None``. If
  603. not ``None``, then the class is forced to the specified value, and the
  604. input must not specify a class. If ``None``, then the input may specify
  605. a class that matches *default_rdclass*. Note that it is not possible to
  606. return rrsets with differing classes; specifying ``None`` for the class
  607. simply allows the user to optionally type a class as that may be convenient
  608. when cutting and pasting.
  609. *default_rdclass*, a ``dns.rdataclass.RdataClass`` or string. The class
  610. of the returned rrsets.
  611. *rdtype*, a ``dns.rdatatype.RdataType``, string, or ``None``. If not
  612. ``None``, then the type is forced to the specified value, and the
  613. input must not specify a type. If ``None``, then a type must be present
  614. for each RR.
  615. *default_ttl*, an ``int``, string, or ``None``. If not ``None``, then if
  616. the TTL is not forced and is not specified, then this value will be used.
  617. if ``None``, then if the TTL is not forced an error will occur if the TTL
  618. is not specified.
  619. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  620. encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
  621. is used. Note that codecs only apply to the owner name; dnspython does
  622. not do IDNA for names in rdata, as there is no IDNA zonefile format.
  623. *origin*, a string, ``dns.name.Name``, or ``None``, is the origin for any
  624. relative names in the input, and also the origin to relativize to if
  625. *relativize* is ``True``.
  626. *relativize*, a bool. If ``True``, names are relativized to the *origin*;
  627. if ``False`` then any relative names in the input are made absolute by
  628. appending the *origin*.
  629. """
  630. if isinstance(origin, str):
  631. origin = dns.name.from_text(origin, dns.name.root, idna_codec)
  632. if isinstance(name, str):
  633. name = dns.name.from_text(name, origin, idna_codec)
  634. if isinstance(ttl, str):
  635. ttl = dns.ttl.from_text(ttl)
  636. if isinstance(default_ttl, str):
  637. default_ttl = dns.ttl.from_text(default_ttl)
  638. if rdclass is not None:
  639. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  640. else:
  641. rdclass = None
  642. default_rdclass = dns.rdataclass.RdataClass.make(default_rdclass)
  643. if rdtype is not None:
  644. rdtype = dns.rdatatype.RdataType.make(rdtype)
  645. else:
  646. rdtype = None
  647. manager = RRSetsReaderManager(origin, relativize, default_rdclass)
  648. with manager.writer(True) as txn:
  649. tok = dns.tokenizer.Tokenizer(text, "<input>", idna_codec=idna_codec)
  650. reader = Reader(
  651. tok,
  652. default_rdclass,
  653. txn,
  654. allow_directives=False,
  655. force_name=name,
  656. force_ttl=ttl,
  657. force_rdclass=rdclass,
  658. force_rdtype=rdtype,
  659. default_ttl=default_ttl,
  660. )
  661. reader.read()
  662. return manager.rrsets