rdata.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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 rdata."""
  17. from importlib import import_module
  18. import base64
  19. import binascii
  20. import io
  21. import inspect
  22. import itertools
  23. import random
  24. import dns.wire
  25. import dns.exception
  26. import dns.immutable
  27. import dns.ipv4
  28. import dns.ipv6
  29. import dns.name
  30. import dns.rdataclass
  31. import dns.rdatatype
  32. import dns.tokenizer
  33. import dns.ttl
  34. _chunksize = 32
  35. # We currently allow comparisons for rdata with relative names for backwards
  36. # compatibility, but in the future we will not, as these kinds of comparisons
  37. # can lead to subtle bugs if code is not carefully written.
  38. #
  39. # This switch allows the future behavior to be turned on so code can be
  40. # tested with it.
  41. _allow_relative_comparisons = True
  42. class NoRelativeRdataOrdering(dns.exception.DNSException):
  43. """An attempt was made to do an ordered comparison of one or more
  44. rdata with relative names. The only reliable way of sorting rdata
  45. is to use non-relativized rdata.
  46. """
  47. def _wordbreak(data, chunksize=_chunksize, separator=b' '):
  48. """Break a binary string into chunks of chunksize characters separated by
  49. a space.
  50. """
  51. if not chunksize:
  52. return data.decode()
  53. return separator.join([data[i:i + chunksize]
  54. for i
  55. in range(0, len(data), chunksize)]).decode()
  56. # pylint: disable=unused-argument
  57. def _hexify(data, chunksize=_chunksize, separator=b' ', **kw):
  58. """Convert a binary string into its hex encoding, broken up into chunks
  59. of chunksize characters separated by a separator.
  60. """
  61. return _wordbreak(binascii.hexlify(data), chunksize, separator)
  62. def _base64ify(data, chunksize=_chunksize, separator=b' ', **kw):
  63. """Convert a binary string into its base64 encoding, broken up into chunks
  64. of chunksize characters separated by a separator.
  65. """
  66. return _wordbreak(base64.b64encode(data), chunksize, separator)
  67. # pylint: enable=unused-argument
  68. __escaped = b'"\\'
  69. def _escapify(qstring):
  70. """Escape the characters in a quoted string which need it."""
  71. if isinstance(qstring, str):
  72. qstring = qstring.encode()
  73. if not isinstance(qstring, bytearray):
  74. qstring = bytearray(qstring)
  75. text = ''
  76. for c in qstring:
  77. if c in __escaped:
  78. text += '\\' + chr(c)
  79. elif c >= 0x20 and c < 0x7F:
  80. text += chr(c)
  81. else:
  82. text += '\\%03d' % c
  83. return text
  84. def _truncate_bitmap(what):
  85. """Determine the index of greatest byte that isn't all zeros, and
  86. return the bitmap that contains all the bytes less than that index.
  87. """
  88. for i in range(len(what) - 1, -1, -1):
  89. if what[i] != 0:
  90. return what[0: i + 1]
  91. return what[0:1]
  92. # So we don't have to edit all the rdata classes...
  93. _constify = dns.immutable.constify
  94. @dns.immutable.immutable
  95. class Rdata:
  96. """Base class for all DNS rdata types."""
  97. __slots__ = ['rdclass', 'rdtype', 'rdcomment']
  98. def __init__(self, rdclass, rdtype):
  99. """Initialize an rdata.
  100. *rdclass*, an ``int`` is the rdataclass of the Rdata.
  101. *rdtype*, an ``int`` is the rdatatype of the Rdata.
  102. """
  103. self.rdclass = self._as_rdataclass(rdclass)
  104. self.rdtype = self._as_rdatatype(rdtype)
  105. self.rdcomment = None
  106. def _get_all_slots(self):
  107. return itertools.chain.from_iterable(getattr(cls, '__slots__', [])
  108. for cls in self.__class__.__mro__)
  109. def __getstate__(self):
  110. # We used to try to do a tuple of all slots here, but it
  111. # doesn't work as self._all_slots isn't available at
  112. # __setstate__() time. Before that we tried to store a tuple
  113. # of __slots__, but that didn't work as it didn't store the
  114. # slots defined by ancestors. This older way didn't fail
  115. # outright, but ended up with partially broken objects, e.g.
  116. # if you unpickled an A RR it wouldn't have rdclass and rdtype
  117. # attributes, and would compare badly.
  118. state = {}
  119. for slot in self._get_all_slots():
  120. state[slot] = getattr(self, slot)
  121. return state
  122. def __setstate__(self, state):
  123. for slot, val in state.items():
  124. object.__setattr__(self, slot, val)
  125. if not hasattr(self, 'rdcomment'):
  126. # Pickled rdata from 2.0.x might not have a rdcomment, so add
  127. # it if needed.
  128. object.__setattr__(self, 'rdcomment', None)
  129. def covers(self):
  130. """Return the type a Rdata covers.
  131. DNS SIG/RRSIG rdatas apply to a specific type; this type is
  132. returned by the covers() function. If the rdata type is not
  133. SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when
  134. creating rdatasets, allowing the rdataset to contain only RRSIGs
  135. of a particular type, e.g. RRSIG(NS).
  136. Returns an ``int``.
  137. """
  138. return dns.rdatatype.NONE
  139. def extended_rdatatype(self):
  140. """Return a 32-bit type value, the least significant 16 bits of
  141. which are the ordinary DNS type, and the upper 16 bits of which are
  142. the "covered" type, if any.
  143. Returns an ``int``.
  144. """
  145. return self.covers() << 16 | self.rdtype
  146. def to_text(self, origin=None, relativize=True, **kw):
  147. """Convert an rdata to text format.
  148. Returns a ``str``.
  149. """
  150. raise NotImplementedError # pragma: no cover
  151. def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
  152. raise NotImplementedError # pragma: no cover
  153. def to_wire(self, file=None, compress=None, origin=None,
  154. canonicalize=False):
  155. """Convert an rdata to wire format.
  156. Returns a ``bytes`` or ``None``.
  157. """
  158. if file:
  159. return self._to_wire(file, compress, origin, canonicalize)
  160. else:
  161. f = io.BytesIO()
  162. self._to_wire(f, compress, origin, canonicalize)
  163. return f.getvalue()
  164. def to_generic(self, origin=None):
  165. """Creates a dns.rdata.GenericRdata equivalent of this rdata.
  166. Returns a ``dns.rdata.GenericRdata``.
  167. """
  168. return dns.rdata.GenericRdata(self.rdclass, self.rdtype,
  169. self.to_wire(origin=origin))
  170. def to_digestable(self, origin=None):
  171. """Convert rdata to a format suitable for digesting in hashes. This
  172. is also the DNSSEC canonical form.
  173. Returns a ``bytes``.
  174. """
  175. return self.to_wire(origin=origin, canonicalize=True)
  176. def __repr__(self):
  177. covers = self.covers()
  178. if covers == dns.rdatatype.NONE:
  179. ctext = ''
  180. else:
  181. ctext = '(' + dns.rdatatype.to_text(covers) + ')'
  182. return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \
  183. dns.rdatatype.to_text(self.rdtype) + ctext + ' rdata: ' + \
  184. str(self) + '>'
  185. def __str__(self):
  186. return self.to_text()
  187. def _cmp(self, other):
  188. """Compare an rdata with another rdata of the same rdtype and
  189. rdclass.
  190. For rdata with only absolute names:
  191. Return < 0 if self < other in the DNSSEC ordering, 0 if self
  192. == other, and > 0 if self > other.
  193. For rdata with at least one relative names:
  194. The rdata sorts before any rdata with only absolute names.
  195. When compared with another relative rdata, all names are
  196. made absolute as if they were relative to the root, as the
  197. proper origin is not available. While this creates a stable
  198. ordering, it is NOT guaranteed to be the DNSSEC ordering.
  199. In the future, all ordering comparisons for rdata with
  200. relative names will be disallowed.
  201. """
  202. try:
  203. our = self.to_digestable()
  204. our_relative = False
  205. except dns.name.NeedAbsoluteNameOrOrigin:
  206. if _allow_relative_comparisons:
  207. our = self.to_digestable(dns.name.root)
  208. our_relative = True
  209. try:
  210. their = other.to_digestable()
  211. their_relative = False
  212. except dns.name.NeedAbsoluteNameOrOrigin:
  213. if _allow_relative_comparisons:
  214. their = other.to_digestable(dns.name.root)
  215. their_relative = True
  216. if _allow_relative_comparisons:
  217. if our_relative != their_relative:
  218. # For the purpose of comparison, all rdata with at least one
  219. # relative name is less than an rdata with only absolute names.
  220. if our_relative:
  221. return -1
  222. else:
  223. return 1
  224. elif our_relative or their_relative:
  225. raise NoRelativeRdataOrdering
  226. if our == their:
  227. return 0
  228. elif our > their:
  229. return 1
  230. else:
  231. return -1
  232. def __eq__(self, other):
  233. if not isinstance(other, Rdata):
  234. return False
  235. if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  236. return False
  237. our_relative = False
  238. their_relative = False
  239. try:
  240. our = self.to_digestable()
  241. except dns.name.NeedAbsoluteNameOrOrigin:
  242. our = self.to_digestable(dns.name.root)
  243. our_relative = True
  244. try:
  245. their = other.to_digestable()
  246. except dns.name.NeedAbsoluteNameOrOrigin:
  247. their = other.to_digestable(dns.name.root)
  248. their_relative = True
  249. if our_relative != their_relative:
  250. return False
  251. return our == their
  252. def __ne__(self, other):
  253. if not isinstance(other, Rdata):
  254. return True
  255. if self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  256. return True
  257. return not self.__eq__(other)
  258. def __lt__(self, other):
  259. if not isinstance(other, Rdata) or \
  260. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  261. return NotImplemented
  262. return self._cmp(other) < 0
  263. def __le__(self, other):
  264. if not isinstance(other, Rdata) or \
  265. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  266. return NotImplemented
  267. return self._cmp(other) <= 0
  268. def __ge__(self, other):
  269. if not isinstance(other, Rdata) or \
  270. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  271. return NotImplemented
  272. return self._cmp(other) >= 0
  273. def __gt__(self, other):
  274. if not isinstance(other, Rdata) or \
  275. self.rdclass != other.rdclass or self.rdtype != other.rdtype:
  276. return NotImplemented
  277. return self._cmp(other) > 0
  278. def __hash__(self):
  279. return hash(self.to_digestable(dns.name.root))
  280. @classmethod
  281. def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
  282. relativize_to=None):
  283. raise NotImplementedError # pragma: no cover
  284. @classmethod
  285. def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
  286. raise NotImplementedError # pragma: no cover
  287. def replace(self, **kwargs):
  288. """
  289. Create a new Rdata instance based on the instance replace was
  290. invoked on. It is possible to pass different parameters to
  291. override the corresponding properties of the base Rdata.
  292. Any field specific to the Rdata type can be replaced, but the
  293. *rdtype* and *rdclass* fields cannot.
  294. Returns an instance of the same Rdata subclass as *self*.
  295. """
  296. # Get the constructor parameters.
  297. parameters = inspect.signature(self.__init__).parameters
  298. # Ensure that all of the arguments correspond to valid fields.
  299. # Don't allow rdclass or rdtype to be changed, though.
  300. for key in kwargs:
  301. if key == 'rdcomment':
  302. continue
  303. if key not in parameters:
  304. raise AttributeError("'{}' object has no attribute '{}'"
  305. .format(self.__class__.__name__, key))
  306. if key in ('rdclass', 'rdtype'):
  307. raise AttributeError("Cannot overwrite '{}' attribute '{}'"
  308. .format(self.__class__.__name__, key))
  309. # Construct the parameter list. For each field, use the value in
  310. # kwargs if present, and the current value otherwise.
  311. args = (kwargs.get(key, getattr(self, key)) for key in parameters)
  312. # Create, validate, and return the new object.
  313. rd = self.__class__(*args)
  314. # The comment is not set in the constructor, so give it special
  315. # handling.
  316. rdcomment = kwargs.get('rdcomment', self.rdcomment)
  317. if rdcomment is not None:
  318. object.__setattr__(rd, 'rdcomment', rdcomment)
  319. return rd
  320. # Type checking and conversion helpers. These are class methods as
  321. # they don't touch object state and may be useful to others.
  322. @classmethod
  323. def _as_rdataclass(cls, value):
  324. return dns.rdataclass.RdataClass.make(value)
  325. @classmethod
  326. def _as_rdatatype(cls, value):
  327. return dns.rdatatype.RdataType.make(value)
  328. @classmethod
  329. def _as_bytes(cls, value, encode=False, max_length=None, empty_ok=True):
  330. if encode and isinstance(value, str):
  331. value = value.encode()
  332. elif isinstance(value, bytearray):
  333. value = bytes(value)
  334. elif not isinstance(value, bytes):
  335. raise ValueError('not bytes')
  336. if max_length is not None and len(value) > max_length:
  337. raise ValueError('too long')
  338. if not empty_ok and len(value) == 0:
  339. raise ValueError('empty bytes not allowed')
  340. return value
  341. @classmethod
  342. def _as_name(cls, value):
  343. # Note that proper name conversion (e.g. with origin and IDNA
  344. # awareness) is expected to be done via from_text. This is just
  345. # a simple thing for people invoking the constructor directly.
  346. if isinstance(value, str):
  347. return dns.name.from_text(value)
  348. elif not isinstance(value, dns.name.Name):
  349. raise ValueError('not a name')
  350. return value
  351. @classmethod
  352. def _as_uint8(cls, value):
  353. if not isinstance(value, int):
  354. raise ValueError('not an integer')
  355. if value < 0 or value > 255:
  356. raise ValueError('not a uint8')
  357. return value
  358. @classmethod
  359. def _as_uint16(cls, value):
  360. if not isinstance(value, int):
  361. raise ValueError('not an integer')
  362. if value < 0 or value > 65535:
  363. raise ValueError('not a uint16')
  364. return value
  365. @classmethod
  366. def _as_uint32(cls, value):
  367. if not isinstance(value, int):
  368. raise ValueError('not an integer')
  369. if value < 0 or value > 4294967295:
  370. raise ValueError('not a uint32')
  371. return value
  372. @classmethod
  373. def _as_uint48(cls, value):
  374. if not isinstance(value, int):
  375. raise ValueError('not an integer')
  376. if value < 0 or value > 281474976710655:
  377. raise ValueError('not a uint48')
  378. return value
  379. @classmethod
  380. def _as_int(cls, value, low=None, high=None):
  381. if not isinstance(value, int):
  382. raise ValueError('not an integer')
  383. if low is not None and value < low:
  384. raise ValueError('value too small')
  385. if high is not None and value > high:
  386. raise ValueError('value too large')
  387. return value
  388. @classmethod
  389. def _as_ipv4_address(cls, value):
  390. if isinstance(value, str):
  391. # call to check validity
  392. dns.ipv4.inet_aton(value)
  393. return value
  394. elif isinstance(value, bytes):
  395. return dns.ipv4.inet_ntoa(value)
  396. else:
  397. raise ValueError('not an IPv4 address')
  398. @classmethod
  399. def _as_ipv6_address(cls, value):
  400. if isinstance(value, str):
  401. # call to check validity
  402. dns.ipv6.inet_aton(value)
  403. return value
  404. elif isinstance(value, bytes):
  405. return dns.ipv6.inet_ntoa(value)
  406. else:
  407. raise ValueError('not an IPv6 address')
  408. @classmethod
  409. def _as_bool(cls, value):
  410. if isinstance(value, bool):
  411. return value
  412. else:
  413. raise ValueError('not a boolean')
  414. @classmethod
  415. def _as_ttl(cls, value):
  416. if isinstance(value, int):
  417. return cls._as_int(value, 0, dns.ttl.MAX_TTL)
  418. elif isinstance(value, str):
  419. return dns.ttl.from_text(value)
  420. else:
  421. raise ValueError('not a TTL')
  422. @classmethod
  423. def _as_tuple(cls, value, as_value):
  424. try:
  425. # For user convenience, if value is a singleton of the list
  426. # element type, wrap it in a tuple.
  427. return (as_value(value),)
  428. except Exception:
  429. # Otherwise, check each element of the iterable *value*
  430. # against *as_value*.
  431. return tuple(as_value(v) for v in value)
  432. # Processing order
  433. @classmethod
  434. def _processing_order(cls, iterable):
  435. items = list(iterable)
  436. random.shuffle(items)
  437. return items
  438. class GenericRdata(Rdata):
  439. """Generic Rdata Class
  440. This class is used for rdata types for which we have no better
  441. implementation. It implements the DNS "unknown RRs" scheme.
  442. """
  443. __slots__ = ['data']
  444. def __init__(self, rdclass, rdtype, data):
  445. super().__init__(rdclass, rdtype)
  446. object.__setattr__(self, 'data', data)
  447. def to_text(self, origin=None, relativize=True, **kw):
  448. return r'\# %d ' % len(self.data) + _hexify(self.data, **kw)
  449. @classmethod
  450. def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True,
  451. relativize_to=None):
  452. token = tok.get()
  453. if not token.is_identifier() or token.value != r'\#':
  454. raise dns.exception.SyntaxError(
  455. r'generic rdata does not start with \#')
  456. length = tok.get_int()
  457. hex = tok.concatenate_remaining_identifiers(True).encode()
  458. data = binascii.unhexlify(hex)
  459. if len(data) != length:
  460. raise dns.exception.SyntaxError(
  461. 'generic rdata hex data has wrong length')
  462. return cls(rdclass, rdtype, data)
  463. def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
  464. file.write(self.data)
  465. @classmethod
  466. def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
  467. return cls(rdclass, rdtype, parser.get_remaining())
  468. _rdata_classes = {}
  469. _module_prefix = 'dns.rdtypes'
  470. def get_rdata_class(rdclass, rdtype):
  471. cls = _rdata_classes.get((rdclass, rdtype))
  472. if not cls:
  473. cls = _rdata_classes.get((dns.rdatatype.ANY, rdtype))
  474. if not cls:
  475. rdclass_text = dns.rdataclass.to_text(rdclass)
  476. rdtype_text = dns.rdatatype.to_text(rdtype)
  477. rdtype_text = rdtype_text.replace('-', '_')
  478. try:
  479. mod = import_module('.'.join([_module_prefix,
  480. rdclass_text, rdtype_text]))
  481. cls = getattr(mod, rdtype_text)
  482. _rdata_classes[(rdclass, rdtype)] = cls
  483. except ImportError:
  484. try:
  485. mod = import_module('.'.join([_module_prefix,
  486. 'ANY', rdtype_text]))
  487. cls = getattr(mod, rdtype_text)
  488. _rdata_classes[(dns.rdataclass.ANY, rdtype)] = cls
  489. _rdata_classes[(rdclass, rdtype)] = cls
  490. except ImportError:
  491. pass
  492. if not cls:
  493. cls = GenericRdata
  494. _rdata_classes[(rdclass, rdtype)] = cls
  495. return cls
  496. def from_text(rdclass, rdtype, tok, origin=None, relativize=True,
  497. relativize_to=None, idna_codec=None):
  498. """Build an rdata object from text format.
  499. This function attempts to dynamically load a class which
  500. implements the specified rdata class and type. If there is no
  501. class-and-type-specific implementation, the GenericRdata class
  502. is used.
  503. Once a class is chosen, its from_text() class method is called
  504. with the parameters to this function.
  505. If *tok* is a ``str``, then a tokenizer is created and the string
  506. is used as its input.
  507. *rdclass*, an ``int``, the rdataclass.
  508. *rdtype*, an ``int``, the rdatatype.
  509. *tok*, a ``dns.tokenizer.Tokenizer`` or a ``str``.
  510. *origin*, a ``dns.name.Name`` (or ``None``), the
  511. origin to use for relative names.
  512. *relativize*, a ``bool``. If true, name will be relativized.
  513. *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
  514. when relativizing names. If not set, the *origin* value will be used.
  515. *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
  516. encoder/decoder to use if a tokenizer needs to be created. If
  517. ``None``, the default IDNA 2003 encoder/decoder is used. If a
  518. tokenizer is not created, then the codec associated with the tokenizer
  519. is the one that is used.
  520. Returns an instance of the chosen Rdata subclass.
  521. """
  522. if isinstance(tok, str):
  523. tok = dns.tokenizer.Tokenizer(tok, idna_codec=idna_codec)
  524. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  525. rdtype = dns.rdatatype.RdataType.make(rdtype)
  526. cls = get_rdata_class(rdclass, rdtype)
  527. with dns.exception.ExceptionWrapper(dns.exception.SyntaxError):
  528. rdata = None
  529. if cls != GenericRdata:
  530. # peek at first token
  531. token = tok.get()
  532. tok.unget(token)
  533. if token.is_identifier() and \
  534. token.value == r'\#':
  535. #
  536. # Known type using the generic syntax. Extract the
  537. # wire form from the generic syntax, and then run
  538. # from_wire on it.
  539. #
  540. grdata = GenericRdata.from_text(rdclass, rdtype, tok, origin,
  541. relativize, relativize_to)
  542. rdata = from_wire(rdclass, rdtype, grdata.data, 0,
  543. len(grdata.data), origin)
  544. #
  545. # If this comparison isn't equal, then there must have been
  546. # compressed names in the wire format, which is an error,
  547. # there being no reasonable context to decompress with.
  548. #
  549. rwire = rdata.to_wire()
  550. if rwire != grdata.data:
  551. raise dns.exception.SyntaxError('compressed data in '
  552. 'generic syntax form '
  553. 'of known rdatatype')
  554. if rdata is None:
  555. rdata = cls.from_text(rdclass, rdtype, tok, origin, relativize,
  556. relativize_to)
  557. token = tok.get_eol_as_token()
  558. if token.comment is not None:
  559. object.__setattr__(rdata, 'rdcomment', token.comment)
  560. return rdata
  561. def from_wire_parser(rdclass, rdtype, parser, origin=None):
  562. """Build an rdata object from wire format
  563. This function attempts to dynamically load a class which
  564. implements the specified rdata class and type. If there is no
  565. class-and-type-specific implementation, the GenericRdata class
  566. is used.
  567. Once a class is chosen, its from_wire() class method is called
  568. with the parameters to this function.
  569. *rdclass*, an ``int``, the rdataclass.
  570. *rdtype*, an ``int``, the rdatatype.
  571. *parser*, a ``dns.wire.Parser``, the parser, which should be
  572. restricted to the rdata length.
  573. *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``,
  574. then names will be relativized to this origin.
  575. Returns an instance of the chosen Rdata subclass.
  576. """
  577. rdclass = dns.rdataclass.RdataClass.make(rdclass)
  578. rdtype = dns.rdatatype.RdataType.make(rdtype)
  579. cls = get_rdata_class(rdclass, rdtype)
  580. with dns.exception.ExceptionWrapper(dns.exception.FormError):
  581. return cls.from_wire_parser(rdclass, rdtype, parser, origin)
  582. def from_wire(rdclass, rdtype, wire, current, rdlen, origin=None):
  583. """Build an rdata object from wire format
  584. This function attempts to dynamically load a class which
  585. implements the specified rdata class and type. If there is no
  586. class-and-type-specific implementation, the GenericRdata class
  587. is used.
  588. Once a class is chosen, its from_wire() class method is called
  589. with the parameters to this function.
  590. *rdclass*, an ``int``, the rdataclass.
  591. *rdtype*, an ``int``, the rdatatype.
  592. *wire*, a ``bytes``, the wire-format message.
  593. *current*, an ``int``, the offset in wire of the beginning of
  594. the rdata.
  595. *rdlen*, an ``int``, the length of the wire-format rdata
  596. *origin*, a ``dns.name.Name`` (or ``None``). If not ``None``,
  597. then names will be relativized to this origin.
  598. Returns an instance of the chosen Rdata subclass.
  599. """
  600. parser = dns.wire.Parser(wire, current)
  601. with parser.restrict_to(rdlen):
  602. return from_wire_parser(rdclass, rdtype, parser, origin)
  603. class RdatatypeExists(dns.exception.DNSException):
  604. """DNS rdatatype already exists."""
  605. supp_kwargs = {'rdclass', 'rdtype'}
  606. fmt = "The rdata type with class {rdclass:d} and rdtype {rdtype:d} " + \
  607. "already exists."
  608. def register_type(implementation, rdtype, rdtype_text, is_singleton=False,
  609. rdclass=dns.rdataclass.IN):
  610. """Dynamically register a module to handle an rdatatype.
  611. *implementation*, a module implementing the type in the usual dnspython
  612. way.
  613. *rdtype*, an ``int``, the rdatatype to register.
  614. *rdtype_text*, a ``str``, the textual form of the rdatatype.
  615. *is_singleton*, a ``bool``, indicating if the type is a singleton (i.e.
  616. RRsets of the type can have only one member.)
  617. *rdclass*, the rdataclass of the type, or ``dns.rdataclass.ANY`` if
  618. it applies to all classes.
  619. """
  620. existing_cls = get_rdata_class(rdclass, rdtype)
  621. if existing_cls != GenericRdata or dns.rdatatype.is_metatype(rdtype):
  622. raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype)
  623. try:
  624. if dns.rdatatype.RdataType(rdtype).name != rdtype_text:
  625. raise RdatatypeExists(rdclass=rdclass, rdtype=rdtype)
  626. except ValueError:
  627. pass
  628. _rdata_classes[(rdclass, rdtype)] = getattr(implementation,
  629. rdtype_text.replace('-', '_'))
  630. dns.rdatatype.register_type(rdtype, rdtype_text, is_singleton)