rdata.py 30 KB

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