Debian Codegraph @

dns/rdtypes/util.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc.
4 #
5 # Permission to use, copy, modify, and distribute this software and its
6 # documentation for any purpose with or without fee is hereby granted,
7 # provided that the above copyright notice and this permission notice
8 # appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
18 import collections
19 import random
20 import struct
21 from typing import Any, Iterable, List, Tuple
22
23 import dns.exception
24 import dns.ipv4
25 import dns.ipv6
26 import dns.name
27 import dns.rdata
28 import dns.rdatatype
29 import dns.tokenizer
30 import dns.wire
31
32
33 class Gateway:
34 """A helper class for the IPSECKEY gateway and AMTRELAY relay fields"""
35
36 name = ""
37
38 def __init__(self, type: Any, gateway: str | dns.name.Name | None = None):
39 self.type = dns.rdata.Rdata._as_uint8(type)
40 self.gateway = gateway
41 self._check()
42
43 @classmethod
44 def _invalid_type(cls, gateway_type):
45 return f"invalid {cls.name} type: {gateway_type}"
46
47 def _check(self):
48 if self.type == 0:
49 if self.gateway not in (".", None):
50 raise SyntaxError(f"invalid {self.name} for type 0")
51 self.gateway = None
52 elif self.type == 1:
53 # check that it's OK
54 assert isinstance(self.gateway, str)
55 dns.ipv4.inet_aton(self.gateway)
56 elif self.type == 2:
57 # check that it's OK
58 assert isinstance(self.gateway, str)
59 dns.ipv6.inet_aton(self.gateway)
60 elif self.type == 3:
61 if not isinstance(self.gateway, dns.name.Name):
62 raise SyntaxError(f"invalid {self.name}; not a name")
63 else:
64 raise SyntaxError(self._invalid_type(self.type))
65
66 def to_text(self, origin=None, relativize=True):
67 if self.type == 0:
68 return "."
69 elif self.type in (1, 2):
70 return self.gateway
71 elif self.type == 3:
72 assert isinstance(self.gateway, dns.name.Name)
73 return str(self.gateway.choose_relativity(origin, relativize))
74 else:
75 raise ValueError(self._invalid_type(self.type)) # pragma: no cover
76
77 @classmethod
78 def from_text(
79 cls, gateway_type, tok, origin=None, relativize=True, relativize_to=None
80 ):
81 if gateway_type in (0, 1, 2):
82 gateway = tok.get_string()
83 elif gateway_type == 3:
84 gateway = tok.get_name(origin, relativize, relativize_to)
85 else:
86 raise dns.exception.SyntaxError(
87 cls._invalid_type(gateway_type)
88 ) # pragma: no cover
89 return cls(gateway_type, gateway)
90
91 # pylint: disable=unused-argument
92 def to_wire(self, file, compress=None, origin=None, canonicalize=False):
93 if self.type == 0:
94 pass
95 elif self.type == 1:
96 assert isinstance(self.gateway, str)
97 file.write(dns.ipv4.inet_aton(self.gateway))
98 elif self.type == 2:
99 assert isinstance(self.gateway, str)
100 file.write(dns.ipv6.inet_aton(self.gateway))
101 elif self.type == 3:
102 assert isinstance(self.gateway, dns.name.Name)
103 self.gateway.to_wire(file, None, origin, False)
104 else:
105 raise ValueError(self._invalid_type(self.type)) # pragma: no cover
106
107 # pylint: enable=unused-argument
108
109 @classmethod
110 def from_wire_parser(cls, gateway_type, parser, origin=None):
111 if gateway_type == 0:
112 gateway = None
113 elif gateway_type == 1:
114 gateway = dns.ipv4.inet_ntoa(parser.get_bytes(4))
115 elif gateway_type == 2:
116 gateway = dns.ipv6.inet_ntoa(parser.get_bytes(16))
117 elif gateway_type == 3:
118 gateway = parser.get_name(origin)
119 else:
120 raise dns.exception.FormError(cls._invalid_type(gateway_type))
121 return cls(gateway_type, gateway)
122
123
124 class Bitmap:
125 """A helper class for the NSEC/NSEC3/CSYNC type bitmaps"""
126
127 type_name = ""
128
129 def __init__(self, windows: Iterable[Tuple[int, bytes]] | None = None):
130 last_window = -1
131 if windows is None:
132 windows = []
133 self.windows = windows
134 for window, bitmap in self.windows:
135 if not isinstance(window, int):
136 raise ValueError(f"bad {self.type_name} window type")
137 if window <= last_window:
138 raise ValueError(f"bad {self.type_name} window order")
139 if window > 256:
140 raise ValueError(f"bad {self.type_name} window number")
141 last_window = window
142 if not isinstance(bitmap, bytes):
143 raise ValueError(f"bad {self.type_name} octets type")
144 if len(bitmap) == 0 or len(bitmap) > 32:
145 raise ValueError(f"bad {self.type_name} octets")
146
147 def to_text(self) -> str:
148 text = ""
149 for window, bitmap in self.windows:
150 bits = []
151 for i, byte in enumerate(bitmap):
152 for j in range(0, 8):
153 if byte & (0x80 >> j):
154 rdtype = dns.rdatatype.RdataType.make(window * 256 + i * 8 + j)
155 bits.append(dns.rdatatype.to_text(rdtype))
156 text += " " + " ".join(bits)
157 return text
158
159 @classmethod
160 def from_text(cls, tok: "dns.tokenizer.Tokenizer") -> "Bitmap":
161 rdtypes = []
162 for token in tok.get_remaining():
163 rdtype = dns.rdatatype.from_text(token.unescape().value)
164 if rdtype == 0:
165 raise dns.exception.SyntaxError(f"{cls.type_name} with bit 0")
166 rdtypes.append(rdtype)
167 return cls.from_rdtypes(rdtypes)
168
169 @classmethod
170 def from_rdtypes(cls, rdtypes: List[dns.rdatatype.RdataType]) -> "Bitmap":
171 rdtypes = sorted(rdtypes)
172 window = 0
173 octets = 0
174 prior_rdtype = 0
175 bitmap = bytearray(b"\0" * 32)
176 windows = []
177 for rdtype in rdtypes:
178 if rdtype == prior_rdtype:
179 continue
180 prior_rdtype = rdtype
181 new_window = rdtype // 256
182 if new_window != window:
183 if octets != 0:
184 windows.append((window, bytes(bitmap[0:octets])))
185 bitmap = bytearray(b"\0" * 32)
186 window = new_window
187 offset = rdtype % 256
188 byte = offset // 8
189 bit = offset % 8
190 octets = byte + 1
191 bitmap[byte] = bitmap[byte] | (0x80 >> bit)
192 if octets != 0:
193 windows.append((window, bytes(bitmap[0:octets])))
194 return cls(windows)
195
196 def to_wire(self, file: Any) -> None:
197 for window, bitmap in self.windows:
198 file.write(struct.pack("!BB", window, len(bitmap)))
199 file.write(bitmap)
200
201 @classmethod
202 def from_wire_parser(cls, parser: "dns.wire.Parser") -> "Bitmap":
203 windows = []
204 while parser.remaining() > 0:
205 window = parser.get_uint8()
206 bitmap = parser.get_counted_bytes()
207 windows.append((window, bitmap))
208 return cls(windows)
209
210
211 def _priority_table(items):
212 by_priority = collections.defaultdict(list)
213 for rdata in items:
214 by_priority[rdata._processing_priority()].append(rdata)
215 return by_priority
216
217
218 def priority_processing_order(iterable):
219 items = list(iterable)
220 if len(items) == 1:
221 return items
222 by_priority = _priority_table(items)
223 ordered = []
224 for k in sorted(by_priority.keys()):
225 rdatas = by_priority[k]
226 random.shuffle(rdatas)
227 ordered.extend(rdatas)
228 return ordered
229
230
231 _no_weight = 0.1
232
233
234 def weighted_processing_order(iterable):
235 items = list(iterable)
236 if len(items) == 1:
237 return items
238 by_priority = _priority_table(items)
239 ordered = []
240 for k in sorted(by_priority.keys()):
241 rdatas = by_priority[k]
242 total = sum(rdata._processing_weight() or _no_weight for rdata in rdatas)
243 while len(rdatas) > 1:
244 r = random.uniform(0, total)
245 for n, rdata in enumerate(rdatas): # noqa: B007
246 weight = rdata._processing_weight() or _no_weight
247 if weight > r:
248 break
249 r -= weight
250 total -= weight # pyright: ignore[reportPossiblyUnboundVariable]
251 # pylint: disable=undefined-loop-variable
252 ordered.append(rdata) # pyright: ignore[reportPossiblyUnboundVariable]
253 del rdatas[n] # pyright: ignore[reportPossiblyUnboundVariable]
254 ordered.append(rdatas[0])
255 return ordered
256
257
258 def parse_formatted_hex(formatted, num_chunks, chunk_size, separator):
259 if len(formatted) != num_chunks * (chunk_size + 1) - 1:
260 raise ValueError("invalid formatted hex string")
261 value = b""
262 for _ in range(num_chunks):
263 chunk = formatted[0:chunk_size]
264 value += int(chunk, 16).to_bytes(chunk_size // 2, "big")
265 formatted = formatted[chunk_size:]
266 if len(formatted) > 0 and formatted[0] != separator:
267 raise ValueError("invalid formatted hex string")
268 formatted = formatted[1:]
269 return value