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