Debian Codegraph @

dns/rdataset.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
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.
17
18 """DNS rdatasets (an rdataset is a set of rdatas of a given type and class)"""
19
20 import io
21 import random
22 import struct
23 from typing import Any, Collection, Dict, List, cast
24
25 import dns.exception
26 import dns.immutable
27 import dns.name
28 import dns.rdata
29 import dns.rdataclass
30 import dns.rdatatype
31 import dns.renderer
32 import dns.set
33 import dns.ttl
34
35 # define SimpleSet here for backwards compatibility
36 SimpleSet = dns.set.Set
37
38
39 class DifferingCovers(dns.exception.DNSException):
40 """An attempt was made to add a DNS SIG/RRSIG whose covered type
41 is not the same as that of the other rdatas in the rdataset."""
42
43
44 class IncompatibleTypes(dns.exception.DNSException):
45 """An attempt was made to add DNS RR data of an incompatible type."""
46
47
48 class Rdataset(dns.set.Set):
49 """A DNS rdataset."""
50
51 __slots__ = ["rdclass", "rdtype", "covers", "ttl"]
52
53 def __init__(
54 self,
55 rdclass: dns.rdataclass.RdataClass,
56 rdtype: dns.rdatatype.RdataType,
57 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
58 ttl: int = 0,
59 ):
60 """Create a new rdataset of the specified class and type.
61
62 *rdclass*, a ``dns.rdataclass.RdataClass``, the rdataclass.
63
64 *rdtype*, an ``dns.rdatatype.RdataType``, the rdatatype.
65
66 *covers*, an ``dns.rdatatype.RdataType``, the covered rdatatype.
67
68 *ttl*, an ``int``, the TTL.
69 """
70
71 super().__init__()
72 self.rdclass = rdclass
73 self.rdtype: dns.rdatatype.RdataType = rdtype
74 self.covers: dns.rdatatype.RdataType = covers
75 self.ttl = ttl
76
77 def _clone(self):
78 obj = cast(Rdataset, super()._clone())
79 obj.rdclass = self.rdclass
80 obj.rdtype = self.rdtype
81 obj.covers = self.covers
82 obj.ttl = self.ttl
83 return obj
84
85 def update_ttl(self, ttl: int) -> None:
86 """Perform TTL minimization.
87
88 Set the TTL of the rdataset to be the lesser of the set's current
89 TTL or the specified TTL. If the set contains no rdatas, set the TTL
90 to the specified TTL.
91
92 *ttl*, an ``int`` or ``str``.
93 """
94 ttl = dns.ttl.make(ttl)
95 if len(self) == 0:
96 self.ttl = ttl
97 elif ttl < self.ttl:
98 self.ttl = ttl
99
100 # pylint: disable=arguments-differ,arguments-renamed
101 def add( # pyright: ignore
102 self, rd: dns.rdata.Rdata, ttl: int | None = None
103 ) -> None:
104 """Add the specified rdata to the rdataset.
105
106 If the optional *ttl* parameter is supplied, then
107 ``self.update_ttl(ttl)`` will be called prior to adding the rdata.
108
109 *rd*, a ``dns.rdata.Rdata``, the rdata
110
111 *ttl*, an ``int``, the TTL.
112
113 Raises ``dns.rdataset.IncompatibleTypes`` if the type and class
114 do not match the type and class of the rdataset.
115
116 Raises ``dns.rdataset.DifferingCovers`` if the type is a signature
117 type and the covered type does not match that of the rdataset.
118 """
119
120 #
121 # If we're adding a signature, do some special handling to
122 # check that the signature covers the same type as the
123 # other rdatas in this rdataset. If this is the first rdata
124 # in the set, initialize the covers field.
125 #
126 if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype:
127 raise IncompatibleTypes
128 if ttl is not None:
129 self.update_ttl(ttl)
130 if self.rdtype == dns.rdatatype.RRSIG or self.rdtype == dns.rdatatype.SIG:
131 covers = rd.covers()
132 if len(self) == 0 and self.covers == dns.rdatatype.NONE:
133 self.covers = covers
134 elif self.covers != covers:
135 raise DifferingCovers
136 if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0:
137 self.clear()
138 super().add(rd)
139
140 def union_update(self, other):
141 self.update_ttl(other.ttl)
142 super().union_update(other)
143
144 def intersection_update(self, other):
145 self.update_ttl(other.ttl)
146 super().intersection_update(other)
147
148 def update(self, other):
149 """Add all rdatas in other to self.
150
151 *other*, a ``dns.rdataset.Rdataset``, the rdataset from which
152 to update.
153 """
154
155 self.update_ttl(other.ttl)
156 super().update(other)
157
158 def _rdata_repr(self):
159 def maybe_truncate(s):
160 if len(s) > 100:
161 return s[:100] + "..."
162 return s
163
164 return "[" + ", ".join(f"<{maybe_truncate(str(rr))}>" for rr in self) + "]"
165
166 def __repr__(self):
167 if self.covers == 0:
168 ctext = ""
169 else:
170 ctext = "(" + dns.rdatatype.to_text(self.covers) + ")"
171 return (
172 "<DNS "
173 + dns.rdataclass.to_text(self.rdclass)
174 + " "
175 + dns.rdatatype.to_text(self.rdtype)
176 + ctext
177 + " rdataset: "
178 + self._rdata_repr()
179 + ">"
180 )
181
182 def __str__(self):
183 return self.to_text()
184
185 def __eq__(self, other):
186 if not isinstance(other, Rdataset):
187 return False
188 if (
189 self.rdclass != other.rdclass
190 or self.rdtype != other.rdtype
191 or self.covers != other.covers
192 ):
193 return False
194 return super().__eq__(other)
195
196 def __ne__(self, other):
197 return not self.__eq__(other)
198
199 def to_text(
200 self,
201 name: dns.name.Name | None = None,
202 origin: dns.name.Name | None = None,
203 relativize: bool = True,
204 override_rdclass: dns.rdataclass.RdataClass | None = None,
205 want_comments: bool = False,
206 **kw: Dict[str, Any],
207 ) -> str:
208 """Convert the rdataset into DNS zone file format.
209
210 See ``dns.name.Name.choose_relativity`` for more information
211 on how *origin* and *relativize* determine the way names
212 are emitted.
213
214 Any additional keyword arguments are passed on to the rdata
215 ``to_text()`` method.
216
217 *name*, a ``dns.name.Name``. If name is not ``None``, emit RRs with
218 *name* as the owner name.
219
220 *origin*, a ``dns.name.Name`` or ``None``, the origin for relative
221 names.
222
223 *relativize*, a ``bool``. If ``True``, names will be relativized
224 to *origin*.
225
226 *override_rdclass*, a ``dns.rdataclass.RdataClass`` or ``None``.
227 If not ``None``, use this class instead of the Rdataset's class.
228
229 *want_comments*, a ``bool``. If ``True``, emit comments for rdata
230 which have them. The default is ``False``.
231 """
232
233 if name is not None:
234 name = name.choose_relativity(origin, relativize)
235 ntext = str(name)
236 pad = " "
237 else:
238 ntext = ""
239 pad = ""
240 s = io.StringIO()
241 if override_rdclass is not None:
242 rdclass = override_rdclass
243 else:
244 rdclass = self.rdclass
245 if len(self) == 0:
246 #
247 # Empty rdatasets are used for the question section, and in
248 # some dynamic updates, so we don't need to print out the TTL
249 # (which is meaningless anyway).
250 #
251 s.write(
252 f"{ntext}{pad}{dns.rdataclass.to_text(rdclass)} "
253 f"{dns.rdatatype.to_text(self.rdtype)}\n"
254 )
255 else:
256 for rd in self:
257 extra = ""
258 if want_comments:
259 if rd.rdcomment:
260 extra = f" ;{rd.rdcomment}"
261 s.write(
262 f"{ntext}{pad}{self.ttl} "
263 f"{dns.rdataclass.to_text(rdclass)} "
264 f"{dns.rdatatype.to_text(self.rdtype)} "
265 f"{rd.to_text(origin=origin, relativize=relativize, **kw)}"
266 f"{extra}\n"
267 )
268 #
269 # We strip off the final \n for the caller's convenience in printing
270 #
271 return s.getvalue()[:-1]
272
273 def to_wire(
274 self,
275 name: dns.name.Name,
276 file: Any,
277 compress: dns.name.CompressType | None = None,
278 origin: dns.name.Name | None = None,
279 override_rdclass: dns.rdataclass.RdataClass | None = None,
280 want_shuffle: bool = True,
281 ) -> int:
282 """Convert the rdataset to wire format.
283
284 *name*, a ``dns.name.Name`` is the owner name to use.
285
286 *file* is the file where the name is emitted (typically a
287 BytesIO file).
288
289 *compress*, a ``dict``, is the compression table to use. If
290 ``None`` (the default), names will not be compressed.
291
292 *origin* is a ``dns.name.Name`` or ``None``. If the name is
293 relative and origin is not ``None``, then *origin* will be appended
294 to it.
295
296 *override_rdclass*, an ``int``, is used as the class instead of the
297 class of the rdataset. This is useful when rendering rdatasets
298 associated with dynamic updates.
299
300 *want_shuffle*, a ``bool``. If ``True``, then the order of the
301 Rdatas within the Rdataset will be shuffled before rendering.
302
303 Returns an ``int``, the number of records emitted.
304 """
305
306 if override_rdclass is not None:
307 rdclass = override_rdclass
308 want_shuffle = False
309 else:
310 rdclass = self.rdclass
311 if len(self) == 0:
312 name.to_wire(file, compress, origin)
313 file.write(struct.pack("!HHIH", self.rdtype, rdclass, 0, 0))
314 return 1
315 else:
316 l: Rdataset | List[dns.rdata.Rdata]
317 if want_shuffle:
318 l = list(self)
319 random.shuffle(l)
320 else:
321 l = self
322 for rd in l:
323 name.to_wire(file, compress, origin)
324 file.write(struct.pack("!HHI", self.rdtype, rdclass, self.ttl))
325 with dns.renderer.prefixed_length(file, 2):
326 rd.to_wire(file, compress, origin)
327 return len(self)
328
329 def match(
330 self,
331 rdclass: dns.rdataclass.RdataClass,
332 rdtype: dns.rdatatype.RdataType,
333 covers: dns.rdatatype.RdataType,
334 ) -> bool:
335 """Returns ``True`` if this rdataset matches the specified class,
336 type, and covers.
337 """
338 if self.rdclass == rdclass and self.rdtype == rdtype and self.covers == covers:
339 return True
340 return False
341
342 def processing_order(self) -> List[dns.rdata.Rdata]:
343 """Return rdatas in a valid processing order according to the type's
344 specification. For example, MX records are in preference order from
345 lowest to highest preferences, with items of the same preference
346 shuffled.
347
348 For types that do not define a processing order, the rdatas are
349 simply shuffled.
350 """
351 if len(self) == 0:
352 return []
353 else:
354 return self[0]._processing_order(iter(self)) # pyright: ignore
355
356
357 @dns.immutable.immutable
358 class ImmutableRdataset(Rdataset): # lgtm[py/missing-equals]
359 """An immutable DNS rdataset."""
360
361 _clone_class = Rdataset
362
363 def __init__(self, rdataset: Rdataset):
364 """Create an immutable rdataset from the specified rdataset."""
365
366 super().__init__(
367 rdataset.rdclass, rdataset.rdtype, rdataset.covers, rdataset.ttl
368 )
369 self.items = dns.immutable.Dict(rdataset.items)
370
371 def update_ttl(self, ttl):
372 raise TypeError("immutable")
373
374 def add(self, rd, ttl=None):
375 raise TypeError("immutable")
376
377 def union_update(self, other):
378 raise TypeError("immutable")
379
380 def intersection_update(self, other):
381 raise TypeError("immutable")
382
383 def update(self, other):
384 raise TypeError("immutable")
385
386 def __delitem__(self, i):
387 raise TypeError("immutable")
388
389 # lgtm complains about these not raising ArithmeticError, but there is
390 # precedent for overrides of these methods in other classes to raise
391 # TypeError, and it seems like the better exception.
392
393 def __ior__(self, other): # lgtm[py/unexpected-raise-in-special-method]
394 raise TypeError("immutable")
395
396 def __iand__(self, other): # lgtm[py/unexpected-raise-in-special-method]
397 raise TypeError("immutable")
398
399 def __iadd__(self, other): # lgtm[py/unexpected-raise-in-special-method]
400 raise TypeError("immutable")
401
402 def __isub__(self, other): # lgtm[py/unexpected-raise-in-special-method]
403 raise TypeError("immutable")
404
405 def clear(self):
406 raise TypeError("immutable")
407
408 def __copy__(self):
409 return ImmutableRdataset(super().copy()) # pyright: ignore
410
411 def copy(self):
412 return ImmutableRdataset(super().copy()) # pyright: ignore
413
414 def union(self, other):
415 return ImmutableRdataset(super().union(other)) # pyright: ignore
416
417 def intersection(self, other):
418 return ImmutableRdataset(super().intersection(other)) # pyright: ignore
419
420 def difference(self, other):
421 return ImmutableRdataset(super().difference(other)) # pyright: ignore
422
423 def symmetric_difference(self, other):
424 return ImmutableRdataset(super().symmetric_difference(other)) # pyright: ignore
425
426
427 def from_text_list(
428 rdclass: dns.rdataclass.RdataClass | str,
429 rdtype: dns.rdatatype.RdataType | str,
430 ttl: int,
431 text_rdatas: Collection[str],
432 idna_codec: dns.name.IDNACodec | None = None,
433 origin: dns.name.Name | None = None,
434 relativize: bool = True,
435 relativize_to: dns.name.Name | None = None,
436 ) -> Rdataset:
437 """Create an rdataset with the specified class, type, and TTL, and with
438 the specified list of rdatas in text format.
439
440 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
441 encoder/decoder to use; if ``None``, the default IDNA 2003
442 encoder/decoder is used.
443
444 *origin*, a ``dns.name.Name`` (or ``None``), the
445 origin to use for relative names.
446
447 *relativize*, a ``bool``. If true, name will be relativized.
448
449 *relativize_to*, a ``dns.name.Name`` (or ``None``), the origin to use
450 when relativizing names. If not set, the *origin* value will be used.
451
452 Returns a ``dns.rdataset.Rdataset`` object.
453 """
454
455 rdclass = dns.rdataclass.RdataClass.make(rdclass)
456 rdtype = dns.rdatatype.RdataType.make(rdtype)
457 r = Rdataset(rdclass, rdtype)
458 r.update_ttl(ttl)
459 for t in text_rdatas:
460 rd = dns.rdata.from_text(
461 r.rdclass, r.rdtype, t, origin, relativize, relativize_to, idna_codec
462 )
463 r.add(rd)
464 return r
465
466
467 def from_text(
468 rdclass: dns.rdataclass.RdataClass | str,
469 rdtype: dns.rdatatype.RdataType | str,
470 ttl: int,
471 *text_rdatas: Any,
472 ) -> Rdataset:
473 """Create an rdataset with the specified class, type, and TTL, and with
474 the specified rdatas in text format.
475
476 Returns a ``dns.rdataset.Rdataset`` object.
477 """
478
479 return from_text_list(rdclass, rdtype, ttl, cast(Collection[str], text_rdatas))
480
481
482 def from_rdata_list(ttl: int, rdatas: Collection[dns.rdata.Rdata]) -> Rdataset:
483 """Create an rdataset with the specified TTL, and with
484 the specified list of rdata objects.
485
486 Returns a ``dns.rdataset.Rdataset`` object.
487 """
488
489 if len(rdatas) == 0:
490 raise ValueError("rdata list must not be empty")
491 r = None
492 for rd in rdatas:
493 if r is None:
494 r = Rdataset(rd.rdclass, rd.rdtype)
495 r.update_ttl(ttl)
496 r.add(rd)
497 assert r is not None
498 return r
499
500
501 def from_rdata(ttl: int, *rdatas: Any) -> Rdataset:
502 """Create an rdataset with the specified TTL, and with
503 the specified rdata objects.
504
505 Returns a ``dns.rdataset.Rdataset`` object.
506 """
507
508 return from_rdata_list(ttl, cast(Collection[dns.rdata.Rdata], rdatas))