rdataset.py 16 KB

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