You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

347 lines
11 KiB

4 years ago
  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 random
  18. from io import StringIO
  19. import struct
  20. import dns.exception
  21. import dns.rdatatype
  22. import dns.rdataclass
  23. import dns.rdata
  24. import dns.set
  25. from ._compat import string_types
  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(Rdataset, self).__init__()
  44. self.rdclass = rdclass
  45. self.rdtype = rdtype
  46. self.covers = covers
  47. self.ttl = ttl
  48. def _clone(self):
  49. obj = super(Rdataset, self)._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``.
  61. """
  62. if len(self) == 0:
  63. self.ttl = ttl
  64. elif ttl < self.ttl:
  65. self.ttl = ttl
  66. def add(self, rd, ttl=None):
  67. """Add the specified rdata to the rdataset.
  68. If the optional *ttl* parameter is supplied, then
  69. ``self.update_ttl(ttl)`` will be called prior to adding the rdata.
  70. *rd*, a ``dns.rdata.Rdata``, the rdata
  71. *ttl*, an ``int``, the TTL.
  72. Raises ``dns.rdataset.IncompatibleTypes`` if the type and class
  73. do not match the type and class of the rdataset.
  74. Raises ``dns.rdataset.DifferingCovers`` if the type is a signature
  75. type and the covered type does not match that of the rdataset.
  76. """
  77. #
  78. # If we're adding a signature, do some special handling to
  79. # check that the signature covers the same type as the
  80. # other rdatas in this rdataset. If this is the first rdata
  81. # in the set, initialize the covers field.
  82. #
  83. if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
  84. raise IncompatibleTypes
  85. if ttl is not None:
  86. self.update_ttl(ttl)
  87. if self.rdtype == dns.rdatatype.RRSIG or \
  88. self.rdtype == dns.rdatatype.SIG:
  89. covers = rd.covers()
  90. if len(self) == 0 and self.covers == dns.rdatatype.NONE:
  91. self.covers = covers
  92. elif self.covers != covers:
  93. raise DifferingCovers
  94. if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
  95. self.clear()
  96. super(Rdataset, self).add(rd)
  97. def union_update(self, other):
  98. self.update_ttl(other.ttl)
  99. super(Rdataset, self).union_update(other)
  100. def intersection_update(self, other):
  101. self.update_ttl(other.ttl)
  102. super(Rdataset, self).intersection_update(other)
  103. def update(self, other):
  104. """Add all rdatas in other to self.
  105. *other*, a ``dns.rdataset.Rdataset``, the rdataset from which
  106. to update.
  107. """
  108. self.update_ttl(other.ttl)
  109. super(Rdataset, self).update(other)
  110. def __repr__(self):
  111. if self.covers == 0:
  112. ctext = ''
  113. else:
  114. ctext = '(' + dns.rdatatype.to_text(self.covers) + ')'
  115. return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \
  116. dns.rdatatype.to_text(self.rdtype) + ctext + ' rdataset>'
  117. def __str__(self):
  118. return self.to_text()
  119. def __eq__(self, other):
  120. if not isinstance(other, Rdataset):
  121. return False
  122. if self.rdclass != other.rdclass or \
  123. self.rdtype != other.rdtype or \
  124. self.covers != other.covers:
  125. return False
  126. return super(Rdataset, self).__eq__(other)
  127. def __ne__(self, other):
  128. return not self.__eq__(other)
  129. def to_text(self, name=None, origin=None, relativize=True,
  130. override_rdclass=None, **kw):
  131. """Convert the rdataset into DNS master file format.
  132. See ``dns.name.Name.choose_relativity`` for more information
  133. on how *origin* and *relativize* determine the way names
  134. are emitted.
  135. Any additional keyword arguments are passed on to the rdata
  136. ``to_text()`` method.
  137. *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with
  138. *name* as the owner name.
  139. *origin*, a ``dns.name.Name`` or ``None``, the origin for relative
  140. names.
  141. *relativize*, a ``bool``. If ``True``, names will be relativized
  142. to *origin*.
  143. """
  144. if name is not None:
  145. name = name.choose_relativity(origin, relativize)
  146. ntext = str(name)
  147. pad = ' '
  148. else:
  149. ntext = ''
  150. pad = ''
  151. s = StringIO()
  152. if override_rdclass is not None:
  153. rdclass = override_rdclass
  154. else:
  155. rdclass = self.rdclass
  156. if len(self) == 0:
  157. #
  158. # Empty rdatasets are used for the question section, and in
  159. # some dynamic updates, so we don't need to print out the TTL
  160. # (which is meaningless anyway).
  161. #
  162. s.write(u'{}{}{} {}\n'.format(ntext, pad,
  163. dns.rdataclass.to_text(rdclass),
  164. dns.rdatatype.to_text(self.rdtype)))
  165. else:
  166. for rd in self:
  167. s.write(u'%s%s%d %s %s %s\n' %
  168. (ntext, pad, self.ttl, dns.rdataclass.to_text(rdclass),
  169. dns.rdatatype.to_text(self.rdtype),
  170. rd.to_text(origin=origin, relativize=relativize,
  171. **kw)))
  172. #
  173. # We strip off the final \n for the caller's convenience in printing
  174. #
  175. return s.getvalue()[:-1]
  176. def to_wire(self, name, file, compress=None, origin=None,
  177. override_rdclass=None, want_shuffle=True):
  178. """Convert the rdataset to wire format.
  179. *name*, a ``dns.name.Name`` is the owner name to use.
  180. *file* is the file where the name is emitted (typically a
  181. BytesIO file).
  182. *compress*, a ``dict``, is the compression table to use. If
  183. ``None`` (the default), names will not be compressed.
  184. *origin* is a ``dns.name.Name`` or ``None``. If the name is
  185. relative and origin is not ``None``, then *origin* will be appended
  186. to it.
  187. *override_rdclass*, an ``int``, is used as the class instead of the
  188. class of the rdataset. This is useful when rendering rdatasets
  189. associated with dynamic updates.
  190. *want_shuffle*, a ``bool``. If ``True``, then the order of the
  191. Rdatas within the Rdataset will be shuffled before rendering.
  192. Returns an ``int``, the number of records emitted.
  193. """
  194. if override_rdclass is not None:
  195. rdclass = override_rdclass
  196. want_shuffle = False
  197. else:
  198. rdclass = self.rdclass
  199. file.seek(0, 2)
  200. if len(self) == 0:
  201. name.to_wire(file, compress, origin)
  202. stuff = struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)
  203. file.write(stuff)
  204. return 1
  205. else:
  206. if want_shuffle:
  207. l = list(self)
  208. random.shuffle(l)
  209. else:
  210. l = self
  211. for rd in l:
  212. name.to_wire(file, compress, origin)
  213. stuff = struct.pack("!HHIH", self.rdtype, rdclass,
  214. self.ttl, 0)
  215. file.write(stuff)
  216. start = file.tell()
  217. rd.to_wire(file, compress, origin)
  218. end = file.tell()
  219. assert end - start < 65536
  220. file.seek(start - 2)
  221. stuff = struct.pack("!H", end - start)
  222. file.write(stuff)
  223. file.seek(0, 2)
  224. return len(self)
  225. def match(self, rdclass, rdtype, covers):
  226. """Returns ``True`` if this rdataset matches the specified class,
  227. type, and covers.
  228. """
  229. if self.rdclass == rdclass and \
  230. self.rdtype == rdtype and \
  231. self.covers == covers:
  232. return True
  233. return False
  234. def from_text_list(rdclass, rdtype, ttl, text_rdatas):
  235. """Create an rdataset with the specified class, type, and TTL, and with
  236. the specified list of rdatas in text format.
  237. Returns a ``dns.rdataset.Rdataset`` object.
  238. """
  239. if isinstance(rdclass, string_types):
  240. rdclass = dns.rdataclass.from_text(rdclass)
  241. if isinstance(rdtype, string_types):
  242. rdtype = dns.rdatatype.from_text(rdtype)
  243. r = Rdataset(rdclass, rdtype)
  244. r.update_ttl(ttl)
  245. for t in text_rdatas:
  246. rd = dns.rdata.from_text(r.rdclass, r.rdtype, t)
  247. r.add(rd)
  248. return r
  249. def from_text(rdclass, rdtype, ttl, *text_rdatas):
  250. """Create an rdataset with the specified class, type, and TTL, and with
  251. the specified rdatas in text format.
  252. Returns a ``dns.rdataset.Rdataset`` object.
  253. """
  254. return from_text_list(rdclass, rdtype, ttl, text_rdatas)
  255. def from_rdata_list(ttl, rdatas):
  256. """Create an rdataset with the specified TTL, and with
  257. the specified list of rdata objects.
  258. Returns a ``dns.rdataset.Rdataset`` object.
  259. """
  260. if len(rdatas) == 0:
  261. raise ValueError("rdata list must not be empty")
  262. r = None
  263. for rd in rdatas:
  264. if r is None:
  265. r = Rdataset(rd.rdclass, rd.rdtype)
  266. r.update_ttl(ttl)
  267. r.add(rd)
  268. return r
  269. def from_rdata(ttl, *rdatas):
  270. """Create an rdataset with the specified TTL, and with
  271. the specified rdata objects.
  272. Returns a ``dns.rdataset.Rdataset`` object.
  273. """
  274. return from_rdata_list(ttl, rdatas)