rdataset.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # Copyright (C) 2001-2007, 2009-2011 Nominum, Inc.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose with or without fee is hereby granted,
  5. # provided that the above copyright notice and this permission notice
  6. # appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  11. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  14. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """DNS rdatasets (an rdataset is a set of rdatas of a given type and class)"""
  16. import random
  17. from io import StringIO
  18. import struct
  19. import dns.exception
  20. import dns.rdatatype
  21. import dns.rdataclass
  22. import dns.rdata
  23. import dns.set
  24. from ._compat import string_types
  25. # define SimpleSet here for backwards compatibility
  26. SimpleSet = dns.set.Set
  27. class DifferingCovers(dns.exception.DNSException):
  28. """An attempt was made to add a DNS SIG/RRSIG whose covered type
  29. is not the same as that of the other rdatas in the rdataset."""
  30. class IncompatibleTypes(dns.exception.DNSException):
  31. """An attempt was made to add DNS RR data of an incompatible type."""
  32. class Rdataset(dns.set.Set):
  33. """A DNS rdataset.
  34. @ivar rdclass: The class of the rdataset
  35. @type rdclass: int
  36. @ivar rdtype: The type of the rdataset
  37. @type rdtype: int
  38. @ivar covers: The covered type. Usually this value is
  39. dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or
  40. dns.rdatatype.RRSIG, then the covers value will be the rdata
  41. type the SIG/RRSIG covers. The library treats the SIG and RRSIG
  42. types as if they were a family of
  43. types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much
  44. easier to work with than if RRSIGs covering different rdata
  45. types were aggregated into a single RRSIG rdataset.
  46. @type covers: int
  47. @ivar ttl: The DNS TTL (Time To Live) value
  48. @type ttl: int
  49. """
  50. __slots__ = ['rdclass', 'rdtype', 'covers', 'ttl']
  51. def __init__(self, rdclass, rdtype, covers=dns.rdatatype.NONE):
  52. """Create a new rdataset of the specified class and type.
  53. @see: the description of the class instance variables for the
  54. meaning of I{rdclass} and I{rdtype}"""
  55. super(Rdataset, self).__init__()
  56. self.rdclass = rdclass
  57. self.rdtype = rdtype
  58. self.covers = covers
  59. self.ttl = 0
  60. def _clone(self):
  61. obj = super(Rdataset, self)._clone()
  62. obj.rdclass = self.rdclass
  63. obj.rdtype = self.rdtype
  64. obj.covers = self.covers
  65. obj.ttl = self.ttl
  66. return obj
  67. def update_ttl(self, ttl):
  68. """Set the TTL of the rdataset to be the lesser of the set's current
  69. TTL or the specified TTL. If the set contains no rdatas, set the TTL
  70. to the specified TTL.
  71. @param ttl: The TTL
  72. @type ttl: int"""
  73. if len(self) == 0:
  74. self.ttl = ttl
  75. elif ttl < self.ttl:
  76. self.ttl = ttl
  77. def add(self, rd, ttl=None):
  78. """Add the specified rdata to the rdataset.
  79. If the optional I{ttl} parameter is supplied, then
  80. self.update_ttl(ttl) will be called prior to adding the rdata.
  81. @param rd: The rdata
  82. @type rd: dns.rdata.Rdata object
  83. @param ttl: The TTL
  84. @type ttl: int"""
  85. #
  86. # If we're adding a signature, do some special handling to
  87. # check that the signature covers the same type as the
  88. # other rdatas in this rdataset. If this is the first rdata
  89. # in the set, initialize the covers field.
  90. #
  91. if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
  92. raise IncompatibleTypes
  93. if ttl is not None:
  94. self.update_ttl(ttl)
  95. if self.rdtype == dns.rdatatype.RRSIG or \
  96. self.rdtype == dns.rdatatype.SIG:
  97. covers = rd.covers()
  98. if len(self) == 0 and self.covers == dns.rdatatype.NONE:
  99. self.covers = covers
  100. elif self.covers != covers:
  101. raise DifferingCovers
  102. if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
  103. self.clear()
  104. super(Rdataset, self).add(rd)
  105. def union_update(self, other):
  106. self.update_ttl(other.ttl)
  107. super(Rdataset, self).union_update(other)
  108. def intersection_update(self, other):
  109. self.update_ttl(other.ttl)
  110. super(Rdataset, self).intersection_update(other)
  111. def update(self, other):
  112. """Add all rdatas in other to self.
  113. @param other: The rdataset from which to update
  114. @type other: dns.rdataset.Rdataset object"""
  115. self.update_ttl(other.ttl)
  116. super(Rdataset, self).update(other)
  117. def __repr__(self):
  118. if self.covers == 0:
  119. ctext = ''
  120. else:
  121. ctext = '(' + dns.rdatatype.to_text(self.covers) + ')'
  122. return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \
  123. dns.rdatatype.to_text(self.rdtype) + ctext + ' rdataset>'
  124. def __str__(self):
  125. return self.to_text()
  126. def __eq__(self, other):
  127. """Two rdatasets are equal if they have the same class, type, and
  128. covers, and contain the same rdata.
  129. @rtype: bool"""
  130. if not isinstance(other, Rdataset):
  131. return False
  132. if self.rdclass != other.rdclass or \
  133. self.rdtype != other.rdtype or \
  134. self.covers != other.covers:
  135. return False
  136. return super(Rdataset, self).__eq__(other)
  137. def __ne__(self, other):
  138. return not self.__eq__(other)
  139. def to_text(self, name=None, origin=None, relativize=True,
  140. override_rdclass=None, **kw):
  141. """Convert the rdataset into DNS master file format.
  142. @see: L{dns.name.Name.choose_relativity} for more information
  143. on how I{origin} and I{relativize} determine the way names
  144. are emitted.
  145. Any additional keyword arguments are passed on to the rdata
  146. to_text() method.
  147. @param name: If name is not None, emit a RRs with I{name} as
  148. the owner name.
  149. @type name: dns.name.Name object
  150. @param origin: The origin for relative names, or None.
  151. @type origin: dns.name.Name object
  152. @param relativize: True if names should names be relativized
  153. @type relativize: bool"""
  154. if name is not None:
  155. name = name.choose_relativity(origin, relativize)
  156. ntext = str(name)
  157. pad = ' '
  158. else:
  159. ntext = ''
  160. pad = ''
  161. s = StringIO()
  162. if override_rdclass is not None:
  163. rdclass = override_rdclass
  164. else:
  165. rdclass = self.rdclass
  166. if len(self) == 0:
  167. #
  168. # Empty rdatasets are used for the question section, and in
  169. # some dynamic updates, so we don't need to print out the TTL
  170. # (which is meaningless anyway).
  171. #
  172. s.write(u'%s%s%s %s\n' % (ntext, pad,
  173. dns.rdataclass.to_text(rdclass),
  174. dns.rdatatype.to_text(self.rdtype)))
  175. else:
  176. for rd in self:
  177. s.write(u'%s%s%d %s %s %s\n' %
  178. (ntext, pad, self.ttl, dns.rdataclass.to_text(rdclass),
  179. dns.rdatatype.to_text(self.rdtype),
  180. rd.to_text(origin=origin, relativize=relativize,
  181. **kw)))
  182. #
  183. # We strip off the final \n for the caller's convenience in printing
  184. #
  185. return s.getvalue()[:-1]
  186. def to_wire(self, name, file, compress=None, origin=None,
  187. override_rdclass=None, want_shuffle=True):
  188. """Convert the rdataset to wire format.
  189. @param name: The owner name of the RRset that will be emitted
  190. @type name: dns.name.Name object
  191. @param file: The file to which the wire format data will be appended
  192. @type file: file
  193. @param compress: The compression table to use; the default is None.
  194. @type compress: dict
  195. @param origin: The origin to be appended to any relative names when
  196. they are emitted. The default is None.
  197. @returns: the number of records emitted
  198. @rtype: int
  199. """
  200. if override_rdclass is not None:
  201. rdclass = override_rdclass
  202. want_shuffle = False
  203. else:
  204. rdclass = self.rdclass
  205. file.seek(0, 2)
  206. if len(self) == 0:
  207. name.to_wire(file, compress, origin)
  208. stuff = struct.pack("!HHIH", self.rdtype, rdclass, 0, 0)
  209. file.write(stuff)
  210. return 1
  211. else:
  212. if want_shuffle:
  213. l = list(self)
  214. random.shuffle(l)
  215. else:
  216. l = self
  217. for rd in l:
  218. name.to_wire(file, compress, origin)
  219. stuff = struct.pack("!HHIH", self.rdtype, rdclass,
  220. self.ttl, 0)
  221. file.write(stuff)
  222. start = file.tell()
  223. rd.to_wire(file, compress, origin)
  224. end = file.tell()
  225. assert end - start < 65536
  226. file.seek(start - 2)
  227. stuff = struct.pack("!H", end - start)
  228. file.write(stuff)
  229. file.seek(0, 2)
  230. return len(self)
  231. def match(self, rdclass, rdtype, covers):
  232. """Returns True if this rdataset matches the specified class, type,
  233. and covers"""
  234. if self.rdclass == rdclass and \
  235. self.rdtype == rdtype and \
  236. self.covers == covers:
  237. return True
  238. return False
  239. def from_text_list(rdclass, rdtype, ttl, text_rdatas):
  240. """Create an rdataset with the specified class, type, and TTL, and with
  241. the specified list of rdatas in text format.
  242. @rtype: dns.rdataset.Rdataset object
  243. """
  244. if isinstance(rdclass, string_types):
  245. rdclass = dns.rdataclass.from_text(rdclass)
  246. if isinstance(rdtype, string_types):
  247. rdtype = dns.rdatatype.from_text(rdtype)
  248. r = Rdataset(rdclass, rdtype)
  249. r.update_ttl(ttl)
  250. for t in text_rdatas:
  251. rd = dns.rdata.from_text(r.rdclass, r.rdtype, t)
  252. r.add(rd)
  253. return r
  254. def from_text(rdclass, rdtype, ttl, *text_rdatas):
  255. """Create an rdataset with the specified class, type, and TTL, and with
  256. the specified rdatas in text format.
  257. @rtype: dns.rdataset.Rdataset object
  258. """
  259. return from_text_list(rdclass, rdtype, ttl, text_rdatas)
  260. def from_rdata_list(ttl, rdatas):
  261. """Create an rdataset with the specified TTL, and with
  262. the specified list of rdata objects.
  263. @rtype: dns.rdataset.Rdataset object
  264. """
  265. if len(rdatas) == 0:
  266. raise ValueError("rdata list must not be empty")
  267. r = None
  268. for rd in rdatas:
  269. if r is None:
  270. r = Rdataset(rd.rdclass, rd.rdtype)
  271. r.update_ttl(ttl)
  272. r.add(rd)
  273. return r
  274. def from_rdata(ttl, *rdatas):
  275. """Create an rdataset with the specified TTL, and with
  276. the specified rdata objects.
  277. @rtype: dns.rdataset.Rdataset object
  278. """
  279. return from_rdata_list(ttl, rdatas)