rdataset.py 15 KB

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