Debian Codegraph @

ansible_collections/community/dns/plugins/module_utils/_names.py

raw
1 # Copyright (c) 2021 Felix Fontein
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import re
11 import typing as t
12
13 from ansible.module_utils.common.text.converters import to_text
14
15 if t.TYPE_CHECKING:
16 from collections.abc import Sequence # pragma: no cover
17
18 _ASCII_PRINTABLE_MATCHER = re.compile(r"^[\x20-\x7e]*$")
19
20
21 def is_ascii_label(domain: str) -> bool:
22 """
23 Check whether domain name has only ASCII labels.
24 """
25 return _ASCII_PRINTABLE_MATCHER.match(domain) is not None
26
27
28 class InvalidDomainName(Exception):
29 """
30 The provided domain name is not valid.
31 """
32
33
34 def split_into_labels(domain: str) -> tuple[list[str], t.Literal["", "."]]:
35 """
36 Split domain name to a list of labels. Start with the top-most label.
37
38 Returns a list of labels and a tail, which is either ``''`` or ``'.'``.
39 Raises ``InvalidDomainName`` if the domain name is not valid.
40 """
41 result = []
42 index = len(domain)
43 tail: t.Literal["", "."] = ""
44 if domain.endswith("."):
45 index -= 1
46 tail = "."
47 if index > 0:
48 while index >= 0:
49 next_index = domain.rfind(".", 0, index)
50 label = domain[next_index + 1 : index]
51 if label == "" or label[0] == "-" or label[-1] == "-" or len(label) > 63:
52 raise InvalidDomainName(domain)
53 result.append(label)
54 index = next_index
55 return result, tail
56
57
58 def join_labels(labels: Sequence[str], tail: str = "") -> str:
59 """
60 Combines the result of split_into_labels() back into a domain name.
61 """
62 return ".".join(reversed(labels)) + tail
63
64
65 def normalize_label(label: str) -> str:
66 """
67 Normalize a domain label. Returns a lower-case ASCII label.
68
69 If a ulabel is provided, it is converted to an alabel.
70 """
71 if not is_ascii_label(label):
72 # Convert ulabel to alabel
73 label = to_text(b"xn--" + to_text(label).encode("punycode"))
74 # Always convert to lower-case
75 return label.lower()