zonefile.py 28 KB

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