Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dns/name.py: 27%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
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.
18"""DNS Names."""
20import copy
21import dataclasses
22import encodings.idna # pyright: ignore
23import functools
24import struct
25from collections.abc import Callable, Iterable
26from typing import Any
28import dns._features
29import dns._text_util
30import dns.enum
31import dns.exception
32import dns.immutable
33import dns.wirebase
34from dns.style import BaseStyle
36# Dnspython will never access idna if the import fails, but pyright can't figure
37# that out, so...
38#
39# pyright: reportAttributeAccessIssue = false, reportPossiblyUnboundVariable = false
41if dns._features.have("idna"):
42 import idna # pyright: ignore
44 have_idna_2008 = True
45else: # pragma: no cover
46 have_idna_2008 = False
49CompressType = dict["Name", int]
52class NameRelation(dns.enum.IntEnum):
53 """Name relation result from fullcompare()."""
55 # This is an IntEnum for backwards compatibility in case anyone
56 # has hardwired the constants.
58 #: The compared names have no relationship to each other.
59 NONE = 0
60 #: the first name is a superdomain of the second.
61 SUPERDOMAIN = 1
62 #: The first name is a subdomain of the second.
63 SUBDOMAIN = 2
64 #: The compared names are equal.
65 EQUAL = 3
66 #: The compared names have a common ancestor.
67 COMMONANCESTOR = 4
69 @classmethod
70 def _maximum(cls):
71 return cls.COMMONANCESTOR # pragma: no cover
73 @classmethod
74 def _short_name(cls):
75 return cls.__name__ # pragma: no cover
78# Backwards compatibility
79NAMERELN_NONE = NameRelation.NONE
80NAMERELN_SUPERDOMAIN = NameRelation.SUPERDOMAIN
81NAMERELN_SUBDOMAIN = NameRelation.SUBDOMAIN
82NAMERELN_EQUAL = NameRelation.EQUAL
83NAMERELN_COMMONANCESTOR = NameRelation.COMMONANCESTOR
86class EmptyLabel(dns.exception.SyntaxError):
87 """A DNS label is empty."""
90class BadEscape(dns.exception.SyntaxError):
91 """An escaped code in a text format of DNS name is invalid."""
94class BadPointer(dns.exception.FormError):
95 """A DNS compression pointer points forward instead of backward."""
98class PointerChainTooLong(dns.exception.FormError):
99 """A DNS compression pointer chain was too long."""
102class BadLabelType(dns.exception.FormError):
103 """The label type in DNS name wire format is unknown."""
106class DecompressionForbidden(dns.exception.FormError):
107 """A name has a compression pointer but decompression is forbidden."""
110class NeedAbsoluteNameOrOrigin(dns.exception.DNSException):
111 """An attempt was made to convert a non-absolute name to
112 wire when there was also a non-absolute (or missing) origin."""
115class NameTooLong(dns.exception.FormError):
116 """A DNS name is > 255 octets long."""
119class LabelTooLong(dns.exception.SyntaxError):
120 """A DNS label is > 63 octets long."""
123class AbsoluteConcatenation(dns.exception.DNSException):
124 """An attempt was made to append anything other than the
125 empty name to an absolute DNS name."""
128class NoParent(dns.exception.DNSException):
129 """An attempt was made to get the parent of the root name
130 or the empty name."""
133class NoIDNA2008(dns.exception.DNSException):
134 """IDNA 2008 processing was requested but the idna module is not
135 available."""
138class IDNAException(dns.exception.DNSException):
139 """IDNA processing raised an exception."""
141 supp_kwargs = {"idna_exception"}
142 fmt = "IDNA processing exception: {idna_exception}"
144 # We do this as otherwise mypy complains about unexpected keyword argument
145 # idna_exception
146 def __init__(self, *args, **kwargs):
147 super().__init__(*args, **kwargs)
150class NeedSubdomainOfOrigin(dns.exception.DNSException):
151 """An absolute name was provided that is not a subdomain of the specified origin."""
154_escaped = b'"().;\\@$'
155# The Unicode full stops are escaped too, as from_unicode() treats them as label
156# separators.
157_escaped_text = '"().;\\@$。.。'
159# Octet values used by from_text().
160_PERIOD_VALUE = ord(".")
161_BACKSLASH_VALUE = ord("\\")
162_ZERO_VALUE = ord("0")
163_NINE_VALUE = ord("9")
166def _escapify(label: bytes | str) -> str:
167 """Escape the characters in label which need it.
169 :returns: the escaped string
170 :rtype: str
171 """
172 if isinstance(label, bytes):
173 # Ordinary DNS label mode. Escape special characters and values
174 # < 0x20 or > 0x7f.
175 text = ""
176 for c in label:
177 if c in _escaped:
178 text += "\\" + chr(c)
179 elif c > 0x20 and c < 0x7F:
180 text += chr(c)
181 else:
182 text += f"\\{c:03d}"
183 return text
185 # Unicode label mode. Escape only special characters and control
186 # characters, i.e. values <= 0x20 and the DEL and C1 range 0x7f-0x9f.
187 text = ""
188 for uc in label:
189 if uc in _escaped_text:
190 text += "\\" + uc
191 elif uc <= "\x20" or "\x7f" <= uc <= "\x9f":
192 text += f"\\{ord(uc):03d}"
193 else:
194 text += uc
195 return text
198class IDNACodec:
199 """Abstract base class for IDNA encoder/decoders."""
201 def __init__(self):
202 pass
204 def is_idna(self, label: bytes) -> bool:
205 return label.lower().startswith(b"xn--")
207 def encode(self, label: str) -> bytes:
208 raise NotImplementedError # pragma: no cover
210 def decode(self, label: bytes) -> str:
211 # We do not apply any IDNA policy on decode.
212 if self.is_idna(label):
213 try:
214 slabel = label[4:].decode("punycode")
215 except Exception as e:
216 raise IDNAException(idna_exception=e)
217 # An A-label encodes a U-label, which has at least one non-ASCII
218 # character. Otherwise e.g. "xn--www-" would decode to "www" and
219 # the name would display as a different one.
220 if is_all_ascii(slabel):
221 raise IDNAException(
222 idna_exception=f"{label!r} does not decode to a U-label"
223 )
224 return _escapify(slabel)
225 else:
226 return _escapify(label)
229class IDNA2003Codec(IDNACodec):
230 """IDNA 2003 encoder/decoder."""
232 def __init__(self, strict_decode: bool = False):
233 """Initialize the IDNA 2003 encoder/decoder.
235 :param bool strict_decode: If ``True``, then IDNA2003 checking
236 is done when decoding. This can cause failures if the name
237 was encoded with IDNA2008. The default is ``False``.
238 """
240 super().__init__()
241 self.strict_decode = strict_decode
243 def encode(self, label: str) -> bytes:
244 """Encode *label*."""
246 if label == "":
247 return b""
248 try:
249 return encodings.idna.ToASCII(label)
250 except UnicodeError:
251 raise LabelTooLong
253 def decode(self, label: bytes) -> str:
254 """Decode *label*."""
255 if not self.strict_decode:
256 return super().decode(label)
257 if label == b"":
258 return ""
259 try:
260 return _escapify(encodings.idna.ToUnicode(label))
261 except Exception as e:
262 raise IDNAException(idna_exception=e)
265class IDNA2008Codec(IDNACodec):
266 """IDNA 2008 encoder/decoder."""
268 def __init__(
269 self,
270 uts_46: bool = False,
271 transitional: bool = False,
272 allow_pure_ascii: bool = False,
273 strict_decode: bool = False,
274 ):
275 """Initialize the IDNA 2008 encoder/decoder.
277 :param bool uts_46: If ``True``, apply Unicode IDNA compatibility
278 processing as described in Unicode Technical Standard #46
279 (https://unicode.org/reports/tr46/). If ``False``, do not
280 apply the mapping. The default is ``False``.
281 :param bool transitional: If ``True``, use the "transitional" mode
282 described in Unicode Technical Standard #46. The default is
283 ``False``. This setting has no effect in idna 3.11 and later
284 as transitional support has been removed.
285 :param bool allow_pure_ascii: If ``True``, then a label which
286 consists of only ASCII characters is allowed. This is less
287 strict than regular IDNA 2008, but is also necessary for mixed
288 names, e.g. a name starting with ``_sip._tcp.`` and ending
289 in an IDN suffix which would otherwise be disallowed. The
290 default is ``False``.
291 :param bool strict_decode: If ``True``, then IDNA2008 checking
292 is done when decoding. This can cause failures if the name
293 was encoded with IDNA2003. The default is ``False``.
294 """
295 super().__init__()
296 self.uts_46 = uts_46
297 self.transitional = transitional
298 self.allow_pure_ascii = allow_pure_ascii
299 self.strict_decode = strict_decode
301 def encode(self, label: str) -> bytes:
302 if label == "":
303 return b""
304 if self.allow_pure_ascii and is_all_ascii(label):
305 encoded = label.encode("ascii")
306 if len(encoded) > 63:
307 raise LabelTooLong
308 return encoded
309 if not have_idna_2008:
310 raise NoIDNA2008
311 try:
312 if self.uts_46:
313 # pylint: disable=possibly-used-before-assignment
314 label = idna.uts46_remap(label, False, self.transitional)
315 return idna.alabel(label)
316 except idna.IDNAError as e:
317 if e.args[0] == "Label too long":
318 raise LabelTooLong
319 else:
320 raise IDNAException(idna_exception=e)
322 def decode(self, label: bytes) -> str:
323 if not self.strict_decode:
324 return super().decode(label)
325 if label == b"":
326 return ""
327 if not have_idna_2008:
328 raise NoIDNA2008
329 try:
330 ulabel = idna.ulabel(label)
331 if self.uts_46:
332 ulabel = idna.uts46_remap(ulabel, False, self.transitional)
333 return _escapify(ulabel)
334 except (idna.IDNAError, UnicodeError) as e:
335 raise IDNAException(idna_exception=e)
338IDNA_2003_Practical = IDNA2003Codec(False)
339IDNA_2003_Strict = IDNA2003Codec(True)
340IDNA_2003 = IDNA_2003_Practical
341IDNA_2008_Practical = IDNA2008Codec(True, False, True, False)
342IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False)
343IDNA_2008_Strict = IDNA2008Codec(False, False, False, True)
344IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False)
345IDNA_2008 = IDNA_2008_Practical
346if have_idna_2008:
347 IDNA_DEFAULT = IDNA_2008_Practical
348else:
349 IDNA_DEFAULT = IDNA_2003_Practical
352def set_default_idna_codec(idna_codec: IDNACodec):
353 """Set the default IDNA codec."""
354 global IDNA_DEFAULT
355 IDNA_DEFAULT = idna_codec
358def _validate_labels(labels: tuple[bytes, ...]) -> None:
359 """Check for empty labels in the middle of a label sequence,
360 labels that are too long, and for too many labels.
362 :raises dns.name.NameTooLong: if the name as a whole is too long.
363 :raises dns.name.EmptyLabel: if a label is empty (i.e. the root
364 label) and appears in a position other than the end of the label
365 sequence.
366 """
368 l = len(labels)
369 total = 0
370 i = -1
371 j = 0
372 for label in labels:
373 ll = len(label)
374 total += ll + 1
375 if ll > 63:
376 raise LabelTooLong
377 if i < 0 and label == b"":
378 i = j
379 j += 1
380 if total > 255:
381 raise NameTooLong
382 if i >= 0 and i != l - 1:
383 raise EmptyLabel
386def _maybe_convert_to_binary(label: bytes | str) -> bytes:
387 """If label is ``str``, convert it to ``bytes``. If it is already
388 ``bytes`` just return it.
390 """
392 if isinstance(label, bytes):
393 return label
394 else:
395 return label.encode()
398@dataclasses.dataclass(frozen=True)
399class NameStyle(BaseStyle):
400 """Name text styles.
402 :param bool omit_final_dot: If ``True``, don't emit the final dot
403 (denoting the root label) for absolute names. The default is
404 ``False``.
405 :param idna_codec: The IDNA decoder to use. The default is ``None``,
406 which means all text is in the standard DNS zonefile format, i.e.
407 punycode will not be decoded.
408 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
409 :param origin: If ``None`` (the default), the name's relativity is not
410 altered before conversion to text. Otherwise, if *relativize* is
411 ``True`` the name is relativized, and if *relativize* is ``False``
412 the name is derelativized.
413 :type origin: :py:class:`dns.name.Name` or ``None``
414 :param bool relativize: Controls the direction of relativization when
415 *origin* is set.
416 """
418 omit_final_dot: bool = False
419 idna_codec: IDNACodec | None = None
420 origin: "Name | None" = None
421 relativize: bool = False
424@dns.immutable.immutable
425class Name:
426 """A DNS name.
428 The dns.name.Name class represents a DNS name as a tuple of
429 labels. Each label is a ``bytes`` in DNS wire format. Instances
430 of the class are immutable.
431 """
433 __slots__ = ["labels"]
435 def __init__(self, labels: Iterable[bytes | str]):
436 """Initialize a DNS name.
438 :param labels: An iterable whose values are ``str`` or ``bytes``.
439 """
441 blabels = [_maybe_convert_to_binary(x) for x in labels]
442 self.labels = tuple(blabels)
443 _validate_labels(self.labels)
445 def __copy__(self):
446 return Name(self.labels)
448 def __deepcopy__(self, memo):
449 return Name(copy.deepcopy(self.labels, memo))
451 def __getstate__(self):
452 # Names can be pickled
453 return {"labels": self.labels}
455 def __setstate__(self, state):
456 super().__setattr__("labels", state["labels"])
457 _validate_labels(self.labels)
459 def is_absolute(self) -> bool:
460 """Is the most significant label of this name the root label?
462 :rtype: bool
463 """
465 return len(self.labels) > 0 and self.labels[-1] == b""
467 def is_wild(self) -> bool:
468 """Is this name wild? (I.e. Is the least significant label ``'*'``?)
470 :rtype: bool
471 """
473 return len(self.labels) > 0 and self.labels[0] == b"*"
475 def __hash__(self) -> int:
476 """Return a case-insensitive hash of the name.
478 :rtype: int
479 """
481 h = 0
482 for label in self.labels:
483 for c in label.lower():
484 h += (h << 3) + c
485 return h
487 def fullcompare(self, other: "Name") -> tuple[NameRelation, int, int]:
488 """Compare two names, returning a 3-tuple
489 ``(relation, order, nlabels)``.
491 *relation* describes the relationship between the names, and is one
492 of: :py:attr:`dns.name.NameRelation.NONE`,
493 :py:attr:`dns.name.NameRelation.SUPERDOMAIN`,
494 :py:attr:`dns.name.NameRelation.SUBDOMAIN`,
495 :py:attr:`dns.name.NameRelation.EQUAL`, or
496 :py:attr:`dns.name.NameRelation.COMMONANCESTOR`.
498 *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and ==
499 0 if *self* == *other*. A relative name is always less than an
500 absolute name. If both names have the same relativity, then
501 the DNSSEC order relation is used to order them.
503 *nlabels* is the number of significant labels that the two names
504 have in common.
506 Here are some examples. Names ending in "." are absolute names,
507 those not ending in "." are relative names.
509 ============= ============= =========== ===== =======
510 self other relation order nlabels
511 ============= ============= =========== ===== =======
512 www.example. www.example. equal 0 3
513 www.example. example. subdomain > 0 2
514 example. www.example. superdomain < 0 2
515 example1.com. example2.com. common anc. < 0 2
516 example1 example2. none < 0 0
517 example1. example2 none > 0 0
518 ============= ============= =========== ===== =======
520 :param other: The name to compare with.
521 :type other: :py:class:`dns.name.Name`
522 :returns: A 3-tuple ``(relation, order, nlabels)``.
523 :rtype: tuple[:py:class:`dns.name.NameRelation`, int, int]
524 """
526 sabs = self.is_absolute()
527 oabs = other.is_absolute()
528 if sabs != oabs:
529 if sabs:
530 return (NameRelation.NONE, 1, 0)
531 else:
532 return (NameRelation.NONE, -1, 0)
533 l1 = len(self.labels)
534 l2 = len(other.labels)
535 ldiff = l1 - l2
536 if ldiff < 0:
537 l = l1
538 else:
539 l = l2
541 order = 0
542 nlabels = 0
543 namereln = NameRelation.NONE
544 while l > 0:
545 l -= 1
546 l1 -= 1
547 l2 -= 1
548 label1 = self.labels[l1].lower()
549 label2 = other.labels[l2].lower()
550 if label1 < label2:
551 order = -1
552 if nlabels > 0:
553 namereln = NameRelation.COMMONANCESTOR
554 return (namereln, order, nlabels)
555 elif label1 > label2:
556 order = 1
557 if nlabels > 0:
558 namereln = NameRelation.COMMONANCESTOR
559 return (namereln, order, nlabels)
560 nlabels += 1
561 order = ldiff
562 if ldiff < 0:
563 namereln = NameRelation.SUPERDOMAIN
564 elif ldiff > 0:
565 namereln = NameRelation.SUBDOMAIN
566 else:
567 namereln = NameRelation.EQUAL
568 return (namereln, order, nlabels)
570 def is_subdomain(self, other: "Name") -> bool:
571 """Is self a subdomain of other?
573 Note that the notion of subdomain includes equality, e.g.
574 ``dnspython.org`` is a subdomain of itself.
576 :rtype: bool
577 """
579 nr, _, _ = self.fullcompare(other)
580 if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL:
581 return True
582 return False
584 def is_superdomain(self, other: "Name") -> bool:
585 """Is self a superdomain of other?
587 Note that the notion of superdomain includes equality, e.g.
588 ``dnspython.org`` is a superdomain of itself.
590 :rtype: bool
591 """
593 nr, _, _ = self.fullcompare(other)
594 if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL:
595 return True
596 return False
598 def canonicalize(self) -> "Name":
599 """Return a name which is equal to the current name, but is in
600 DNSSEC canonical form.
602 :rtype: :py:class:`dns.name.Name`
603 """
605 return Name([x.lower() for x in self.labels])
607 def __eq__(self, other):
608 if isinstance(other, Name):
609 return self.fullcompare(other)[1] == 0
610 else:
611 return False
613 def __ne__(self, other):
614 if isinstance(other, Name):
615 return self.fullcompare(other)[1] != 0
616 else:
617 return True
619 def __lt__(self, other):
620 if isinstance(other, Name):
621 return self.fullcompare(other)[1] < 0
622 else:
623 return NotImplemented
625 def __le__(self, other):
626 if isinstance(other, Name):
627 return self.fullcompare(other)[1] <= 0
628 else:
629 return NotImplemented
631 def __ge__(self, other):
632 if isinstance(other, Name):
633 return self.fullcompare(other)[1] >= 0
634 else:
635 return NotImplemented
637 def __gt__(self, other):
638 if isinstance(other, Name):
639 return self.fullcompare(other)[1] > 0
640 else:
641 return NotImplemented
643 def __repr__(self):
644 return "<DNS name " + self.__str__() + ">"
646 def __str__(self):
647 return self.to_text(False)
649 def to_text(
650 self, omit_final_dot: bool = False, style: NameStyle | None = None
651 ) -> str:
652 """Convert name to DNS text format.
654 :param bool omit_final_dot: If ``True``, don't emit the final dot
655 (denoting the root label) for absolute names. The default is
656 ``False``.
657 :param style: If specified, the style overrides the other parameters.
658 :type style: :py:class:`dns.name.NameStyle` or ``None``
659 :rtype: str
660 """
661 if style is None:
662 style = NameStyle(omit_final_dot=omit_final_dot)
663 return self.to_styled_text(style)
665 def to_unicode(
666 self,
667 omit_final_dot: bool = False,
668 idna_codec: IDNACodec | None = None,
669 style: NameStyle | None = None,
670 ) -> str:
671 """Convert name to DNS text format.
673 IDN ACE labels are converted to Unicode using the specified codec.
675 :param bool omit_final_dot: If ``True``, don't emit the final dot
676 (denoting the root label) for absolute names. The default is
677 ``False``.
678 :param idna_codec: The IDNA codec to use for decoding ACE labels.
679 If ``None``, the default IDNA codec is used.
680 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
681 :param style: If specified, the style overrides the other parameters.
682 :type style: :py:class:`dns.name.NameStyle` or ``None``
683 :rtype: str
684 """
685 if idna_codec is None:
686 idna_codec = IDNA_DEFAULT
687 if style is None:
688 style = NameStyle(omit_final_dot=omit_final_dot, idna_codec=idna_codec)
689 return self.to_styled_text(style)
691 def to_styled_text(self, style: NameStyle) -> str:
692 """Convert name to text format, applying the style.
694 See the documentation for :py:class:`dns.name.NameStyle` for a description
695 of the style parameters.
697 :param style: The style to apply.
698 :type style: :py:class:`dns.name.NameStyle`
699 :rtype: str
700 """
702 name = self.choose_relativity(style.origin, style.relativize)
703 if len(name.labels) == 0:
704 return "@"
705 if len(name.labels) == 1 and name.labels[0] == b"":
706 return "."
707 if style.omit_final_dot and name.is_absolute():
708 l = name.labels[:-1]
709 else:
710 l = name.labels
711 if style.idna_codec is None:
712 return ".".join(map(_escapify, l))
713 else:
714 return ".".join([style.idna_codec.decode(x) for x in l])
716 def to_digestable(self, origin: "Name | None" = None) -> bytes:
717 """Convert name to a format suitable for digesting in hashes.
719 The name is canonicalized and converted to uncompressed wire
720 format. All names in wire format are absolute. If the name
721 is a relative name, then an origin must be supplied.
723 :param origin: If the name is relative and *origin* is not ``None``,
724 then *origin* will be appended to the name.
725 :type origin: :py:class:`dns.name.Name` or ``None``
726 :raises dns.name.NeedAbsoluteNameOrOrigin: if the name is relative
727 and no origin was provided.
728 :rtype: bytes
729 """
731 digest = self.to_wire(origin=origin, canonicalize=True)
732 assert digest is not None
733 return digest
735 def to_wire(
736 self,
737 file: Any | None = None,
738 compress: CompressType | None = None,
739 origin: "Name | None" = None,
740 canonicalize: bool = False,
741 ) -> bytes | None:
742 """Convert name to wire format, possibly compressing it.
744 :param file: The file where the name is emitted (typically an
745 ``io.BytesIO`` file). If ``None`` (the default), a ``bytes``
746 containing the wire name will be returned.
747 :param compress: The compression table to use. If ``None`` (the
748 default), names will not be compressed. Note that the compression
749 code assumes that compression offset 0 is the start of *file*,
750 and thus compression will not be correct if this is not the case.
751 :type compress: dict or ``None``
752 :param origin: If the name is relative and *origin* is not ``None``,
753 then *origin* will be appended to it.
754 :type origin: :py:class:`dns.name.Name` or ``None``
755 :param bool canonicalize: Whether the name should be canonicalized;
756 that is, converted to a format suitable for digesting in hashes.
757 :raises dns.name.NeedAbsoluteNameOrOrigin: if the name is relative
758 and no origin was provided.
759 :returns: ``None`` if *file* is provided, otherwise the wire format
760 as ``bytes``.
761 :rtype: bytes or ``None``
762 """
764 if file is None:
765 out = bytearray()
766 for label in self.labels:
767 out.append(len(label))
768 if canonicalize:
769 out += label.lower()
770 else:
771 out += label
772 if not self.is_absolute():
773 if origin is None or not origin.is_absolute():
774 raise NeedAbsoluteNameOrOrigin
775 for label in origin.labels:
776 out.append(len(label))
777 if canonicalize:
778 out += label.lower()
779 else:
780 out += label
781 return bytes(out)
783 labels: Iterable[bytes]
784 if not self.is_absolute():
785 if origin is None or not origin.is_absolute():
786 raise NeedAbsoluteNameOrOrigin
787 labels = list(self.labels)
788 labels.extend(list(origin.labels))
789 else:
790 labels = self.labels
791 i = 0
792 for label in labels:
793 n = Name(labels[i:])
794 i += 1
795 if compress is not None:
796 pos = compress.get(n)
797 else:
798 pos = None
799 if pos is not None:
800 value = 0xC000 + pos
801 s = struct.pack("!H", value)
802 file.write(s)
803 break
804 else:
805 if compress is not None and len(n) > 1:
806 pos = file.tell()
807 if pos <= 0x3FFF:
808 compress[n] = pos
809 l = len(label)
810 file.write(struct.pack("!B", l))
811 if l > 0:
812 if canonicalize:
813 file.write(label.lower())
814 else:
815 file.write(label)
816 return None
818 def __len__(self) -> int:
819 """The length of the name (in labels).
821 :rtype: int
822 """
824 return len(self.labels)
826 def __getitem__(self, index: Any) -> Any:
827 return self.labels[index]
829 def __add__(self, other):
830 return self.concatenate(other)
832 def __sub__(self, other):
833 return self.relativize(other)
835 def split(self, depth: int) -> tuple["Name", "Name"]:
836 """Split a name into a prefix and suffix names at the specified depth.
838 :param int depth: The number of labels in the suffix.
839 :raises ValueError: if *depth* is not >= 0 and <= the length of the
840 name.
841 :returns: A ``(prefix, suffix)`` tuple.
842 :rtype: tuple[:py:class:`dns.name.Name`, :py:class:`dns.name.Name`]
843 """
845 l = len(self.labels)
846 if depth == 0:
847 return (self, empty)
848 elif depth == l:
849 return (empty, self)
850 elif depth < 0 or depth > l:
851 raise ValueError("depth must be >= 0 and <= the length of the name")
852 return (Name(self[:-depth]), Name(self[-depth:]))
854 def concatenate(self, other: "Name") -> "Name":
855 """Return a new name which is the concatenation of self and other.
857 :param other: The name to concatenate.
858 :type other: :py:class:`dns.name.Name`
859 :raises dns.name.AbsoluteConcatenation: if the name is absolute and
860 *other* is not the empty name.
861 :rtype: :py:class:`dns.name.Name`
862 """
864 if self.is_absolute() and len(other) > 0:
865 raise AbsoluteConcatenation
866 labels = list(self.labels)
867 labels.extend(list(other.labels))
868 return Name(labels)
870 def relativize(self, origin: "Name") -> "Name":
871 """If the name is a subdomain of *origin*, return a new name which is
872 the name relative to origin. Otherwise return the name.
874 For example, relativizing ``www.dnspython.org.`` to origin
875 ``dnspython.org.`` returns the name ``www``. Relativizing ``example.``
876 to origin ``dnspython.org.`` returns ``example.``.
878 :param origin: The origin to relativize against.
879 :type origin: :py:class:`dns.name.Name`
880 :rtype: :py:class:`dns.name.Name`
881 """
883 if self.is_subdomain(origin):
884 return Name(self[: -len(origin)])
885 else:
886 return self
888 def derelativize(self, origin: "Name") -> "Name":
889 """If the name is a relative name, return a new name which is the
890 concatenation of the name and origin. Otherwise return the name.
892 For example, derelativizing ``www`` to origin ``dnspython.org.``
893 returns the name ``www.dnspython.org.``. Derelativizing ``example.``
894 to origin ``dnspython.org.`` returns ``example.``.
896 :param origin: The origin to append.
897 :type origin: :py:class:`dns.name.Name`
898 :rtype: :py:class:`dns.name.Name`
899 """
901 if not self.is_absolute():
902 return self.concatenate(origin)
903 else:
904 return self
906 def choose_relativity(
907 self, origin: "Name | None" = None, relativize: bool = True
908 ) -> "Name":
909 """Return a name with the relativity desired by the caller.
911 If *origin* is ``None``, then the name is returned.
912 Otherwise, if *relativize* is ``True`` the name is
913 relativized, and if *relativize* is ``False`` the name is
914 derelativized.
916 :param origin: If not ``None``, controls relativization.
917 :type origin: :py:class:`dns.name.Name` or ``None``
918 :param bool relativize: If ``True``, relativize; if ``False``,
919 derelativize.
920 :rtype: :py:class:`dns.name.Name`
921 """
923 if origin:
924 if relativize:
925 return self.relativize(origin)
926 else:
927 return self.derelativize(origin)
928 else:
929 return self
931 def parent(self) -> "Name":
932 """Return the parent of the name.
934 For example, the parent of ``www.dnspython.org.`` is ``dnspython.org.``.
936 :raises dns.name.NoParent: if the name is either the root name or the
937 empty name, and thus has no parent.
938 :rtype: :py:class:`dns.name.Name`
939 """
941 if self == root or self == empty:
942 raise NoParent
943 return Name(self.labels[1:])
945 def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
946 """Return the maximal predecessor of the name in the DNSSEC ordering.
948 Returns the maximal predecessor in the zone whose origin is *origin*,
949 or returns the longest name under *origin* if the name is *origin*
950 (i.e. wraps around to the longest name, which may still be *origin*
951 due to length considerations).
953 The relativity of the name is preserved, so if this name is relative
954 then the method will return a relative name, and likewise if this name
955 is absolute then the predecessor will be absolute.
957 :param origin: The zone origin.
958 :type origin: :py:class:`dns.name.Name`
959 :param bool prefix_ok: If ``True`` (the default), prefixing labels is
960 allowed. Specify ``False`` when computing a maximal predecessor
961 at a zone cut point.
962 :rtype: :py:class:`dns.name.Name`
963 """
964 return _handle_relativity_and_call(
965 _absolute_predecessor, self, origin, prefix_ok
966 )
968 def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
969 """Return the minimal successor of the name in the DNSSEC ordering.
971 Returns the minimal successor in the zone whose origin is *origin*,
972 or returns *origin* if the successor cannot be computed due to name
973 length limitations.
975 Note that *origin* is returned in the "too long" cases because wrapping
976 around to the origin is how NSEC records express "end of the zone".
978 The relativity of the name is preserved, so if this name is relative
979 then the method will return a relative name, and likewise if this name
980 is absolute then the successor will be absolute.
982 :param origin: The zone origin.
983 :type origin: :py:class:`dns.name.Name`
984 :param bool prefix_ok: If ``True`` (the default), prefixing a new
985 minimal label is allowed. Specify ``False`` when computing a
986 minimal successor at a zone cut point.
987 :rtype: :py:class:`dns.name.Name`
988 """
989 return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok)
992#: The root name, '.'
993root = Name([b""])
995#: The empty name.
996empty = Name([])
999def from_unicode(
1000 text: str, origin: Name | None = root, idna_codec: IDNACodec | None = None
1001) -> Name:
1002 """Convert unicode text into a :py:class:`dns.name.Name` object.
1004 Labels are encoded in IDN ACE form according to rules specified by
1005 the IDNA codec.
1007 :param str text: The text to convert into a name.
1008 :param origin: The origin to append to non-absolute names. The
1009 default is the root name.
1010 :type origin: :py:class:`dns.name.Name` or ``None``
1011 :param idna_codec: The IDNA encoder/decoder. If ``None``, the default
1012 IDNA encoder/decoder is used.
1013 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
1014 :rtype: :py:class:`dns.name.Name`
1015 """
1017 labels = []
1018 label = ""
1019 escaping = False
1020 edigits = 0
1021 total = 0
1022 if idna_codec is None:
1023 idna_codec = IDNA_DEFAULT
1024 if text == "@":
1025 text = ""
1026 if text:
1027 if text in [".", "\u3002", "\uff0e", "\uff61"]:
1028 return Name([b""]) # no Unicode "u" on this constant!
1029 for c in text:
1030 if escaping:
1031 if edigits == 0:
1032 if dns._text_util.is_ascii_digit(c):
1033 total = int(c)
1034 edigits += 1
1035 else:
1036 label += c
1037 escaping = False
1038 else:
1039 if not dns._text_util.is_ascii_digit(c):
1040 raise BadEscape
1041 total *= 10
1042 total += int(c)
1043 edigits += 1
1044 if edigits == 3:
1045 if total > 255:
1046 raise BadEscape
1047 escaping = False
1048 label += chr(total)
1049 elif c in [".", "\u3002", "\uff0e", "\uff61"]:
1050 if len(label) == 0:
1051 raise EmptyLabel
1052 labels.append(idna_codec.encode(label))
1053 label = ""
1054 elif c == "\\":
1055 escaping = True
1056 edigits = 0
1057 total = 0
1058 else:
1059 label += c
1060 if escaping:
1061 raise BadEscape
1062 if len(label) > 0:
1063 labels.append(idna_codec.encode(label))
1064 else:
1065 labels.append(b"")
1067 if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
1068 labels.extend(list(origin.labels))
1069 return Name(labels)
1072def is_all_ascii(text: str) -> bool:
1073 for c in text:
1074 if ord(c) > 0x7F:
1075 return False
1076 return True
1079def from_text(
1080 text: bytes | str,
1081 origin: Name | None = root,
1082 idna_codec: IDNACodec | None = None,
1083) -> Name:
1084 """Convert text into a :py:class:`dns.name.Name` object.
1086 :param text: The text to convert into a name.
1087 :type text: bytes or str
1088 :param origin: The origin to append to non-absolute names. The
1089 default is the root name.
1090 :type origin: :py:class:`dns.name.Name` or ``None``
1091 :param idna_codec: The IDNA encoder/decoder. If ``None``, the default
1092 IDNA encoder/decoder is used.
1093 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
1094 :rtype: :py:class:`dns.name.Name`
1095 """
1097 if isinstance(text, str):
1098 if not is_all_ascii(text):
1099 # Some codepoint in the input text is > 127, so IDNA applies.
1100 return from_unicode(text, origin, idna_codec)
1101 # The input is all ASCII, so treat this like an ordinary non-IDNA
1102 # domain name. Note that "all ASCII" is about the input text,
1103 # not the codepoints in the domain name. E.g. if text has value
1104 #
1105 # r'\150\151\152\153\154\155\156\157\158\159'
1106 #
1107 # then it's still "all ASCII" even though the domain name has
1108 # codepoints > 127.
1109 text = text.encode("ascii")
1110 labels = []
1111 # A bytearray, as appending to bytes copies the label each time.
1112 label = bytearray()
1113 escaping = False
1114 edigits = 0
1115 total = 0
1116 if text == b"@":
1117 text = b""
1118 if text:
1119 if text == b".":
1120 return Name([b""])
1121 if isinstance(text, bytes) and b"\\" not in text:
1122 # No escapes, so the labels are just the text split at the dots.
1123 labels = text.split(b".")
1124 if b"" in labels[:-1]:
1125 raise EmptyLabel
1126 if labels[-1] != b"" and origin is not None:
1127 labels.extend(origin.labels)
1128 return Name(labels)
1129 for c in text:
1130 if escaping:
1131 if edigits == 0:
1132 if _ZERO_VALUE <= c <= _NINE_VALUE:
1133 total = c - _ZERO_VALUE
1134 edigits += 1
1135 else:
1136 label.append(c)
1137 escaping = False
1138 else:
1139 if not _ZERO_VALUE <= c <= _NINE_VALUE:
1140 raise BadEscape
1141 total *= 10
1142 total += c - _ZERO_VALUE
1143 edigits += 1
1144 if edigits == 3:
1145 if total > 255:
1146 raise BadEscape
1147 escaping = False
1148 label.append(total)
1149 elif c == _PERIOD_VALUE:
1150 if len(label) == 0:
1151 raise EmptyLabel
1152 labels.append(bytes(label))
1153 label = bytearray()
1154 elif c == _BACKSLASH_VALUE:
1155 escaping = True
1156 edigits = 0
1157 total = 0
1158 else:
1159 label.append(c)
1160 if escaping:
1161 raise BadEscape
1162 if len(label) > 0:
1163 labels.append(bytes(label))
1164 else:
1165 labels.append(b"")
1166 if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
1167 labels.extend(list(origin.labels))
1168 return Name(labels)
1171MAX_COMPRESSION_POINTER_CHAIN = 16
1173# A Note on Decompressability
1174#
1175# Dnspython used to be generous about decompression, being willing to decompress
1176# any name. To reduce algorithmic complexity attacks, dnspython now is strict about
1177# where compression is permissible. This policy is applied in the individual
1178# rdata parsers, and by having dns.wire.Parser.get_name() disallow compression by
1179# default (a breaking change for code which directly calls get_name()).
1180#
1181# For the record, here are the rules enforced in the library, which is the policy
1182# specified in RFC 3597:
1183#
1184# All owner names may be compressed and decompressed.
1185#
1186# Names in the original types that are not obsolete, namely CNAME, MX, NS, PTR,
1187# and SOA are compressed in wire format and thus may be decompressed too.
1188#
1189# Names in types RP, AFSDB, RT, SIG, PX, NXT, NAPTR, and SRV will not be
1190# compressed by dnspython, but MAY be compressed when decoding wire format.
1191#
1192# Names in all other types will not be compressed by dnspython, and MUST NOT
1193# be compressed when decoding wire format.
1196def from_wire_parser(parser: dns.wirebase.Parser, decompress: bool = True) -> Name:
1197 """Convert possibly compressed wire format into a :py:class:`dns.name.Name`.
1199 :param parser: The wire format parser.
1200 :type parser: :py:class:`dns.wirebase.Parser`
1201 :param decompress: Is decompression allowed?
1202 :type decompress: bool
1203 :raises dns.name.BadPointer: if a compression pointer did not
1204 point backwards in the message.
1205 :raises dns.name.BadLabelType: if an invalid label type was encountered.
1206 :raises dns.name.DecompressionForbidden: if a name needs decompression but it is
1207 not allowed.
1208 :rtype: :py:class:`dns.name.Name`
1209 """
1211 labels = []
1212 biggest_pointer = parser.current
1213 hops = 0
1214 with parser.restore_furthest():
1215 start = parser.current
1216 count = parser.get_uint8()
1217 while count != 0:
1218 if count < 64:
1219 labels.append(parser.get_bytes(count))
1220 elif count >= 192:
1221 # Are compressed names allowed at all?
1222 if not decompress:
1223 raise DecompressionForbidden
1224 # For sanity, compression pointers must point backwards.
1225 current = (count & 0x3F) * 256 + parser.get_uint8()
1226 if current >= biggest_pointer:
1227 raise BadPointer
1228 biggest_pointer = current
1229 hops += 1
1230 if hops > MAX_COMPRESSION_POINTER_CHAIN:
1231 raise PointerChainTooLong
1232 # For sanity, the entire compression target must not overlap
1233 # with any part of this name.
1234 parser.restrict_end(start)
1235 parser.seek(current)
1236 start = current
1237 else:
1238 raise BadLabelType
1239 count = parser.get_uint8()
1240 labels.append(b"")
1241 return Name(labels)
1244def from_wire(message: bytes, current: int) -> tuple[Name, int]:
1245 """Convert possibly compressed wire format into a :py:class:`dns.name.Name`.
1247 :param bytes message: A ``bytes`` containing an entire DNS message in DNS
1248 wire form.
1249 :param int current: The offset of the beginning of the name from the
1250 start of the message.
1251 :raises dns.name.BadPointer: if a compression pointer did not
1252 point backwards in the message.
1253 :raises dns.name.BadLabelType: if an invalid label type was encountered.
1254 :returns: A tuple of the name that was read and the number of bytes of
1255 the wire format message which were consumed reading it.
1256 :rtype: tuple[:py:class:`dns.name.Name`, int]
1257 """
1259 parser = dns.wirebase.Parser(message, current)
1260 name = from_wire_parser(parser)
1261 return (name, parser.current - current)
1264# RFC 4471 Support
1266_MINIMAL_OCTET = b"\x00"
1267_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET)
1268_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET])
1269_MAXIMAL_OCTET = b"\xff"
1270_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET)
1271_AT_SIGN_VALUE = ord("@")
1272_LEFT_SQUARE_BRACKET_VALUE = ord("[")
1275def _wire_length(labels):
1276 return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0)
1279def _pad_to_max_name(name):
1280 needed = 255 - _wire_length(name.labels)
1281 new_labels = []
1282 while needed > 64:
1283 new_labels.append(_MAXIMAL_OCTET * 63)
1284 needed -= 64
1285 if needed >= 2:
1286 new_labels.append(_MAXIMAL_OCTET * (needed - 1))
1287 # Note we're already maximal in the needed == 1 case as while we'd like
1288 # to add one more byte as a new label, we can't, as adding a new non-empty
1289 # label requires at least 2 bytes.
1290 new_labels = list(reversed(new_labels))
1291 new_labels.extend(name.labels)
1292 return Name(new_labels)
1295def _pad_to_max_label(label, suffix_labels):
1296 length = len(label)
1297 # We have to subtract one here to account for the length byte of label.
1298 remaining = 255 - _wire_length(suffix_labels) - length - 1
1299 if remaining <= 0:
1300 # Shouldn't happen!
1301 return label
1302 needed = min(63 - length, remaining)
1303 return label + _MAXIMAL_OCTET * needed
1306def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name:
1307 # This is the RFC 4471 predecessor algorithm using the "absolute method" of section
1308 # 3.1.1.
1309 #
1310 # Our caller must ensure that the name and origin are absolute, and that name is a
1311 # subdomain of origin.
1312 if name == origin:
1313 return _pad_to_max_name(name)
1314 least_significant_label = name[0]
1315 if least_significant_label == _MINIMAL_OCTET:
1316 return name.parent()
1317 least_octet = least_significant_label[-1]
1318 suffix_labels = name.labels[1:]
1319 if least_octet == _MINIMAL_OCTET_VALUE:
1320 new_labels = [least_significant_label[:-1]]
1321 else:
1322 octets = bytearray(least_significant_label)
1323 octet = octets[-1]
1324 if octet == _LEFT_SQUARE_BRACKET_VALUE:
1325 octet = _AT_SIGN_VALUE
1326 else:
1327 octet -= 1
1328 octets[-1] = octet
1329 least_significant_label = bytes(octets)
1330 new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)]
1331 new_labels.extend(suffix_labels)
1332 name = Name(new_labels)
1333 if prefix_ok:
1334 return _pad_to_max_name(name)
1335 else:
1336 return name
1339def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name:
1340 # This is the RFC 4471 successor algorithm using the "absolute method" of section
1341 # 3.1.2.
1342 #
1343 # Our caller must ensure that the name and origin are absolute, and that name is a
1344 # subdomain of origin.
1345 if prefix_ok:
1346 # Try prefixing \000 as new label
1347 try:
1348 return _SUCCESSOR_PREFIX.concatenate(name)
1349 except NameTooLong:
1350 pass
1351 while name != origin:
1352 # Try extending the least significant label.
1353 least_significant_label = name[0]
1354 if len(least_significant_label) < 63:
1355 # We may be able to extend the least label with a minimal additional byte.
1356 # This is only "may" because we could have a maximal length name even though
1357 # the least significant label isn't maximally long.
1358 new_labels = [least_significant_label + _MINIMAL_OCTET]
1359 new_labels.extend(name.labels[1:])
1360 try:
1361 return Name(new_labels)
1362 except NameTooLong:
1363 pass
1364 # We can't extend the label either, so we'll try to increment the least
1365 # signficant non-maximal byte in it.
1366 octets = bytearray(least_significant_label)
1367 # We do this reversed iteration with an explicit indexing variable because
1368 # if we find something to increment, we're going to want to truncate everything
1369 # to the right of it.
1370 for i in range(len(octets) - 1, -1, -1):
1371 octet = octets[i]
1372 if octet == _MAXIMAL_OCTET_VALUE:
1373 # We can't increment this, so keep looking.
1374 continue
1375 # Finally, something we can increment. We have to apply a special rule for
1376 # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when
1377 # comparing names, uppercase letters compare as if they were their
1378 # lower-case equivalents. If we increment "@" to "A", then it would compare
1379 # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have
1380 # skipped the most minimal successor, namely "[".
1381 if octet == _AT_SIGN_VALUE:
1382 octet = _LEFT_SQUARE_BRACKET_VALUE
1383 else:
1384 octet += 1
1385 octets[i] = octet
1386 # We can now truncate all of the maximal values we skipped (if any)
1387 new_labels = [bytes(octets[: i + 1])]
1388 new_labels.extend(name.labels[1:])
1389 # We haven't changed the length of the name, so the Name constructor will
1390 # always work.
1391 return Name(new_labels)
1392 # We couldn't increment, so chop off the least significant label and try
1393 # again.
1394 name = name.parent()
1396 # We couldn't increment at all, so return the origin, as wrapping around is the
1397 # DNSSEC way.
1398 return origin
1401def _handle_relativity_and_call(
1402 function: Callable[[Name, Name, bool], Name],
1403 name: Name,
1404 origin: Name,
1405 prefix_ok: bool,
1406) -> Name:
1407 # Make "name" absolute if needed, ensure that the origin is absolute,
1408 # call function(), and then relativize the result if needed.
1409 if not origin.is_absolute():
1410 raise NeedAbsoluteNameOrOrigin
1411 relative = not name.is_absolute()
1412 if relative:
1413 name = name.derelativize(origin)
1414 elif not name.is_subdomain(origin):
1415 raise NeedSubdomainOfOrigin
1416 result_name = function(name, origin, prefix_ok)
1417 if relative:
1418 result_name = result_name.relativize(origin)
1419 return result_name