rdataset.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2001-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. """DNS rdatasets (an rdataset is a set of rdatas of a given type and class)"""
  17. import io
  18. import random
  19. import struct
  20. from typing import Any, Collection, Dict, List, cast
  21. import dns.exception
  22. import dns.immutable
  23. import dns.name
  24. import dns.rdata
  25. import dns.rdataclass
  26. import dns.rdatatype
  27. import dns.renderer
  28. import dns.set
  29. import dns.ttl
  30. # define SimpleSet here for backwards compatibility
  31. SimpleSet = dns.set.Set
  32. class DifferingCovers(dns.exception.DNSException):
  33. """An attempt was made to add a DNS SIG/RRSIG whose covered type
  34. is not the same as that of the other rdatas in the rdataset."""
  35. class IncompatibleTypes(dns.exception.DNSException):
  36. """An attempt was made to add DNS RR data of an incompatible type."""
  37. class Rdataset(dns.set.Set):
  38. """A DNS rdataset."""
  39. __slots__ = ["rdclass", "rdtype", "covers", "ttl"]
  40. def __init__(
  41. self,
  42. rdclass: dns.rdataclass.RdataClass,
  43. rdtype: dns.rdatatype.RdataType,
  44. covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
  45. ttl: int = 0,
  46. ):
  47. """Create a new rdataset of the specified class and type.
  48. *rdclass*, a ``dns.rdataclass.RdataClass``, the rdataclass.
  49. *rdtype*, an ``dns.rdatatype.RdataType``, the rdatatype.
  50. *covers*, an ``dns.rdatatype.RdataType``, the covered rdatatype.
  51. *ttl*, an ``int``, the TTL.
  52. """
  53. super().__init__()
  54. self.rdclass = rdclass
  55. self.rdtype: dns.rdatatype.RdataType = rdtype
  56. self.covers: dns.rdatatype.RdataType = covers
  57. self.ttl = ttl
  58. def _clone(self):
  59. obj = cast(Rdataset, super()._clone())
  60. obj.rdclass = self.rdclass
  61. obj.rdtype = self.rdtype
  62. obj.covers = self.covers
  63. obj.ttl = self.ttl
  64. return obj
  65. def update_ttl(self, ttl: int) -> None:
  66. """Perform TTL minimization.
  67. Set the TTL of the rdataset to be the lesser of the set's current
  68. TTL or the specified TTL. If the set contains no rdatas, set the TTL
  69. to the specified TTL.
  70. *ttl*, an ``int`` or ``str``.
  71. """
  72. ttl = dns.ttl.make(ttl)
  73. if len(self) == 0:
  74. self.ttl = ttl
  75. elif ttl < self.ttl:
  76. self.ttl = ttl
  77. # pylint: disable=arguments-differ,arguments-renamed
  78. def add( # pyright: ignore
  79. self, rd: dns.rdata.Rdata, ttl: int | None = None
  80. ) -> None:
  81. """Add the specified rdata to the rdataset.
  82. If the optional *ttl* parameter is supplied, then
  83. ``self.update_ttl(ttl)`` will be called prior to adding the rdata.
  84. *rd*, a ``dns.rdata.Rdata``, the rdata
  85. *ttl*, an ``int``, the TTL.
  86. Raises ``dns.rdataset.IncompatibleTypes`` if the type and class
  87. do not match the type and class of the rdataset.
  88. Raises ``dns.rdataset.DifferingCovers`` if the type is a signature
  89. type and the covered type does not match that of the rdataset.
  90. """
  91. #
  92. # If we're adding a signature, do some special handling to
  93. # check that the signature covers the same type as the
  94. # other rdatas in this rdataset. If this is the first rdata
  95. # in the set, initialize the covers field.
  96. #
  97. if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
  98. raise IncompatibleTypes
  99. if ttl is not None:
  100. self.update_ttl(ttl)
  101. if self.rdtype == dns.rdatatype.RRSIG or self.rdtype == dns.rdatatype.SIG:
  102. covers = rd.covers()
  103. if len(self) == 0 and self.covers == dns.rdatatype.NONE:
  104. self.covers = covers
  105. elif self.covers != covers:
  106. raise DifferingCovers
  107. if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
  108. self.clear()
  109. super().add(rd)
  110. def union_update(self, other):
  111. self.update_ttl(other.ttl)
  112. super().union_update(other)
  113. def intersection_update(self, other):
  114. self.update_ttl(other.ttl)
  115. super().intersection_update(other)
  116. def update(self, other):
  117. """Add all rdatas in other to self.
  118. *other*, a ``dns.rdataset.Rdataset``, the rdataset from which
  119. to update.
  120. """
  121. self.update_ttl(other.ttl)
  122. super().update(other)
  123. def _rdata_repr(self):
  124. def maybe_truncate(s):
  125. if len(s) > 100:
  126. return s[:100] + "..."
  127. return s
  128. return "[" + ", ".join(f"<{maybe_truncate(str(rr))}>" for rr in self) + "]"
  129. def __repr__(self):
  130. if self.covers == 0:
  131. ctext = ""
  132. else:
  133. ctext = "(" + dns.rdatatype.to_text(self.covers) + ")"
  134. return (
  135. "<DNS "
  136. + dns.rdataclass.to_text(self.rdclass)
  137. + " "
  138. + dns.rdatatype.to_text(self.rdtype)
  139. + ctext
  140. + " rdataset: "
  141. + self._rdata_repr()
  142. + ">"
  143. )
  144. def __str__(self):
  145. return self.to_text()
  146. def __eq__(self, other):
  147. if not isinstance(other, Rdataset):
  148. return False
  149. if (
  150. self.rdclass != other.rdclass
  151. or self.rdtype != other.rdtype
  152. or self.covers != other.covers
  153. ):
  154. return False
  155. return super().__eq__(other)
  156. def __ne__(self, other):
  157. return not self.__eq__(other)
  158. def to_text(
  159. self,
  160. name: dns.name.Name | None = None,
  161. origin: dns.name.Name | None = None,
  162. relativize: bool = True,
  163. override_rdclass: dns.rdataclass.RdataClass | None = None,
  164. want_comments: bool = False,
  165. **kw: Dict[str, Any],
  166. ) -> str:
  167. """Convert the rdataset into DNS zone file format.
  168. See ``dns.name.Name.choose_relativity`` for more information
  169. on how *origin* and *relativize* determine the way names
  170. are emitted.
  171. Any additional keyword arguments are passed on to the rdata
  172. ``to_text()`` method.
  173. *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with
  174. *name* as the owner name.
  175. *origin*, a ``dns.name.Name`` or ``None``, the origin for relative
  176. names.
  177. *relativize*, a ``bool``. If ``True``, names will be relativized
  178. to *origin*.
  179. *override_rdclass*, a ``dns.rdataclass.RdataClass`` or ``None``.
  180. If not ``None``, use this class instead of the Rdataset's class.
  181. *want_comments*, a ``bool``. If ``True``, emit comments for rdata
  182. which have them. The default is ``False``.
  183. """
  184. if name is not None:
  185. name = name.choose_relativity(origin, relativize)
  186. ntext = str(name)
  187. pad = " "
  188. else:
  189. ntext = ""
  190. pad = ""
  191. s = io.StringIO()
  192. if override_rdclass is not None:
  193. rdclass = override_rdclass
  194. else:
  195. rdclass = self.rdclass
  196. if len(self) == 0:
  197. #
  198. # Empty rdatasets are used for the question section, and in
  199. # some dynamic updates, so we don't need to print out the TTL
  200. # (which is meaningless anyway).
  201. #
  202. s.write(
  203. f"{ntext}{pad}{dns.rdataclass.to_text(rdclass)} "
  204. f"{dns.rdatatype.to_text(self.rdtype)}\n"
  205. )
  206. else:
  207. for rd in self:
  208. extra = ""
  209. if want_comments:
  210. if rd.rdcomment:
  211. extra = f" ;{rd.rdcomment}"
  212. s.write(
  213. f"{ntext}{pad}{self.ttl} "
  214. f"{dns.rdataclass.to_text(rdclass)} "
  215. f"{dns.rdatatype.to_text(self.rdtype)} "
  216. f"{rd.to_text(origin=origin, relativize=relativize, **kw)}"
  217. f"{extra}\n"
  218. )
  219. #
  220. # We strip off the final \n for the caller's convenience in printing
  221. #
  222. return s.getvalue()[:-1]
  223. def to_wire(
  224. self,
  225. name: dns.name.Name,
  226. file: Any,
  227. compress: dns.name.CompressType | None = None,
  228. origin: dns.name.Name | None = None,
  229. override_rdclass: dns.rdataclass.RdataClass | None = None,
  230. want_shuffle: bool = True,
  231. ) -> int:
  232. """Convert the rdataset to wire format.
  233. *name*, a ``dns.name.Name`` is the owner name to use.
  234. *file* is the file where the name is emitted (typically a
  235. BytesIO file).
  236. *compress*, a ``dict``, is the compression table to use. If
  237. ``None`` (the default), names will not be compressed.
  238. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  239. relative and origin is not ``None``, then *origin* will be appended
  240. to it.
  241. *override_rdclass*, an ``int``, is used as the class instead of the
  242. class of the rdataset. This is useful when rendering rdatasets
  243. associated with dynamic updates.
  244. *want_shuffle*, a ``bool``. If ``True``, then the order of the
  245. Rdatas within the Rdataset will be shuffled before rendering.
  246. Returns an ``int``, the number of records emitted.
  247. """
  248. if override_rdclass is not None:
  249. rdclass = override_rdclass
  250. want_shuffle = False
  251. else:
  252. rdclass = self.rdclass
  253. if len(self) == 0:
  254. name.to_wire(file, compress, origin)
  255. file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0))
  256. return 1
  257. else:
  258. l: Rdataset | List[dns.rdata.Rdata]
  259. if want_shuffle:
  260. l = list(self)
  261. random.shuffle(l)
  262. else:
  263. l = self
  264. for rd in l:
  265. name.to_wire(file, compress, origin)
  266. file.write(struct.pack("!HHI", self.rdtype, rdclass, self.ttl))
  267. with dns.renderer.prefixed_length(file, 2):
  268. rd.to_wire(file, compress, origin)
  269. return len(self)
  270. def match(
  271. self,
  272. rdclass: dns.rdataclass.RdataClass,
  273. rdtype: dns.rdatatype.RdataType,
  274. covers: dns.rdatatype.RdataType,
  275. ) -> bool:
  276. """Returns ``True`` if this rdataset matches the specified class,
  277. type, and covers.
  278. """
  279. if self.rdclass == rdclass and self.rdtype == rdtype and self.covers == covers:
  280. return True
  281. return False
  282. def processing_order(self) -> List[dns.rdata.Rdata]:
  283. """Return rdatas in a valid processing order according to the type's
  284. specification. For example, MX records are in preference order from
  285. lowest to highest preferences, with items of the same preference
  286. shuffled.
  287. For types that do not define a processing order, the rdatas are
  288. simply shuffled.
  289. """
  290. if len(self) == 0:
  291. return []
  292. else:
  293. return self[0]._processing_order(iter(self)) # pyright: ignore
  294. @dns.immutable.immutable
  295. class ImmutableRdataset(Rdataset): # lgtm[py/missing-equals]
  296. """An immutable DNS rdataset."""
  297. _clone_class = Rdataset
  298. def __init__(self, rdataset: Rdataset):
  299. """Create an immutable rdataset from the specified rdataset."""
  300. super().__init__(
  301. rdataset.rdclass, rdataset.rdtype, rdataset.covers, rdataset.ttl
  302. )
  303. self.items = dns.immutable.Dict(rdataset.items)
  304. def update_ttl(self, ttl):
  305. raise TypeError("immutable")
  306. def add(self, rd, ttl=None):
  307. raise TypeError("immutable")
  308. def union_update(self, other):
  309. raise TypeError("immutable")
  310. def intersection_update(self, other):
  311. raise TypeError("immutable")
  312. def update(self, other):
  313. raise TypeError("immutable")
  314. def __delitem__(self, i):
  315. raise TypeError("immutable")
  316. # lgtm complains about these not raising ArithmeticError, but there is
  317. # precedent for overrides of these methods in other classes to raise
  318. # TypeError, and it seems like the better exception.
  319. def __ior__(self, other): # lgtm[py/unexpected-raise-in-special-method]
  320. raise TypeError("immutable")
  321. def __iand__(self, other): # lgtm[py/unexpected-raise-in-special-method]
  322. raise TypeError("immutable")
  323. def __iadd__(self, other): # lgtm[py/unexpected-raise-in-special-method]
  324. raise TypeError("immutable")
  325. def __isub__(self, other): # lgtm[py/unexpected-raise-in-special-method]
  326. raise TypeError("immutable")
  327. def clear(self):
  328. raise TypeError("immutable")
  329. def __copy__(self):
  330. return ImmutableRdataset(super().copy()) # pyright: ignore
  331. def copy(self):
  332. return ImmutableRdataset(super().copy()) # pyright: ignore
  333. def union(self, other):
  334. return ImmutableRdataset(super().union(other)) # pyright: ignore
  335. def intersection(self, other):
  336. return ImmutableRdataset(super().intersection(other)) # pyright: ignore
  337. def difference(self, other):
  338. return ImmutableRdataset(super().difference(other)) # pyright: ignore
  339. def symmetric_difference(self, other):
  340. return ImmutableRdataset(super().symmetric_difference(other)) # pyright: ignore
  341. def from_text_list(
  342. rdclass: dns.rdataclass.RdataClass | str,
  343. rdtype: dns.rdatatype.RdataType | str,
  344. ttl: int,
  345. text_rdatas: Collection[str],
  346. idna_codec: dns.name.IDNACodec | None = None,
  347. origin: dns.name.Name | None = None,
  348. relativize: bool = True,
  349. relativize_to: dns.name.Name | None = None,
  350. ) -> Rdataset:
  351. """Create an rdataset with the specified class, type, and TTL, and with
  352. the specified list of rdatas in text format.
  353. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  354. encoder/decoder to use; if ``None``, the default IDNA 2003
  355. encoder/decoder is used.
  356. *origin*, a ``dns.name.Name`` (or ``None``), the
  357. origin to use for relative names.
  358. *relativize*, a ``bool``. If true, name will be relativized.
  359. *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
  360. when relativizing names. If not set, the *origin* value will be used.
  361. Returns a ``dns.rdataset.Rdataset`` object.
  362. """
  363. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  364. rdtype = dns.rdatatype.RdataType.make(rdtype)
  365. r = Rdataset(rdclass, rdtype)
  366. r.update_ttl(ttl)
  367. for t in text_rdatas:
  368. rd = dns.rdata.from_text(
  369. r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec
  370. )
  371. r.add(rd)
  372. return r
  373. def from_text(
  374. rdclass: dns.rdataclass.RdataClass | str,
  375. rdtype: dns.rdatatype.RdataType | str,
  376. ttl: int,
  377. *text_rdatas: Any,
  378. ) -> Rdataset:
  379. """Create an rdataset with the specified class, type, and TTL, and with
  380. the specified rdatas in text format.
  381. Returns a ``dns.rdataset.Rdataset`` object.
  382. """
  383. return from_text_list(rdclass, rdtype, ttl, cast(Collection[str], text_rdatas))
  384. def from_rdata_list(ttl: int, rdatas: Collection[dns.rdata.Rdata]) -> Rdataset:
  385. """Create an rdataset with the specified TTL, and with
  386. the specified list of rdata objects.
  387. Returns a ``dns.rdataset.Rdataset`` object.
  388. """
  389. if len(rdatas) == 0:
  390. raise ValueError("rdata list must not be empty")
  391. r = None
  392. for rd in rdatas:
  393. if r is None:
  394. r = Rdataset(rd.rdclass, rd.rdtype)
  395. r.update_ttl(ttl)
  396. r.add(rd)
  397. assert r is not None
  398. return r
  399. def from_rdata(ttl: int, *rdatas: Any) -> Rdataset:
  400. """Create an rdataset with the specified TTL, and with
  401. the specified rdata objects.
  402. Returns a ``dns.rdataset.Rdataset`` object.
  403. """
  404. return from_rdata_list(ttl, cast(Collection[dns.rdata.Rdata], rdatas))