Debian Codegraph @

ansible_collections/community/dns/plugins/plugin_utils/_public_suffix.py

raw
1 # Copyright (c) 2021, Felix Fontein <[email protected]>
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 plugin 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 os.path
11 import re
12 import typing as t
13
14 from ansible_collections.community.dns.plugins.module_utils._names import (
15 InvalidDomainName,
16 normalize_label,
17 split_into_labels,
18 )
19
20 _BEGIN_SUBSET_MATCHER = re.compile(r"===BEGIN ([^=]*) DOMAINS===")
21 _END_SUBSET_MATCHER = re.compile(r"===END ([^=]*) DOMAINS===")
22
23
24 class PublicSuffixEntry:
25 """
26 Contains a Public Suffix List entry with metadata.
27 """
28
29 def __init__(
30 self,
31 labels: tuple[str, ...],
32 exception_rule: bool = False,
33 part: str | None = None,
34 ) -> None:
35 self.labels = labels
36 self.exception_rule = exception_rule
37 self.part = part
38
39 def matches(self, normalized_labels) -> bool:
40 """
41 Match PSL entry with a given normalized list of labels.
42 """
43 if len(normalized_labels) < len(self.labels):
44 return False
45 for i, label in enumerate(self.labels):
46 normalized_label = normalized_labels[i]
47 if label not in (normalized_label, "*"):
48 return False
49 return True
50
51
52 def select_prevailing_rule(rules: list[PublicSuffixEntry]) -> PublicSuffixEntry:
53 """
54 Given a non-empty set of rules matching a domain name, finds the prevailing rule.
55
56 It uses the algorithm specified on https://publicsuffix.org/list/.
57 """
58 max_length_rule = rules[0]
59 max_length = len(max_length_rule.labels)
60 for rule in rules:
61 if rule.exception_rule:
62 return rule
63 if len(rule.labels) > max_length:
64 max_length = len(rule.labels)
65 max_length_rule = rule
66 return max_length_rule
67
68
69 class PublicSuffixList:
70 """
71 Contains the Public Suffix List.
72 """
73
74 def __init__(self, rules: list[PublicSuffixEntry]) -> None:
75 self._generic_rule = PublicSuffixEntry(("*",))
76 self._rules = sorted(rules, key=lambda entry: entry.labels)
77
78 @classmethod
79 def load(cls, filename: str) -> t.Self:
80 """
81 Load Public Suffix List from the given filename.
82 """
83 rules: list[PublicSuffixEntry] = []
84 part: str | None = None
85 with open(filename, "rb") as content_file:
86 content = content_file.read().decode("utf-8")
87 for line in content.splitlines():
88 line = line.strip()
89 if line.startswith("//") or not line:
90 m = _BEGIN_SUBSET_MATCHER.search(line)
91 if m:
92 part = m.group(1).lower()
93 m = _END_SUBSET_MATCHER.search(line)
94 if m:
95 part = None
96 continue
97 if part is None:
98 raise AssertionError("Internal error: found PSL entry with no part!")
99 exception_rule = False
100 if line.startswith("!"):
101 exception_rule = True
102 line = line[1:]
103 if line.startswith("."):
104 line = line[1:]
105 labels = tuple(
106 normalize_label(label) for label in split_into_labels(line)[0]
107 )
108 rules.append(
109 PublicSuffixEntry(labels, exception_rule=exception_rule, part=part)
110 )
111 return cls(rules)
112
113 def get_suffix_length_and_rule(
114 self, normalized_labels: list[str], icann_only: bool = False
115 ) -> tuple[int, PublicSuffixEntry | None]:
116 """
117 Given a list of normalized labels, searches for a matching rule.
118
119 Returns the tuple ``(suffix_length, rule)``. The ``rule`` is never ``None``
120 except if ``normalized_labels`` is empty, in which case ``(0, None)`` is returned.
121
122 If ``icann_only`` is set to ``True``, only official ICANN rules are used. If
123 ``icann_only`` is ``False`` (default), also private rules are used.
124 """
125 if not normalized_labels:
126 return 0, None
127
128 # Find matching rules
129 rules: list[PublicSuffixEntry] = []
130 for rule in self._rules:
131 if icann_only and rule.part != "icann":
132 continue
133 if rule.matches(normalized_labels):
134 rules.append(rule)
135 if not rules:
136 rules.append(self._generic_rule)
137
138 # Select prevailing rule
139 rule = select_prevailing_rule(rules)
140
141 # Determine suffix
142 suffix_length = len(rule.labels)
143 if rule.exception_rule:
144 suffix_length -= 1
145
146 # Return result
147 return suffix_length, rule
148
149 def get_suffix(
150 self,
151 domain: str,
152 keep_unknown_suffix: bool = True,
153 normalize_result: bool = False,
154 icann_only: bool = False,
155 ) -> str:
156 """
157 Given a domain name, extracts the public suffix.
158
159 If ``keep_unknown_suffix`` is set to ``False``, only suffixes matching explicit
160 entries from the PSL are returned. If ``keep_unknown_suffix`` is ``True`` (default),
161 the implicit ``*`` rule is used if no other rule matches.
162
163 If ``normalize_result`` is set to ``True``, the result is re-combined form the
164 normalized labels. In that case, the result is lower-case ASCII. If
165 ``normalize_result`` is ``False`` (default), the result ``result`` always satisfies
166 ``domain.endswith(result)``.
167
168 If ``icann_only`` is set to ``True``, only official ICANN rules are used. If
169 ``icann_only`` is ``False`` (default), also private rules are used.
170 """
171 # Split into labels and normalize
172 try:
173 labels, tail = split_into_labels(domain)
174 normalized_labels = [normalize_label(label) for label in labels]
175 except InvalidDomainName:
176 return ""
177 if normalize_result:
178 labels = normalized_labels
179
180 # Get suffix length
181 suffix_length, rule = self.get_suffix_length_and_rule(
182 normalized_labels, icann_only=icann_only
183 )
184 if rule is None:
185 return ""
186 if not keep_unknown_suffix and rule is self._generic_rule:
187 return ""
188 return ".".join(reversed(labels[:suffix_length])) + tail
189
190 def get_registrable_domain(
191 self,
192 domain: str,
193 keep_unknown_suffix: bool = True,
194 only_if_registerable: bool = True,
195 normalize_result: bool = False,
196 icann_only: bool = False,
197 ) -> str:
198 """
199 Given a domain name, extracts the registrable domain. This is the public suffix
200 including the last label before the suffix.
201
202 If ``keep_unknown_suffix`` is set to ``False``, only suffixes matching explicit
203 entries from the PSL are returned. If no suffix can be found, ``''`` is returned.
204 If ``keep_unknown_suffix`` is ``True`` (default), the implicit ``*`` rule is used
205 if no other rule matches.
206
207 If ``only_if_registerable`` is set to ``False``, the public suffix is returned
208 if there is no label before the suffix. If ``only_if_registerable`` is ``True``
209 (default), ``''`` is returned in that case.
210
211 If ``normalize_result`` is set to ``True``, the result is re-combined form the
212 normalized labels. In that case, the result is lower-case ASCII. If
213 ``normalize_result`` is ``False`` (default), the result ``result`` always satisfies
214 ``domain.endswith(result)``.
215
216 If ``icann_only`` is set to ``True``, only official ICANN rules are used. If
217 ``icann_only`` is ``False`` (default), also private rules are used.
218 """
219 # Split into labels and normalize
220 try:
221 labels, tail = split_into_labels(domain)
222 normalized_labels = [normalize_label(label) for label in labels]
223 except InvalidDomainName:
224 return ""
225 if normalize_result:
226 labels = normalized_labels
227
228 # Get suffix length
229 suffix_length, rule = self.get_suffix_length_and_rule(
230 normalized_labels, icann_only=icann_only
231 )
232 if rule is None:
233 return ""
234 if not keep_unknown_suffix and rule is self._generic_rule:
235 return ""
236 if suffix_length < len(labels):
237 suffix_length += 1
238 elif only_if_registerable:
239 return ""
240 return ".".join(reversed(labels[:suffix_length])) + tail
241
242
243 # The official Public Suffix List
244 PUBLIC_SUFFIX_LIST = PublicSuffixList.load(
245 os.path.join(os.path.dirname(__file__), "..", "public_suffix_list.dat")
246 )