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 = '"().;\\@$。.。'
160def _escapify(label: bytes | str) -> str:
161 """Escape the characters in label which need it.
163 :returns: the escaped string
164 :rtype: str
165 """
166 if isinstance(label, bytes):
167 # Ordinary DNS label mode. Escape special characters and values
168 # < 0x20 or > 0x7f.
169 text = ""
170 for c in label:
171 if c in _escaped:
172 text += "\\" + chr(c)
173 elif c > 0x20 and c < 0x7F:
174 text += chr(c)
175 else:
176 text += f"\\{c:03d}"
177 return text
179 # Unicode label mode. Escape only special characters and control
180 # characters, i.e. values <= 0x20 and the DEL and C1 range 0x7f-0x9f.
181 text = ""
182 for uc in label:
183 if uc in _escaped_text:
184 text += "\\" + uc
185 elif uc <= "\x20" or "\x7f" <= uc <= "\x9f":
186 text += f"\\{ord(uc):03d}"
187 else:
188 text += uc
189 return text
192class IDNACodec:
193 """Abstract base class for IDNA encoder/decoders."""
195 def __init__(self):
196 pass
198 def is_idna(self, label: bytes) -> bool:
199 return label.lower().startswith(b"xn--")
201 def encode(self, label: str) -> bytes:
202 raise NotImplementedError # pragma: no cover
204 def decode(self, label: bytes) -> str:
205 # We do not apply any IDNA policy on decode.
206 if self.is_idna(label):
207 try:
208 slabel = label[4:].decode("punycode")
209 except Exception as e:
210 raise IDNAException(idna_exception=e)
211 # An A-label encodes a U-label, which has at least one non-ASCII
212 # character. Otherwise e.g. "xn--www-" would decode to "www" and
213 # the name would display as a different one.
214 if is_all_ascii(slabel):
215 raise IDNAException(
216 idna_exception=f"{label!r} does not decode to a U-label"
217 )
218 return _escapify(slabel)
219 else:
220 return _escapify(label)
223class IDNA2003Codec(IDNACodec):
224 """IDNA 2003 encoder/decoder."""
226 def __init__(self, strict_decode: bool = False):
227 """Initialize the IDNA 2003 encoder/decoder.
229 :param bool strict_decode: If ``True``, then IDNA2003 checking
230 is done when decoding. This can cause failures if the name
231 was encoded with IDNA2008. The default is ``False``.
232 """
234 super().__init__()
235 self.strict_decode = strict_decode
237 def encode(self, label: str) -> bytes:
238 """Encode *label*."""
240 if label == "":
241 return b""
242 try:
243 return encodings.idna.ToASCII(label)
244 except UnicodeError:
245 raise LabelTooLong
247 def decode(self, label: bytes) -> str:
248 """Decode *label*."""
249 if not self.strict_decode:
250 return super().decode(label)
251 if label == b"":
252 return ""
253 try:
254 return _escapify(encodings.idna.ToUnicode(label))
255 except Exception as e:
256 raise IDNAException(idna_exception=e)
259class IDNA2008Codec(IDNACodec):
260 """IDNA 2008 encoder/decoder."""
262 def __init__(
263 self,
264 uts_46: bool = False,
265 transitional: bool = False,
266 allow_pure_ascii: bool = False,
267 strict_decode: bool = False,
268 ):
269 """Initialize the IDNA 2008 encoder/decoder.
271 :param bool uts_46: If ``True``, apply Unicode IDNA compatibility
272 processing as described in Unicode Technical Standard #46
273 (https://unicode.org/reports/tr46/). If ``False``, do not
274 apply the mapping. The default is ``False``.
275 :param bool transitional: If ``True``, use the "transitional" mode
276 described in Unicode Technical Standard #46. The default is
277 ``False``. This setting has no effect in idna 3.11 and later
278 as transitional support has been removed.
279 :param bool allow_pure_ascii: If ``True``, then a label which
280 consists of only ASCII characters is allowed. This is less
281 strict than regular IDNA 2008, but is also necessary for mixed
282 names, e.g. a name starting with ``_sip._tcp.`` and ending
283 in an IDN suffix which would otherwise be disallowed. The
284 default is ``False``.
285 :param bool strict_decode: If ``True``, then IDNA2008 checking
286 is done when decoding. This can cause failures if the name
287 was encoded with IDNA2003. The default is ``False``.
288 """
289 super().__init__()
290 self.uts_46 = uts_46
291 self.transitional = transitional
292 self.allow_pure_ascii = allow_pure_ascii
293 self.strict_decode = strict_decode
295 def encode(self, label: str) -> bytes:
296 if label == "":
297 return b""
298 if self.allow_pure_ascii and is_all_ascii(label):
299 encoded = label.encode("ascii")
300 if len(encoded) > 63:
301 raise LabelTooLong
302 return encoded
303 if not have_idna_2008:
304 raise NoIDNA2008
305 try:
306 if self.uts_46:
307 # pylint: disable=possibly-used-before-assignment
308 label = idna.uts46_remap(label, False, self.transitional)
309 return idna.alabel(label)
310 except idna.IDNAError as e:
311 if e.args[0] == "Label too long":
312 raise LabelTooLong
313 else:
314 raise IDNAException(idna_exception=e)
316 def decode(self, label: bytes) -> str:
317 if not self.strict_decode:
318 return super().decode(label)
319 if label == b"":
320 return ""
321 if not have_idna_2008:
322 raise NoIDNA2008
323 try:
324 ulabel = idna.ulabel(label)
325 if self.uts_46:
326 ulabel = idna.uts46_remap(ulabel, False, self.transitional)
327 return _escapify(ulabel)
328 except (idna.IDNAError, UnicodeError) as e:
329 raise IDNAException(idna_exception=e)
332IDNA_2003_Practical = IDNA2003Codec(False)
333IDNA_2003_Strict = IDNA2003Codec(True)
334IDNA_2003 = IDNA_2003_Practical
335IDNA_2008_Practical = IDNA2008Codec(True, False, True, False)
336IDNA_2008_UTS_46 = IDNA2008Codec(True, False, False, False)
337IDNA_2008_Strict = IDNA2008Codec(False, False, False, True)
338IDNA_2008_Transitional = IDNA2008Codec(True, True, False, False)
339IDNA_2008 = IDNA_2008_Practical
340if have_idna_2008:
341 IDNA_DEFAULT = IDNA_2008_Practical
342else:
343 IDNA_DEFAULT = IDNA_2003_Practical
346def set_default_idna_codec(idna_codec: IDNACodec):
347 """Set the default IDNA codec."""
348 global IDNA_DEFAULT
349 IDNA_DEFAULT = idna_codec
352def _validate_labels(labels: tuple[bytes, ...]) -> None:
353 """Check for empty labels in the middle of a label sequence,
354 labels that are too long, and for too many labels.
356 :raises dns.name.NameTooLong: if the name as a whole is too long.
357 :raises dns.name.EmptyLabel: if a label is empty (i.e. the root
358 label) and appears in a position other than the end of the label
359 sequence.
360 """
362 l = len(labels)
363 total = 0
364 i = -1
365 j = 0
366 for label in labels:
367 ll = len(label)
368 total += ll + 1
369 if ll > 63:
370 raise LabelTooLong
371 if i < 0 and label == b"":
372 i = j
373 j += 1
374 if total > 255:
375 raise NameTooLong
376 if i >= 0 and i != l - 1:
377 raise EmptyLabel
380def _maybe_convert_to_binary(label: bytes | str) -> bytes:
381 """If label is ``str``, convert it to ``bytes``. If it is already
382 ``bytes`` just return it.
384 """
386 if isinstance(label, bytes):
387 return label
388 else:
389 return label.encode()
392@dataclasses.dataclass(frozen=True)
393class NameStyle(BaseStyle):
394 """Name text styles.
396 :param bool omit_final_dot: If ``True``, don't emit the final dot
397 (denoting the root label) for absolute names. The default is
398 ``False``.
399 :param idna_codec: The IDNA decoder to use. The default is ``None``,
400 which means all text is in the standard DNS zonefile format, i.e.
401 punycode will not be decoded.
402 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
403 :param origin: If ``None`` (the default), the name's relativity is not
404 altered before conversion to text. Otherwise, if *relativize* is
405 ``True`` the name is relativized, and if *relativize* is ``False``
406 the name is derelativized.
407 :type origin: :py:class:`dns.name.Name` or ``None``
408 :param bool relativize: Controls the direction of relativization when
409 *origin* is set.
410 """
412 omit_final_dot: bool = False
413 idna_codec: IDNACodec | None = None
414 origin: "Name | None" = None
415 relativize: bool = False
418@dns.immutable.immutable
419class Name:
420 """A DNS name.
422 The dns.name.Name class represents a DNS name as a tuple of
423 labels. Each label is a ``bytes`` in DNS wire format. Instances
424 of the class are immutable.
425 """
427 __slots__ = ["labels"]
429 def __init__(self, labels: Iterable[bytes | str]):
430 """Initialize a DNS name.
432 :param labels: An iterable whose values are ``str`` or ``bytes``.
433 """
435 blabels = [_maybe_convert_to_binary(x) for x in labels]
436 self.labels = tuple(blabels)
437 _validate_labels(self.labels)
439 def __copy__(self):
440 return Name(self.labels)
442 def __deepcopy__(self, memo):
443 return Name(copy.deepcopy(self.labels, memo))
445 def __getstate__(self):
446 # Names can be pickled
447 return {"labels": self.labels}
449 def __setstate__(self, state):
450 super().__setattr__("labels", state["labels"])
451 _validate_labels(self.labels)
453 def is_absolute(self) -> bool:
454 """Is the most significant label of this name the root label?
456 :rtype: bool
457 """
459 return len(self.labels) > 0 and self.labels[-1] == b""
461 def is_wild(self) -> bool:
462 """Is this name wild? (I.e. Is the least significant label ``'*'``?)
464 :rtype: bool
465 """
467 return len(self.labels) > 0 and self.labels[0] == b"*"
469 def __hash__(self) -> int:
470 """Return a case-insensitive hash of the name.
472 :rtype: int
473 """
475 h = 0
476 for label in self.labels:
477 for c in label.lower():
478 h += (h << 3) + c
479 return h
481 def fullcompare(self, other: "Name") -> tuple[NameRelation, int, int]:
482 """Compare two names, returning a 3-tuple
483 ``(relation, order, nlabels)``.
485 *relation* describes the relationship between the names, and is one
486 of: :py:attr:`dns.name.NameRelation.NONE`,
487 :py:attr:`dns.name.NameRelation.SUPERDOMAIN`,
488 :py:attr:`dns.name.NameRelation.SUBDOMAIN`,
489 :py:attr:`dns.name.NameRelation.EQUAL`, or
490 :py:attr:`dns.name.NameRelation.COMMONANCESTOR`.
492 *order* is < 0 if *self* < *other*, > 0 if *self* > *other*, and ==
493 0 if *self* == *other*. A relative name is always less than an
494 absolute name. If both names have the same relativity, then
495 the DNSSEC order relation is used to order them.
497 *nlabels* is the number of significant labels that the two names
498 have in common.
500 Here are some examples. Names ending in "." are absolute names,
501 those not ending in "." are relative names.
503 ============= ============= =========== ===== =======
504 self other relation order nlabels
505 ============= ============= =========== ===== =======
506 www.example. www.example. equal 0 3
507 www.example. example. subdomain > 0 2
508 example. www.example. superdomain < 0 2
509 example1.com. example2.com. common anc. < 0 2
510 example1 example2. none < 0 0
511 example1. example2 none > 0 0
512 ============= ============= =========== ===== =======
514 :param other: The name to compare with.
515 :type other: :py:class:`dns.name.Name`
516 :returns: A 3-tuple ``(relation, order, nlabels)``.
517 :rtype: tuple[:py:class:`dns.name.NameRelation`, int, int]
518 """
520 sabs = self.is_absolute()
521 oabs = other.is_absolute()
522 if sabs != oabs:
523 if sabs:
524 return (NameRelation.NONE, 1, 0)
525 else:
526 return (NameRelation.NONE, -1, 0)
527 l1 = len(self.labels)
528 l2 = len(other.labels)
529 ldiff = l1 - l2
530 if ldiff < 0:
531 l = l1
532 else:
533 l = l2
535 order = 0
536 nlabels = 0
537 namereln = NameRelation.NONE
538 while l > 0:
539 l -= 1
540 l1 -= 1
541 l2 -= 1
542 label1 = self.labels[l1].lower()
543 label2 = other.labels[l2].lower()
544 if label1 < label2:
545 order = -1
546 if nlabels > 0:
547 namereln = NameRelation.COMMONANCESTOR
548 return (namereln, order, nlabels)
549 elif label1 > label2:
550 order = 1
551 if nlabels > 0:
552 namereln = NameRelation.COMMONANCESTOR
553 return (namereln, order, nlabels)
554 nlabels += 1
555 order = ldiff
556 if ldiff < 0:
557 namereln = NameRelation.SUPERDOMAIN
558 elif ldiff > 0:
559 namereln = NameRelation.SUBDOMAIN
560 else:
561 namereln = NameRelation.EQUAL
562 return (namereln, order, nlabels)
564 def is_subdomain(self, other: "Name") -> bool:
565 """Is self a subdomain of other?
567 Note that the notion of subdomain includes equality, e.g.
568 ``dnspython.org`` is a subdomain of itself.
570 :rtype: bool
571 """
573 nr, _, _ = self.fullcompare(other)
574 if nr == NameRelation.SUBDOMAIN or nr == NameRelation.EQUAL:
575 return True
576 return False
578 def is_superdomain(self, other: "Name") -> bool:
579 """Is self a superdomain of other?
581 Note that the notion of superdomain includes equality, e.g.
582 ``dnspython.org`` is a superdomain of itself.
584 :rtype: bool
585 """
587 nr, _, _ = self.fullcompare(other)
588 if nr == NameRelation.SUPERDOMAIN or nr == NameRelation.EQUAL:
589 return True
590 return False
592 def canonicalize(self) -> "Name":
593 """Return a name which is equal to the current name, but is in
594 DNSSEC canonical form.
596 :rtype: :py:class:`dns.name.Name`
597 """
599 return Name([x.lower() for x in self.labels])
601 def __eq__(self, other):
602 if isinstance(other, Name):
603 return self.fullcompare(other)[1] == 0
604 else:
605 return False
607 def __ne__(self, other):
608 if isinstance(other, Name):
609 return self.fullcompare(other)[1] != 0
610 else:
611 return True
613 def __lt__(self, other):
614 if isinstance(other, Name):
615 return self.fullcompare(other)[1] < 0
616 else:
617 return NotImplemented
619 def __le__(self, other):
620 if isinstance(other, Name):
621 return self.fullcompare(other)[1] <= 0
622 else:
623 return NotImplemented
625 def __ge__(self, other):
626 if isinstance(other, Name):
627 return self.fullcompare(other)[1] >= 0
628 else:
629 return NotImplemented
631 def __gt__(self, other):
632 if isinstance(other, Name):
633 return self.fullcompare(other)[1] > 0
634 else:
635 return NotImplemented
637 def __repr__(self):
638 return "<DNS name " + self.__str__() + ">"
640 def __str__(self):
641 return self.to_text(False)
643 def to_text(
644 self, omit_final_dot: bool = False, style: NameStyle | None = None
645 ) -> str:
646 """Convert name to DNS text format.
648 :param bool omit_final_dot: If ``True``, don't emit the final dot
649 (denoting the root label) for absolute names. The default is
650 ``False``.
651 :param style: If specified, the style overrides the other parameters.
652 :type style: :py:class:`dns.name.NameStyle` or ``None``
653 :rtype: str
654 """
655 if style is None:
656 style = NameStyle(omit_final_dot=omit_final_dot)
657 return self.to_styled_text(style)
659 def to_unicode(
660 self,
661 omit_final_dot: bool = False,
662 idna_codec: IDNACodec | None = None,
663 style: NameStyle | None = None,
664 ) -> str:
665 """Convert name to DNS text format.
667 IDN ACE labels are converted to Unicode using the specified codec.
669 :param bool omit_final_dot: If ``True``, don't emit the final dot
670 (denoting the root label) for absolute names. The default is
671 ``False``.
672 :param idna_codec: The IDNA codec to use for decoding ACE labels.
673 If ``None``, the default IDNA codec is used.
674 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
675 :param style: If specified, the style overrides the other parameters.
676 :type style: :py:class:`dns.name.NameStyle` or ``None``
677 :rtype: str
678 """
679 if idna_codec is None:
680 idna_codec = IDNA_DEFAULT
681 if style is None:
682 style = NameStyle(omit_final_dot=omit_final_dot, idna_codec=idna_codec)
683 return self.to_styled_text(style)
685 def to_styled_text(self, style: NameStyle) -> str:
686 """Convert name to text format, applying the style.
688 See the documentation for :py:class:`dns.name.NameStyle` for a description
689 of the style parameters.
691 :param style: The style to apply.
692 :type style: :py:class:`dns.name.NameStyle`
693 :rtype: str
694 """
696 name = self.choose_relativity(style.origin, style.relativize)
697 if len(name.labels) == 0:
698 return "@"
699 if len(name.labels) == 1 and name.labels[0] == b"":
700 return "."
701 if style.omit_final_dot and name.is_absolute():
702 l = name.labels[:-1]
703 else:
704 l = name.labels
705 if style.idna_codec is None:
706 return ".".join(map(_escapify, l))
707 else:
708 return ".".join([style.idna_codec.decode(x) for x in l])
710 def to_digestable(self, origin: "Name | None" = None) -> bytes:
711 """Convert name to a format suitable for digesting in hashes.
713 The name is canonicalized and converted to uncompressed wire
714 format. All names in wire format are absolute. If the name
715 is a relative name, then an origin must be supplied.
717 :param origin: If the name is relative and *origin* is not ``None``,
718 then *origin* will be appended to the name.
719 :type origin: :py:class:`dns.name.Name` or ``None``
720 :raises dns.name.NeedAbsoluteNameOrOrigin: if the name is relative
721 and no origin was provided.
722 :rtype: bytes
723 """
725 digest = self.to_wire(origin=origin, canonicalize=True)
726 assert digest is not None
727 return digest
729 def to_wire(
730 self,
731 file: Any | None = None,
732 compress: CompressType | None = None,
733 origin: "Name | None" = None,
734 canonicalize: bool = False,
735 ) -> bytes | None:
736 """Convert name to wire format, possibly compressing it.
738 :param file: The file where the name is emitted (typically an
739 ``io.BytesIO`` file). If ``None`` (the default), a ``bytes``
740 containing the wire name will be returned.
741 :param compress: The compression table to use. If ``None`` (the
742 default), names will not be compressed. Note that the compression
743 code assumes that compression offset 0 is the start of *file*,
744 and thus compression will not be correct if this is not the case.
745 :type compress: dict or ``None``
746 :param origin: If the name is relative and *origin* is not ``None``,
747 then *origin* will be appended to it.
748 :type origin: :py:class:`dns.name.Name` or ``None``
749 :param bool canonicalize: Whether the name should be canonicalized;
750 that is, converted to a format suitable for digesting in hashes.
751 :raises dns.name.NeedAbsoluteNameOrOrigin: if the name is relative
752 and no origin was provided.
753 :returns: ``None`` if *file* is provided, otherwise the wire format
754 as ``bytes``.
755 :rtype: bytes or ``None``
756 """
758 if file is None:
759 out = bytearray()
760 for label in self.labels:
761 out.append(len(label))
762 if canonicalize:
763 out += label.lower()
764 else:
765 out += label
766 if not self.is_absolute():
767 if origin is None or not origin.is_absolute():
768 raise NeedAbsoluteNameOrOrigin
769 for label in origin.labels:
770 out.append(len(label))
771 if canonicalize:
772 out += label.lower()
773 else:
774 out += label
775 return bytes(out)
777 labels: Iterable[bytes]
778 if not self.is_absolute():
779 if origin is None or not origin.is_absolute():
780 raise NeedAbsoluteNameOrOrigin
781 labels = list(self.labels)
782 labels.extend(list(origin.labels))
783 else:
784 labels = self.labels
785 i = 0
786 for label in labels:
787 n = Name(labels[i:])
788 i += 1
789 if compress is not None:
790 pos = compress.get(n)
791 else:
792 pos = None
793 if pos is not None:
794 value = 0xC000 + pos
795 s = struct.pack("!H", value)
796 file.write(s)
797 break
798 else:
799 if compress is not None and len(n) > 1:
800 pos = file.tell()
801 if pos <= 0x3FFF:
802 compress[n] = pos
803 l = len(label)
804 file.write(struct.pack("!B", l))
805 if l > 0:
806 if canonicalize:
807 file.write(label.lower())
808 else:
809 file.write(label)
810 return None
812 def __len__(self) -> int:
813 """The length of the name (in labels).
815 :rtype: int
816 """
818 return len(self.labels)
820 def __getitem__(self, index: Any) -> Any:
821 return self.labels[index]
823 def __add__(self, other):
824 return self.concatenate(other)
826 def __sub__(self, other):
827 return self.relativize(other)
829 def split(self, depth: int) -> tuple["Name", "Name"]:
830 """Split a name into a prefix and suffix names at the specified depth.
832 :param int depth: The number of labels in the suffix.
833 :raises ValueError: if *depth* is not >= 0 and <= the length of the
834 name.
835 :returns: A ``(prefix, suffix)`` tuple.
836 :rtype: tuple[:py:class:`dns.name.Name`, :py:class:`dns.name.Name`]
837 """
839 l = len(self.labels)
840 if depth == 0:
841 return (self, empty)
842 elif depth == l:
843 return (empty, self)
844 elif depth < 0 or depth > l:
845 raise ValueError("depth must be >= 0 and <= the length of the name")
846 return (Name(self[:-depth]), Name(self[-depth:]))
848 def concatenate(self, other: "Name") -> "Name":
849 """Return a new name which is the concatenation of self and other.
851 :param other: The name to concatenate.
852 :type other: :py:class:`dns.name.Name`
853 :raises dns.name.AbsoluteConcatenation: if the name is absolute and
854 *other* is not the empty name.
855 :rtype: :py:class:`dns.name.Name`
856 """
858 if self.is_absolute() and len(other) > 0:
859 raise AbsoluteConcatenation
860 labels = list(self.labels)
861 labels.extend(list(other.labels))
862 return Name(labels)
864 def relativize(self, origin: "Name") -> "Name":
865 """If the name is a subdomain of *origin*, return a new name which is
866 the name relative to origin. Otherwise return the name.
868 For example, relativizing ``www.dnspython.org.`` to origin
869 ``dnspython.org.`` returns the name ``www``. Relativizing ``example.``
870 to origin ``dnspython.org.`` returns ``example.``.
872 :param origin: The origin to relativize against.
873 :type origin: :py:class:`dns.name.Name`
874 :rtype: :py:class:`dns.name.Name`
875 """
877 if self.is_subdomain(origin):
878 return Name(self[: -len(origin)])
879 else:
880 return self
882 def derelativize(self, origin: "Name") -> "Name":
883 """If the name is a relative name, return a new name which is the
884 concatenation of the name and origin. Otherwise return the name.
886 For example, derelativizing ``www`` to origin ``dnspython.org.``
887 returns the name ``www.dnspython.org.``. Derelativizing ``example.``
888 to origin ``dnspython.org.`` returns ``example.``.
890 :param origin: The origin to append.
891 :type origin: :py:class:`dns.name.Name`
892 :rtype: :py:class:`dns.name.Name`
893 """
895 if not self.is_absolute():
896 return self.concatenate(origin)
897 else:
898 return self
900 def choose_relativity(
901 self, origin: "Name | None" = None, relativize: bool = True
902 ) -> "Name":
903 """Return a name with the relativity desired by the caller.
905 If *origin* is ``None``, then the name is returned.
906 Otherwise, if *relativize* is ``True`` the name is
907 relativized, and if *relativize* is ``False`` the name is
908 derelativized.
910 :param origin: If not ``None``, controls relativization.
911 :type origin: :py:class:`dns.name.Name` or ``None``
912 :param bool relativize: If ``True``, relativize; if ``False``,
913 derelativize.
914 :rtype: :py:class:`dns.name.Name`
915 """
917 if origin:
918 if relativize:
919 return self.relativize(origin)
920 else:
921 return self.derelativize(origin)
922 else:
923 return self
925 def parent(self) -> "Name":
926 """Return the parent of the name.
928 For example, the parent of ``www.dnspython.org.`` is ``dnspython.org.``.
930 :raises dns.name.NoParent: if the name is either the root name or the
931 empty name, and thus has no parent.
932 :rtype: :py:class:`dns.name.Name`
933 """
935 if self == root or self == empty:
936 raise NoParent
937 return Name(self.labels[1:])
939 def predecessor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
940 """Return the maximal predecessor of the name in the DNSSEC ordering.
942 Returns the maximal predecessor in the zone whose origin is *origin*,
943 or returns the longest name under *origin* if the name is *origin*
944 (i.e. wraps around to the longest name, which may still be *origin*
945 due to length considerations).
947 The relativity of the name is preserved, so if this name is relative
948 then the method will return a relative name, and likewise if this name
949 is absolute then the predecessor will be absolute.
951 :param origin: The zone origin.
952 :type origin: :py:class:`dns.name.Name`
953 :param bool prefix_ok: If ``True`` (the default), prefixing labels is
954 allowed. Specify ``False`` when computing a maximal predecessor
955 at a zone cut point.
956 :rtype: :py:class:`dns.name.Name`
957 """
958 return _handle_relativity_and_call(
959 _absolute_predecessor, self, origin, prefix_ok
960 )
962 def successor(self, origin: "Name", prefix_ok: bool = True) -> "Name":
963 """Return the minimal successor of the name in the DNSSEC ordering.
965 Returns the minimal successor in the zone whose origin is *origin*,
966 or returns *origin* if the successor cannot be computed due to name
967 length limitations.
969 Note that *origin* is returned in the "too long" cases because wrapping
970 around to the origin is how NSEC records express "end of the zone".
972 The relativity of the name is preserved, so if this name is relative
973 then the method will return a relative name, and likewise if this name
974 is absolute then the successor will be absolute.
976 :param origin: The zone origin.
977 :type origin: :py:class:`dns.name.Name`
978 :param bool prefix_ok: If ``True`` (the default), prefixing a new
979 minimal label is allowed. Specify ``False`` when computing a
980 minimal successor at a zone cut point.
981 :rtype: :py:class:`dns.name.Name`
982 """
983 return _handle_relativity_and_call(_absolute_successor, self, origin, prefix_ok)
986#: The root name, '.'
987root = Name([b""])
989#: The empty name.
990empty = Name([])
993def from_unicode(
994 text: str, origin: Name | None = root, idna_codec: IDNACodec | None = None
995) -> Name:
996 """Convert unicode text into a :py:class:`dns.name.Name` object.
998 Labels are encoded in IDN ACE form according to rules specified by
999 the IDNA codec.
1001 :param str text: The text to convert into a name.
1002 :param origin: The origin to append to non-absolute names. The
1003 default is the root name.
1004 :type origin: :py:class:`dns.name.Name` or ``None``
1005 :param idna_codec: The IDNA encoder/decoder. If ``None``, the default
1006 IDNA encoder/decoder is used.
1007 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
1008 :rtype: :py:class:`dns.name.Name`
1009 """
1011 labels = []
1012 label = ""
1013 escaping = False
1014 edigits = 0
1015 total = 0
1016 if idna_codec is None:
1017 idna_codec = IDNA_DEFAULT
1018 if text == "@":
1019 text = ""
1020 if text:
1021 if text in [".", "\u3002", "\uff0e", "\uff61"]:
1022 return Name([b""]) # no Unicode "u" on this constant!
1023 for c in text:
1024 if escaping:
1025 if edigits == 0:
1026 if dns._text_util.is_ascii_digit(c):
1027 total = int(c)
1028 edigits += 1
1029 else:
1030 label += c
1031 escaping = False
1032 else:
1033 if not dns._text_util.is_ascii_digit(c):
1034 raise BadEscape
1035 total *= 10
1036 total += int(c)
1037 edigits += 1
1038 if edigits == 3:
1039 if total > 255:
1040 raise BadEscape
1041 escaping = False
1042 label += chr(total)
1043 elif c in [".", "\u3002", "\uff0e", "\uff61"]:
1044 if len(label) == 0:
1045 raise EmptyLabel
1046 labels.append(idna_codec.encode(label))
1047 label = ""
1048 elif c == "\\":
1049 escaping = True
1050 edigits = 0
1051 total = 0
1052 else:
1053 label += c
1054 if escaping:
1055 raise BadEscape
1056 if len(label) > 0:
1057 labels.append(idna_codec.encode(label))
1058 else:
1059 labels.append(b"")
1061 if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
1062 labels.extend(list(origin.labels))
1063 return Name(labels)
1066def is_all_ascii(text: str) -> bool:
1067 for c in text:
1068 if ord(c) > 0x7F:
1069 return False
1070 return True
1073def from_text(
1074 text: bytes | str,
1075 origin: Name | None = root,
1076 idna_codec: IDNACodec | None = None,
1077) -> Name:
1078 """Convert text into a :py:class:`dns.name.Name` object.
1080 :param text: The text to convert into a name.
1081 :type text: bytes or str
1082 :param origin: The origin to append to non-absolute names. The
1083 default is the root name.
1084 :type origin: :py:class:`dns.name.Name` or ``None``
1085 :param idna_codec: The IDNA encoder/decoder. If ``None``, the default
1086 IDNA encoder/decoder is used.
1087 :type idna_codec: :py:class:`dns.name.IDNACodec` or ``None``
1088 :rtype: :py:class:`dns.name.Name`
1089 """
1091 if isinstance(text, str):
1092 if not is_all_ascii(text):
1093 # Some codepoint in the input text is > 127, so IDNA applies.
1094 return from_unicode(text, origin, idna_codec)
1095 # The input is all ASCII, so treat this like an ordinary non-IDNA
1096 # domain name. Note that "all ASCII" is about the input text,
1097 # not the codepoints in the domain name. E.g. if text has value
1098 #
1099 # r'\150\151\152\153\154\155\156\157\158\159'
1100 #
1101 # then it's still "all ASCII" even though the domain name has
1102 # codepoints > 127.
1103 text = text.encode("ascii")
1104 labels = []
1105 # A bytearray, as appending to bytes copies the label each time.
1106 label = bytearray()
1107 escaping = False
1108 edigits = 0
1109 total = 0
1110 if text == b"@":
1111 text = b""
1112 if text:
1113 if text == b".":
1114 return Name([b""])
1115 for c in text:
1116 byte_ = struct.pack("!B", c)
1117 if escaping:
1118 if edigits == 0:
1119 if byte_.isdigit():
1120 total = int(byte_)
1121 edigits += 1
1122 else:
1123 label += byte_
1124 escaping = False
1125 else:
1126 if not byte_.isdigit():
1127 raise BadEscape
1128 total *= 10
1129 total += int(byte_)
1130 edigits += 1
1131 if edigits == 3:
1132 if total > 255:
1133 raise BadEscape
1134 escaping = False
1135 label += struct.pack("!B", total)
1136 elif byte_ == b".":
1137 if len(label) == 0:
1138 raise EmptyLabel
1139 labels.append(bytes(label))
1140 label = bytearray()
1141 elif byte_ == b"\\":
1142 escaping = True
1143 edigits = 0
1144 total = 0
1145 else:
1146 label += byte_
1147 if escaping:
1148 raise BadEscape
1149 if len(label) > 0:
1150 labels.append(bytes(label))
1151 else:
1152 labels.append(b"")
1153 if (len(labels) == 0 or labels[-1] != b"") and origin is not None:
1154 labels.extend(list(origin.labels))
1155 return Name(labels)
1158MAX_COMPRESSION_POINTER_CHAIN = 16
1160# A Note on Decompressability
1161#
1162# Dnspython used to be generous about decompression, being willing to decompress
1163# any name. To reduce algorithmic complexity attacks, dnspython now is strict about
1164# where compression is permissible. This policy is applied in the individual
1165# rdata parsers, and by having dns.wire.Parser.get_name() disallow compression by
1166# default (a breaking change for code which directly calls get_name()).
1167#
1168# For the record, here are the rules enforced in the library, which is the policy
1169# specified in RFC 3597:
1170#
1171# All owner names may be compressed and decompressed.
1172#
1173# Names in the original types that are not obsolete, namely CNAME, MX, NS, PTR,
1174# and SOA are compressed in wire format and thus may be decompressed too.
1175#
1176# Names in types RP, AFSDB, RT, SIG, PX, NXT, NAPTR, and SRV will not be
1177# compressed by dnspython, but MAY be compressed when decoding wire format.
1178#
1179# Names in all other types will not be compressed by dnspython, and MUST NOT
1180# be compressed when decoding wire format.
1183def from_wire_parser(parser: dns.wirebase.Parser, decompress: bool = True) -> Name:
1184 """Convert possibly compressed wire format into a :py:class:`dns.name.Name`.
1186 :param parser: The wire format parser.
1187 :type parser: :py:class:`dns.wirebase.Parser`
1188 :param decompress: Is decompression allowed?
1189 :type decompress: bool
1190 :raises dns.name.BadPointer: if a compression pointer did not
1191 point backwards in the message.
1192 :raises dns.name.BadLabelType: if an invalid label type was encountered.
1193 :raises dns.name.DecompressionForbidden: if a name needs decompression but it is
1194 not allowed.
1195 :rtype: :py:class:`dns.name.Name`
1196 """
1198 labels = []
1199 biggest_pointer = parser.current
1200 hops = 0
1201 with parser.restore_furthest():
1202 start = parser.current
1203 count = parser.get_uint8()
1204 while count != 0:
1205 if count < 64:
1206 labels.append(parser.get_bytes(count))
1207 elif count >= 192:
1208 # Are compressed names allowed at all?
1209 if not decompress:
1210 raise DecompressionForbidden
1211 # For sanity, compression pointers must point backwards.
1212 current = (count & 0x3F) * 256 + parser.get_uint8()
1213 if current >= biggest_pointer:
1214 raise BadPointer
1215 biggest_pointer = current
1216 hops += 1
1217 if hops > MAX_COMPRESSION_POINTER_CHAIN:
1218 raise PointerChainTooLong
1219 # For sanity, the entire compression target must not overlap
1220 # with any part of this name.
1221 parser.restrict_end(start)
1222 parser.seek(current)
1223 start = current
1224 else:
1225 raise BadLabelType
1226 count = parser.get_uint8()
1227 labels.append(b"")
1228 return Name(labels)
1231def from_wire(message: bytes, current: int) -> tuple[Name, int]:
1232 """Convert possibly compressed wire format into a :py:class:`dns.name.Name`.
1234 :param bytes message: A ``bytes`` containing an entire DNS message in DNS
1235 wire form.
1236 :param int current: The offset of the beginning of the name from the
1237 start of the message.
1238 :raises dns.name.BadPointer: if a compression pointer did not
1239 point backwards in the message.
1240 :raises dns.name.BadLabelType: if an invalid label type was encountered.
1241 :returns: A tuple of the name that was read and the number of bytes of
1242 the wire format message which were consumed reading it.
1243 :rtype: tuple[:py:class:`dns.name.Name`, int]
1244 """
1246 parser = dns.wirebase.Parser(message, current)
1247 name = from_wire_parser(parser)
1248 return (name, parser.current - current)
1251# RFC 4471 Support
1253_MINIMAL_OCTET = b"\x00"
1254_MINIMAL_OCTET_VALUE = ord(_MINIMAL_OCTET)
1255_SUCCESSOR_PREFIX = Name([_MINIMAL_OCTET])
1256_MAXIMAL_OCTET = b"\xff"
1257_MAXIMAL_OCTET_VALUE = ord(_MAXIMAL_OCTET)
1258_AT_SIGN_VALUE = ord("@")
1259_LEFT_SQUARE_BRACKET_VALUE = ord("[")
1262def _wire_length(labels):
1263 return functools.reduce(lambda v, x: v + len(x) + 1, labels, 0)
1266def _pad_to_max_name(name):
1267 needed = 255 - _wire_length(name.labels)
1268 new_labels = []
1269 while needed > 64:
1270 new_labels.append(_MAXIMAL_OCTET * 63)
1271 needed -= 64
1272 if needed >= 2:
1273 new_labels.append(_MAXIMAL_OCTET * (needed - 1))
1274 # Note we're already maximal in the needed == 1 case as while we'd like
1275 # to add one more byte as a new label, we can't, as adding a new non-empty
1276 # label requires at least 2 bytes.
1277 new_labels = list(reversed(new_labels))
1278 new_labels.extend(name.labels)
1279 return Name(new_labels)
1282def _pad_to_max_label(label, suffix_labels):
1283 length = len(label)
1284 # We have to subtract one here to account for the length byte of label.
1285 remaining = 255 - _wire_length(suffix_labels) - length - 1
1286 if remaining <= 0:
1287 # Shouldn't happen!
1288 return label
1289 needed = min(63 - length, remaining)
1290 return label + _MAXIMAL_OCTET * needed
1293def _absolute_predecessor(name: Name, origin: Name, prefix_ok: bool) -> Name:
1294 # This is the RFC 4471 predecessor algorithm using the "absolute method" of section
1295 # 3.1.1.
1296 #
1297 # Our caller must ensure that the name and origin are absolute, and that name is a
1298 # subdomain of origin.
1299 if name == origin:
1300 return _pad_to_max_name(name)
1301 least_significant_label = name[0]
1302 if least_significant_label == _MINIMAL_OCTET:
1303 return name.parent()
1304 least_octet = least_significant_label[-1]
1305 suffix_labels = name.labels[1:]
1306 if least_octet == _MINIMAL_OCTET_VALUE:
1307 new_labels = [least_significant_label[:-1]]
1308 else:
1309 octets = bytearray(least_significant_label)
1310 octet = octets[-1]
1311 if octet == _LEFT_SQUARE_BRACKET_VALUE:
1312 octet = _AT_SIGN_VALUE
1313 else:
1314 octet -= 1
1315 octets[-1] = octet
1316 least_significant_label = bytes(octets)
1317 new_labels = [_pad_to_max_label(least_significant_label, suffix_labels)]
1318 new_labels.extend(suffix_labels)
1319 name = Name(new_labels)
1320 if prefix_ok:
1321 return _pad_to_max_name(name)
1322 else:
1323 return name
1326def _absolute_successor(name: Name, origin: Name, prefix_ok: bool) -> Name:
1327 # This is the RFC 4471 successor algorithm using the "absolute method" of section
1328 # 3.1.2.
1329 #
1330 # Our caller must ensure that the name and origin are absolute, and that name is a
1331 # subdomain of origin.
1332 if prefix_ok:
1333 # Try prefixing \000 as new label
1334 try:
1335 return _SUCCESSOR_PREFIX.concatenate(name)
1336 except NameTooLong:
1337 pass
1338 while name != origin:
1339 # Try extending the least significant label.
1340 least_significant_label = name[0]
1341 if len(least_significant_label) < 63:
1342 # We may be able to extend the least label with a minimal additional byte.
1343 # This is only "may" because we could have a maximal length name even though
1344 # the least significant label isn't maximally long.
1345 new_labels = [least_significant_label + _MINIMAL_OCTET]
1346 new_labels.extend(name.labels[1:])
1347 try:
1348 return Name(new_labels)
1349 except NameTooLong:
1350 pass
1351 # We can't extend the label either, so we'll try to increment the least
1352 # signficant non-maximal byte in it.
1353 octets = bytearray(least_significant_label)
1354 # We do this reversed iteration with an explicit indexing variable because
1355 # if we find something to increment, we're going to want to truncate everything
1356 # to the right of it.
1357 for i in range(len(octets) - 1, -1, -1):
1358 octet = octets[i]
1359 if octet == _MAXIMAL_OCTET_VALUE:
1360 # We can't increment this, so keep looking.
1361 continue
1362 # Finally, something we can increment. We have to apply a special rule for
1363 # incrementing "@", sending it to "[", because RFC 4034 6.1 says that when
1364 # comparing names, uppercase letters compare as if they were their
1365 # lower-case equivalents. If we increment "@" to "A", then it would compare
1366 # as "a", which is after "[", "\", "]", "^", "_", and "`", so we would have
1367 # skipped the most minimal successor, namely "[".
1368 if octet == _AT_SIGN_VALUE:
1369 octet = _LEFT_SQUARE_BRACKET_VALUE
1370 else:
1371 octet += 1
1372 octets[i] = octet
1373 # We can now truncate all of the maximal values we skipped (if any)
1374 new_labels = [bytes(octets[: i + 1])]
1375 new_labels.extend(name.labels[1:])
1376 # We haven't changed the length of the name, so the Name constructor will
1377 # always work.
1378 return Name(new_labels)
1379 # We couldn't increment, so chop off the least significant label and try
1380 # again.
1381 name = name.parent()
1383 # We couldn't increment at all, so return the origin, as wrapping around is the
1384 # DNSSEC way.
1385 return origin
1388def _handle_relativity_and_call(
1389 function: Callable[[Name, Name, bool], Name],
1390 name: Name,
1391 origin: Name,
1392 prefix_ok: bool,
1393) -> Name:
1394 # Make "name" absolute if needed, ensure that the origin is absolute,
1395 # call function(), and then relativize the result if needed.
1396 if not origin.is_absolute():
1397 raise NeedAbsoluteNameOrOrigin
1398 relative = not name.is_absolute()
1399 if relative:
1400 name = name.derelativize(origin)
1401 elif not name.is_subdomain(origin):
1402 raise NeedSubdomainOfOrigin
1403 result_name = function(name, origin, prefix_ok)
1404 if relative:
1405 result_name = result_name.relativize(origin)
1406 return result_name