rdata.py 31 KB

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