Debian Codegraph @

dns/zone.py

raw
1 # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
3 # Copyright (C) 2003-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 """DNS Zones."""
19
20 import contextlib
21 import io
22 import os
23 import struct
24 from typing import (
25 Any,
26 Callable,
27 Iterable,
28 Iterator,
29 List,
30 MutableMapping,
31 Set,
32 Tuple,
33 cast,
34 )
35
36 import dns.exception
37 import dns.grange
38 import dns.immutable
39 import dns.name
40 import dns.node
41 import dns.rdata
42 import dns.rdataclass
43 import dns.rdataset
44 import dns.rdatatype
45 import dns.rdtypes.ANY.SOA
46 import dns.rdtypes.ANY.ZONEMD
47 import dns.rrset
48 import dns.tokenizer
49 import dns.transaction
50 import dns.ttl
51 import dns.zonefile
52 from dns.zonetypes import DigestHashAlgorithm, DigestScheme, _digest_hashers
53
54
55 class BadZone(dns.exception.DNSException):
56 """The DNS zone is malformed."""
57
58
59 class NoSOA(BadZone):
60 """The DNS zone has no SOA RR at its origin."""
61
62
63 class NoNS(BadZone):
64 """The DNS zone has no NS RRset at its origin."""
65
66
67 class UnknownOrigin(BadZone):
68 """The DNS zone's origin is unknown."""
69
70
71 class UnsupportedDigestScheme(dns.exception.DNSException):
72 """The zone digest's scheme is unsupported."""
73
74
75 class UnsupportedDigestHashAlgorithm(dns.exception.DNSException):
76 """The zone digest's origin is unsupported."""
77
78
79 class NoDigest(dns.exception.DNSException):
80 """The DNS zone has no ZONEMD RRset at its origin."""
81
82
83 class DigestVerificationFailure(dns.exception.DNSException):
84 """The ZONEMD digest failed to verify."""
85
86
87 def _validate_name(
88 name: dns.name.Name,
89 origin: dns.name.Name | None,
90 relativize: bool,
91 ) -> dns.name.Name:
92 # This name validation code is shared by Zone and Version
93 if origin is None:
94 # This should probably never happen as other code (e.g.
95 # _rr_line) will notice the lack of an origin before us, but
96 # we check just in case!
97 raise KeyError("no zone origin is defined")
98 if name.is_absolute():
99 if not name.is_subdomain(origin):
100 raise KeyError("name parameter must be a subdomain of the zone origin")
101 if relativize:
102 name = name.relativize(origin)
103 else:
104 # We have a relative name. Make sure that the derelativized name is
105 # not too long.
106 try:
107 abs_name = name.derelativize(origin)
108 except dns.name.NameTooLong:
109 # We map dns.name.NameTooLong to KeyError to be consistent with
110 # the other exceptions above.
111 raise KeyError("relative name too long for zone")
112 if not relativize:
113 # We have a relative name in a non-relative zone, so use the
114 # derelativized name.
115 name = abs_name
116 return name
117
118
119 class Zone(dns.transaction.TransactionManager):
120 """A DNS zone.
121
122 A ``Zone`` is a mapping from names to nodes. The zone object may be
123 treated like a Python dictionary, e.g. ``zone[name]`` will retrieve
124 the node associated with that name. The *name* may be a
125 ``dns.name.Name object``, or it may be a string. In either case,
126 if the name is relative it is treated as relative to the origin of
127 the zone.
128 """
129
130 node_factory: Callable[[], dns.node.Node] = dns.node.Node
131 map_factory: Callable[[], MutableMapping[dns.name.Name, dns.node.Node]] = dict
132 # We only require the version types as "Version" to allow for flexibility, as
133 # only the version protocol matters
134 writable_version_factory: Callable[["Zone", bool], "Version"] | None = None
135 immutable_version_factory: Callable[["Version"], "Version"] | None = None
136
137 __slots__ = ["rdclass", "origin", "nodes", "relativize"]
138
139 def __init__(
140 self,
141 origin: dns.name.Name | str | None,
142 rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
143 relativize: bool = True,
144 ):
145 """Initialize a zone object.
146
147 *origin* is the origin of the zone. It may be a ``dns.name.Name``,
148 a ``str``, or ``None``. If ``None``, then the zone's origin will
149 be set by the first ``$ORIGIN`` line in a zone file.
150
151 *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
152
153 *relativize*, a ``bool``, determine's whether domain names are
154 relativized to the zone's origin. The default is ``True``.
155 """
156
157 if origin is not None:
158 if isinstance(origin, str):
159 origin = dns.name.from_text(origin)
160 elif not isinstance(origin, dns.name.Name):
161 raise ValueError("origin parameter must be convertible to a DNS name")
162 if not origin.is_absolute():
163 raise ValueError("origin parameter must be an absolute name")
164 self.origin = origin
165 self.rdclass = rdclass
166 self.nodes: MutableMapping[dns.name.Name, dns.node.Node] = self.map_factory()
167 self.relativize = relativize
168
169 def __eq__(self, other):
170 """Two zones are equal if they have the same origin, class, and
171 nodes.
172
173 Returns a ``bool``.
174 """
175
176 if not isinstance(other, Zone):
177 return False
178 if (
179 self.rdclass != other.rdclass
180 or self.origin != other.origin
181 or self.nodes != other.nodes
182 ):
183 return False
184 return True
185
186 def __ne__(self, other):
187 """Are two zones not equal?
188
189 Returns a ``bool``.
190 """
191
192 return not self.__eq__(other)
193
194 def _validate_name(self, name: dns.name.Name | str) -> dns.name.Name:
195 # Note that any changes in this method should have corresponding changes
196 # made in the Version _validate_name() method.
197 if isinstance(name, str):
198 name = dns.name.from_text(name, None)
199 elif not isinstance(name, dns.name.Name):
200 raise KeyError("name parameter must be convertible to a DNS name")
201 return _validate_name(name, self.origin, self.relativize)
202
203 def __getitem__(self, key):
204 key = self._validate_name(key)
205 return self.nodes[key]
206
207 def __setitem__(self, key, value):
208 key = self._validate_name(key)
209 self.nodes[key] = value
210
211 def __delitem__(self, key):
212 key = self._validate_name(key)
213 del self.nodes[key]
214
215 def __iter__(self):
216 return self.nodes.__iter__()
217
218 def keys(self):
219 return self.nodes.keys()
220
221 def values(self):
222 return self.nodes.values()
223
224 def items(self):
225 return self.nodes.items()
226
227 def get(self, key):
228 key = self._validate_name(key)
229 return self.nodes.get(key)
230
231 def __contains__(self, key):
232 key = self._validate_name(key)
233 return key in self.nodes
234
235 def find_node(
236 self, name: dns.name.Name | str, create: bool = False
237 ) -> dns.node.Node:
238 """Find a node in the zone, possibly creating it.
239
240 *name*: the name of the node to find.
241 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
242 name must be a subdomain of the zone's origin. If ``zone.relativize``
243 is ``True``, then the name will be relativized.
244
245 *create*, a ``bool``. If true, the node will be created if it does
246 not exist.
247
248 Raises ``KeyError`` if the name is not known and create was
249 not specified, or if the name was not a subdomain of the origin.
250
251 Returns a ``dns.node.Node``.
252 """
253
254 name = self._validate_name(name)
255 node = self.nodes.get(name)
256 if node is None:
257 if not create:
258 raise KeyError
259 node = self.node_factory()
260 self.nodes[name] = node
261 return node
262
263 def get_node(
264 self, name: dns.name.Name | str, create: bool = False
265 ) -> dns.node.Node | None:
266 """Get a node in the zone, possibly creating it.
267
268 This method is like ``find_node()``, except it returns None instead
269 of raising an exception if the node does not exist and creation
270 has not been requested.
271
272 *name*: the name of the node to find.
273 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
274 name must be a subdomain of the zone's origin. If ``zone.relativize``
275 is ``True``, then the name will be relativized.
276
277 *create*, a ``bool``. If true, the node will be created if it does
278 not exist.
279
280 Returns a ``dns.node.Node`` or ``None``.
281 """
282
283 try:
284 node = self.find_node(name, create)
285 except KeyError:
286 node = None
287 return node
288
289 def delete_node(self, name: dns.name.Name | str) -> None:
290 """Delete the specified node if it exists.
291
292 *name*: the name of the node to find.
293 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
294 name must be a subdomain of the zone's origin. If ``zone.relativize``
295 is ``True``, then the name will be relativized.
296
297 It is not an error if the node does not exist.
298 """
299
300 name = self._validate_name(name)
301 if name in self.nodes:
302 del self.nodes[name]
303
304 def find_rdataset(
305 self,
306 name: dns.name.Name | str,
307 rdtype: dns.rdatatype.RdataType | str,
308 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
309 create: bool = False,
310 ) -> dns.rdataset.Rdataset:
311 """Look for an rdataset with the specified name and type in the zone,
312 and return an rdataset encapsulating it.
313
314 The rdataset returned is not a copy; changes to it will change
315 the zone.
316
317 KeyError is raised if the name or type are not found.
318
319 *name*: the name of the node to find.
320 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
321 name must be a subdomain of the zone's origin. If ``zone.relativize``
322 is ``True``, then the name will be relativized.
323
324 *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
325
326 *covers*, a ``dns.rdatatype.RdataType`` or ``str`` the covered type.
327 Usually this value is ``dns.rdatatype.NONE``, but if the
328 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
329 then the covers value will be the rdata type the SIG/RRSIG
330 covers. The library treats the SIG and RRSIG types as if they
331 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
332 This makes RRSIGs much easier to work with than if RRSIGs
333 covering different rdata types were aggregated into a single
334 RRSIG rdataset.
335
336 *create*, a ``bool``. If true, the node will be created if it does
337 not exist.
338
339 Raises ``KeyError`` if the name is not known and create was
340 not specified, or if the name was not a subdomain of the origin.
341
342 Returns a ``dns.rdataset.Rdataset``.
343 """
344
345 name = self._validate_name(name)
346 rdtype = dns.rdatatype.RdataType.make(rdtype)
347 covers = dns.rdatatype.RdataType.make(covers)
348 node = self.find_node(name, create)
349 return node.find_rdataset(self.rdclass, rdtype, covers, create)
350
351 def get_rdataset(
352 self,
353 name: dns.name.Name | str,
354 rdtype: dns.rdatatype.RdataType | str,
355 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
356 create: bool = False,
357 ) -> dns.rdataset.Rdataset | None:
358 """Look for an rdataset with the specified name and type in the zone.
359
360 This method is like ``find_rdataset()``, except it returns None instead
361 of raising an exception if the rdataset does not exist and creation
362 has not been requested.
363
364 The rdataset returned is not a copy; changes to it will change
365 the zone.
366
367 *name*: the name of the node to find.
368 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
369 name must be a subdomain of the zone's origin. If ``zone.relativize``
370 is ``True``, then the name will be relativized.
371
372 *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
373
374 *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type.
375 Usually this value is ``dns.rdatatype.NONE``, but if the
376 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
377 then the covers value will be the rdata type the SIG/RRSIG
378 covers. The library treats the SIG and RRSIG types as if they
379 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
380 This makes RRSIGs much easier to work with than if RRSIGs
381 covering different rdata types were aggregated into a single
382 RRSIG rdataset.
383
384 *create*, a ``bool``. If true, the node will be created if it does
385 not exist.
386
387 Raises ``KeyError`` if the name is not known and create was
388 not specified, or if the name was not a subdomain of the origin.
389
390 Returns a ``dns.rdataset.Rdataset`` or ``None``.
391 """
392
393 try:
394 rdataset = self.find_rdataset(name, rdtype, covers, create)
395 except KeyError:
396 rdataset = None
397 return rdataset
398
399 def delete_rdataset(
400 self,
401 name: dns.name.Name | str,
402 rdtype: dns.rdatatype.RdataType | str,
403 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
404 ) -> None:
405 """Delete the rdataset matching *rdtype* and *covers*, if it
406 exists at the node specified by *name*.
407
408 It is not an error if the node does not exist, or if there is no matching
409 rdataset at the node.
410
411 If the node has no rdatasets after the deletion, it will itself be deleted.
412
413 *name*: the name of the node to find. The value may be a ``dns.name.Name`` or a
414 ``str``. If absolute, the name must be a subdomain of the zone's origin. If
415 ``zone.relativize`` is ``True``, then the name will be relativized.
416
417 *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
418
419 *covers*, a ``dns.rdatatype.RdataType`` or ``str`` or ``None``, the covered
420 type. Usually this value is ``dns.rdatatype.NONE``, but if the rdtype is
421 ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``, then the covers value will be
422 the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types
423 as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This
424 makes RRSIGs much easier to work with than if RRSIGs covering different rdata
425 types were aggregated into a single RRSIG rdataset.
426 """
427
428 name = self._validate_name(name)
429 rdtype = dns.rdatatype.RdataType.make(rdtype)
430 covers = dns.rdatatype.RdataType.make(covers)
431 node = self.get_node(name)
432 if node is not None:
433 node.delete_rdataset(self.rdclass, rdtype, covers)
434 if len(node) == 0:
435 self.delete_node(name)
436
437 def replace_rdataset(
438 self, name: dns.name.Name | str, replacement: dns.rdataset.Rdataset
439 ) -> None:
440 """Replace an rdataset at name.
441
442 It is not an error if there is no rdataset matching I{replacement}.
443
444 Ownership of the *replacement* object is transferred to the zone;
445 in other words, this method does not store a copy of *replacement*
446 at the node, it stores *replacement* itself.
447
448 If the node does not exist, it is created.
449
450 *name*: the name of the node to find.
451 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
452 name must be a subdomain of the zone's origin. If ``zone.relativize``
453 is ``True``, then the name will be relativized.
454
455 *replacement*, a ``dns.rdataset.Rdataset``, the replacement rdataset.
456 """
457
458 if replacement.rdclass != self.rdclass:
459 raise ValueError("replacement.rdclass != zone.rdclass")
460 node = self.find_node(name, True)
461 node.replace_rdataset(replacement)
462
463 def find_rrset(
464 self,
465 name: dns.name.Name | str,
466 rdtype: dns.rdatatype.RdataType | str,
467 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
468 ) -> dns.rrset.RRset:
469 """Look for an rdataset with the specified name and type in the zone,
470 and return an RRset encapsulating it.
471
472 This method is less efficient than the similar
473 ``find_rdataset()`` because it creates an RRset instead of
474 returning the matching rdataset. It may be more convenient
475 for some uses since it returns an object which binds the owner
476 name to the rdataset.
477
478 This method may not be used to create new nodes or rdatasets;
479 use ``find_rdataset`` instead.
480
481 *name*: the name of the node to find.
482 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
483 name must be a subdomain of the zone's origin. If ``zone.relativize``
484 is ``True``, then the name will be relativized.
485
486 *rdtype*, a ``dns.rdatatype.RdataType`` or ``str``, the rdata type desired.
487
488 *covers*, a ``dns.rdatatype.RdataType`` or ``str``, the covered type.
489 Usually this value is ``dns.rdatatype.NONE``, but if the
490 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
491 then the covers value will be the rdata type the SIG/RRSIG
492 covers. The library treats the SIG and RRSIG types as if they
493 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
494 This makes RRSIGs much easier to work with than if RRSIGs
495 covering different rdata types were aggregated into a single
496 RRSIG rdataset.
497
498 *create*, a ``bool``. If true, the node will be created if it does
499 not exist.
500
501 Raises ``KeyError`` if the name is not known and create was
502 not specified, or if the name was not a subdomain of the origin.
503
504 Returns a ``dns.rrset.RRset`` or ``None``.
505 """
506
507 vname = self._validate_name(name)
508 rdtype = dns.rdatatype.RdataType.make(rdtype)
509 covers = dns.rdatatype.RdataType.make(covers)
510 rdataset = self.nodes[vname].find_rdataset(self.rdclass, rdtype, covers)
511 rrset = dns.rrset.RRset(vname, self.rdclass, rdtype, covers)
512 rrset.update(rdataset)
513 return rrset
514
515 def get_rrset(
516 self,
517 name: dns.name.Name | str,
518 rdtype: dns.rdatatype.RdataType | str,
519 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
520 ) -> dns.rrset.RRset | None:
521 """Look for an rdataset with the specified name and type in the zone,
522 and return an RRset encapsulating it.
523
524 This method is less efficient than the similar ``get_rdataset()``
525 because it creates an RRset instead of returning the matching
526 rdataset. It may be more convenient for some uses since it
527 returns an object which binds the owner name to the rdataset.
528
529 This method may not be used to create new nodes or rdatasets;
530 use ``get_rdataset()`` instead.
531
532 *name*: the name of the node to find.
533 The value may be a ``dns.name.Name`` or a ``str``. If absolute, the
534 name must be a subdomain of the zone's origin. If ``zone.relativize``
535 is ``True``, then the name will be relativized.
536
537 *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
538
539 *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
540 Usually this value is ``dns.rdatatype.NONE``, but if the
541 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
542 then the covers value will be the rdata type the SIG/RRSIG
543 covers. The library treats the SIG and RRSIG types as if they
544 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
545 This makes RRSIGs much easier to work with than if RRSIGs
546 covering different rdata types were aggregated into a single
547 RRSIG rdataset.
548
549 *create*, a ``bool``. If true, the node will be created if it does
550 not exist.
551
552 Returns a ``dns.rrset.RRset`` or ``None``.
553 """
554
555 try:
556 rrset = self.find_rrset(name, rdtype, covers)
557 except KeyError:
558 rrset = None
559 return rrset
560
561 def iterate_rdatasets(
562 self,
563 rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY,
564 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
565 ) -> Iterator[Tuple[dns.name.Name, dns.rdataset.Rdataset]]:
566 """Return a generator which yields (name, rdataset) tuples for
567 all rdatasets in the zone which have the specified *rdtype*
568 and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
569 then all rdatasets will be matched.
570
571 *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
572
573 *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
574 Usually this value is ``dns.rdatatype.NONE``, but if the
575 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
576 then the covers value will be the rdata type the SIG/RRSIG
577 covers. The library treats the SIG and RRSIG types as if they
578 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
579 This makes RRSIGs much easier to work with than if RRSIGs
580 covering different rdata types were aggregated into a single
581 RRSIG rdataset.
582 """
583
584 rdtype = dns.rdatatype.RdataType.make(rdtype)
585 covers = dns.rdatatype.RdataType.make(covers)
586 for name, node in self.items():
587 for rds in node:
588 if rdtype == dns.rdatatype.ANY or (
589 rds.rdtype == rdtype and rds.covers == covers
590 ):
591 yield (name, rds)
592
593 def iterate_rdatas(
594 self,
595 rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.ANY,
596 covers: dns.rdatatype.RdataType | str = dns.rdatatype.NONE,
597 ) -> Iterator[Tuple[dns.name.Name, int, dns.rdata.Rdata]]:
598 """Return a generator which yields (name, ttl, rdata) tuples for
599 all rdatas in the zone which have the specified *rdtype*
600 and *covers*. If *rdtype* is ``dns.rdatatype.ANY``, the default,
601 then all rdatas will be matched.
602
603 *rdtype*, a ``dns.rdataset.Rdataset`` or ``str``, the rdata type desired.
604
605 *covers*, a ``dns.rdataset.Rdataset`` or ``str``, the covered type.
606 Usually this value is ``dns.rdatatype.NONE``, but if the
607 rdtype is ``dns.rdatatype.SIG`` or ``dns.rdatatype.RRSIG``,
608 then the covers value will be the rdata type the SIG/RRSIG
609 covers. The library treats the SIG and RRSIG types as if they
610 were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA).
611 This makes RRSIGs much easier to work with than if RRSIGs
612 covering different rdata types were aggregated into a single
613 RRSIG rdataset.
614 """
615
616 rdtype = dns.rdatatype.RdataType.make(rdtype)
617 covers = dns.rdatatype.RdataType.make(covers)
618 for name, node in self.items():
619 for rds in node:
620 if rdtype == dns.rdatatype.ANY or (
621 rds.rdtype == rdtype and rds.covers == covers
622 ):
623 for rdata in rds:
624 yield (name, rds.ttl, rdata)
625
626 def to_file(
627 self,
628 f: Any,
629 sorted: bool = True,
630 relativize: bool = True,
631 nl: str | None = None,
632 want_comments: bool = False,
633 want_origin: bool = False,
634 ) -> None:
635 """Write a zone to a file.
636
637 *f*, a file or `str`. If *f* is a string, it is treated
638 as the name of a file to open.
639
640 *sorted*, a ``bool``. If True, the default, then the file
641 will be written with the names sorted in DNSSEC order from
642 least to greatest. Otherwise the names will be written in
643 whatever order they happen to have in the zone's dictionary.
644
645 *relativize*, a ``bool``. If True, the default, then domain
646 names in the output will be relativized to the zone's origin
647 if possible.
648
649 *nl*, a ``str`` or None. The end of line string. If not
650 ``None``, the output will use the platform's native
651 end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
652
653 *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
654 as part of writing the file. If ``False``, the default, do not
655 emit them.
656
657 *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
658 the start of the file. If ``False``, the default, do not emit
659 one.
660 """
661
662 if isinstance(f, str):
663 cm: contextlib.AbstractContextManager = open(f, "wb")
664 else:
665 cm = contextlib.nullcontext(f)
666 with cm as f:
667 # must be in this way, f.encoding may contain None, or even
668 # attribute may not be there
669 file_enc = getattr(f, "encoding", None)
670 if file_enc is None:
671 file_enc = "utf-8"
672
673 if nl is None:
674 # binary mode, '\n' is not enough
675 nl_b = os.linesep.encode(file_enc)
676 nl = "\n"
677 elif isinstance(nl, str):
678 nl_b = nl.encode(file_enc)
679 else:
680 nl_b = nl
681 nl = nl.decode()
682
683 if want_origin:
684 assert self.origin is not None
685 l = "$ORIGIN " + self.origin.to_text()
686 l_b = l.encode(file_enc)
687 try:
688 f.write(l_b)
689 f.write(nl_b)
690 except TypeError: # textual mode
691 f.write(l)
692 f.write(nl)
693
694 if sorted:
695 names = list(self.keys())
696 names.sort()
697 else:
698 names = self.keys()
699 for n in names:
700 l = self[n].to_text(
701 n,
702 origin=self.origin, # pyright: ignore
703 relativize=relativize, # pyright: ignore
704 want_comments=want_comments, # pyright: ignore
705 )
706 l_b = l.encode(file_enc)
707
708 try:
709 f.write(l_b)
710 f.write(nl_b)
711 except TypeError: # textual mode
712 f.write(l)
713 f.write(nl)
714
715 def to_text(
716 self,
717 sorted: bool = True,
718 relativize: bool = True,
719 nl: str | None = None,
720 want_comments: bool = False,
721 want_origin: bool = False,
722 ) -> str:
723 """Return a zone's text as though it were written to a file.
724
725 *sorted*, a ``bool``. If True, the default, then the file
726 will be written with the names sorted in DNSSEC order from
727 least to greatest. Otherwise the names will be written in
728 whatever order they happen to have in the zone's dictionary.
729
730 *relativize*, a ``bool``. If True, the default, then domain
731 names in the output will be relativized to the zone's origin
732 if possible.
733
734 *nl*, a ``str`` or None. The end of line string. If not
735 ``None``, the output will use the platform's native
736 end-of-line marker (i.e. LF on POSIX, CRLF on Windows).
737
738 *want_comments*, a ``bool``. If ``True``, emit end-of-line comments
739 as part of writing the file. If ``False``, the default, do not
740 emit them.
741
742 *want_origin*, a ``bool``. If ``True``, emit a $ORIGIN line at
743 the start of the output. If ``False``, the default, do not emit
744 one.
745
746 Returns a ``str``.
747 """
748 temp_buffer = io.StringIO()
749 self.to_file(temp_buffer, sorted, relativize, nl, want_comments, want_origin)
750 return_value = temp_buffer.getvalue()
751 temp_buffer.close()
752 return return_value
753
754 def check_origin(self) -> None:
755 """Do some simple checking of the zone's origin.
756
757 Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
758
759 Raises ``dns.zone.NoNS`` if there is no NS RRset.
760
761 Raises ``KeyError`` if there is no origin node.
762 """
763 if self.relativize:
764 name = dns.name.empty
765 else:
766 assert self.origin is not None
767 name = self.origin
768 if self.get_rdataset(name, dns.rdatatype.SOA) is None:
769 raise NoSOA
770 if self.get_rdataset(name, dns.rdatatype.NS) is None:
771 raise NoNS
772
773 def get_soa(
774 self, txn: dns.transaction.Transaction | None = None
775 ) -> dns.rdtypes.ANY.SOA.SOA:
776 """Get the zone SOA rdata.
777
778 Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
779
780 Returns a ``dns.rdtypes.ANY.SOA.SOA`` Rdata.
781 """
782 if self.relativize:
783 origin_name = dns.name.empty
784 else:
785 if self.origin is None:
786 # get_soa() has been called very early, and there must not be
787 # an SOA if there is no origin.
788 raise NoSOA
789 origin_name = self.origin
790 soa_rds: dns.rdataset.Rdataset | None
791 if txn:
792 soa_rds = txn.get(origin_name, dns.rdatatype.SOA)
793 else:
794 soa_rds = self.get_rdataset(origin_name, dns.rdatatype.SOA)
795 if soa_rds is None:
796 raise NoSOA
797 else:
798 soa = cast(dns.rdtypes.ANY.SOA.SOA, soa_rds[0])
799 return soa
800
801 def _compute_digest(
802 self,
803 hash_algorithm: DigestHashAlgorithm,
804 scheme: DigestScheme = DigestScheme.SIMPLE,
805 ) -> bytes:
806 hashinfo = _digest_hashers.get(hash_algorithm)
807 if not hashinfo:
808 raise UnsupportedDigestHashAlgorithm
809 if scheme != DigestScheme.SIMPLE:
810 raise UnsupportedDigestScheme
811
812 if self.relativize:
813 origin_name = dns.name.empty
814 else:
815 assert self.origin is not None
816 origin_name = self.origin
817 hasher = hashinfo()
818 for name, node in sorted(self.items()):
819 rrnamebuf = name.to_digestable(self.origin)
820 for rdataset in sorted(node, key=lambda rds: (rds.rdtype, rds.covers)):
821 if name == origin_name and dns.rdatatype.ZONEMD in (
822 rdataset.rdtype,
823 rdataset.covers,
824 ):
825 continue
826 rrfixed = struct.pack(
827 "!HHI", rdataset.rdtype, rdataset.rdclass, rdataset.ttl
828 )
829 rdatas = [rdata.to_digestable(self.origin) for rdata in rdataset]
830 for rdata in sorted(rdatas):
831 rrlen = struct.pack("!H", len(rdata))
832 hasher.update(rrnamebuf + rrfixed + rrlen + rdata)
833 return hasher.digest()
834
835 def compute_digest(
836 self,
837 hash_algorithm: DigestHashAlgorithm,
838 scheme: DigestScheme = DigestScheme.SIMPLE,
839 ) -> dns.rdtypes.ANY.ZONEMD.ZONEMD:
840 serial = self.get_soa().serial
841 digest = self._compute_digest(hash_algorithm, scheme)
842 return dns.rdtypes.ANY.ZONEMD.ZONEMD(
843 self.rdclass, dns.rdatatype.ZONEMD, serial, scheme, hash_algorithm, digest
844 )
845
846 def verify_digest(
847 self, zonemd: dns.rdtypes.ANY.ZONEMD.ZONEMD | None = None
848 ) -> None:
849 digests: dns.rdataset.Rdataset | List[dns.rdtypes.ANY.ZONEMD.ZONEMD]
850 if zonemd:
851 digests = [zonemd]
852 else:
853 assert self.origin is not None
854 rds = self.get_rdataset(self.origin, dns.rdatatype.ZONEMD)
855 if rds is None:
856 raise NoDigest
857 digests = rds
858 for digest in digests:
859 try:
860 computed = self._compute_digest(digest.hash_algorithm, digest.scheme)
861 if computed == digest.digest:
862 return
863 except Exception:
864 pass
865 raise DigestVerificationFailure
866
867 # TransactionManager methods
868
869 def reader(self) -> "Transaction":
870 return Transaction(self, False, Version(self, 1, self.nodes, self.origin))
871
872 def writer(self, replacement: bool = False) -> "Transaction":
873 txn = Transaction(self, replacement)
874 txn._setup_version()
875 return txn
876
877 def origin_information(
878 self,
879 ) -> Tuple[dns.name.Name | None, bool, dns.name.Name | None]:
880 effective: dns.name.Name | None
881 if self.relativize:
882 effective = dns.name.empty
883 else:
884 effective = self.origin
885 return (self.origin, self.relativize, effective)
886
887 def get_class(self):
888 return self.rdclass
889
890 # Transaction methods
891
892 def _end_read(self, txn):
893 pass
894
895 def _end_write(self, txn):
896 pass
897
898 def _commit_version(self, txn, version, origin):
899 self.nodes = version.nodes
900 if self.origin is None:
901 self.origin = origin
902
903 def _get_next_version_id(self) -> int:
904 # Versions are ephemeral and all have id 1
905 return 1
906
907
908 # These classes used to be in dns.versioned, but have moved here so we can use
909 # the copy-on-write transaction mechanism for both kinds of zones. In a
910 # regular zone, the version only exists during the transaction, and the nodes
911 # are regular dns.node.Nodes.
912
913 # A node with a version id.
914
915
916 class VersionedNode(dns.node.Node): # lgtm[py/missing-equals]
917 __slots__ = ["id"]
918
919 def __init__(self):
920 super().__init__()
921 # A proper id will get set by the Version
922 self.id = 0
923
924
925 @dns.immutable.immutable
926 class ImmutableVersionedNode(VersionedNode):
927 def __init__(self, node):
928 super().__init__()
929 self.id = node.id
930 self.rdatasets = tuple(
931 [dns.rdataset.ImmutableRdataset(rds) for rds in node.rdatasets]
932 )
933
934 def find_rdataset(
935 self,
936 rdclass: dns.rdataclass.RdataClass,
937 rdtype: dns.rdatatype.RdataType,
938 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
939 create: bool = False,
940 ) -> dns.rdataset.Rdataset:
941 if create:
942 raise TypeError("immutable")
943 return super().find_rdataset(rdclass, rdtype, covers, False)
944
945 def get_rdataset(
946 self,
947 rdclass: dns.rdataclass.RdataClass,
948 rdtype: dns.rdatatype.RdataType,
949 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
950 create: bool = False,
951 ) -> dns.rdataset.Rdataset | None:
952 if create:
953 raise TypeError("immutable")
954 return super().get_rdataset(rdclass, rdtype, covers, False)
955
956 def delete_rdataset(
957 self,
958 rdclass: dns.rdataclass.RdataClass,
959 rdtype: dns.rdatatype.RdataType,
960 covers: dns.rdatatype.RdataType = dns.rdatatype.NONE,
961 ) -> None:
962 raise TypeError("immutable")
963
964 def replace_rdataset(self, replacement: dns.rdataset.Rdataset) -> None:
965 raise TypeError("immutable")
966
967 def is_immutable(self) -> bool:
968 return True
969
970
971 class Version:
972 def __init__(
973 self,
974 zone: Zone,
975 id: int,
976 nodes: MutableMapping[dns.name.Name, dns.node.Node] | None = None,
977 origin: dns.name.Name | None = None,
978 ):
979 self.zone = zone
980 self.id = id
981 if nodes is not None:
982 self.nodes = nodes
983 else:
984 self.nodes = zone.map_factory()
985 self.origin = origin
986
987 def _validate_name(self, name: dns.name.Name) -> dns.name.Name:
988 return _validate_name(name, self.origin, self.zone.relativize)
989
990 def get_node(self, name: dns.name.Name) -> dns.node.Node | None:
991 name = self._validate_name(name)
992 return self.nodes.get(name)
993
994 def get_rdataset(
995 self,
996 name: dns.name.Name,
997 rdtype: dns.rdatatype.RdataType,
998 covers: dns.rdatatype.RdataType,
999 ) -> dns.rdataset.Rdataset | None:
1000 node = self.get_node(name)
1001 if node is None:
1002 return None
1003 return node.get_rdataset(self.zone.rdclass, rdtype, covers)
1004
1005 def keys(self):
1006 return self.nodes.keys()
1007
1008 def items(self):
1009 return self.nodes.items()
1010
1011
1012 class WritableVersion(Version):
1013 def __init__(self, zone: Zone, replacement: bool = False):
1014 # The zone._versions_lock must be held by our caller in a versioned
1015 # zone.
1016 id = zone._get_next_version_id()
1017 super().__init__(zone, id)
1018 if not replacement:
1019 # We copy the map, because that gives us a simple and thread-safe
1020 # way of doing versions, and we have a garbage collector to help
1021 # us. We only make new node objects if we actually change the
1022 # node.
1023 self.nodes.update(zone.nodes)
1024 # We have to copy the zone origin as it may be None in the first
1025 # version, and we don't want to mutate the zone until we commit.
1026 self.origin = zone.origin
1027 self.changed: Set[dns.name.Name] = set()
1028
1029 def _maybe_cow_with_name(
1030 self, name: dns.name.Name
1031 ) -> Tuple[dns.node.Node, dns.name.Name]:
1032 name = self._validate_name(name)
1033 node = self.nodes.get(name)
1034 if node is None or name not in self.changed:
1035 new_node = self.zone.node_factory()
1036 if hasattr(new_node, "id"):
1037 # We keep doing this for backwards compatibility, as earlier
1038 # code used new_node.id != self.id for the "do we need to CoW?"
1039 # test. Now we use the changed set as this works with both
1040 # regular zones and versioned zones.
1041 #
1042 # We ignore the mypy error as this is safe but it doesn't see it.
1043 new_node.id = self.id # type: ignore
1044 if node is not None:
1045 # moo! copy on write!
1046 new_node.rdatasets.extend(node.rdatasets)
1047 self.nodes[name] = new_node
1048 self.changed.add(name)
1049 return (new_node, name)
1050 else:
1051 return (node, name)
1052
1053 def _maybe_cow(self, name: dns.name.Name) -> dns.node.Node:
1054 return self._maybe_cow_with_name(name)[0]
1055
1056 def delete_node(self, name: dns.name.Name) -> None:
1057 name = self._validate_name(name)
1058 if name in self.nodes:
1059 del self.nodes[name]
1060 self.changed.add(name)
1061
1062 def put_rdataset(
1063 self, name: dns.name.Name, rdataset: dns.rdataset.Rdataset
1064 ) -> None:
1065 node = self._maybe_cow(name)
1066 node.replace_rdataset(rdataset)
1067
1068 def delete_rdataset(
1069 self,
1070 name: dns.name.Name,
1071 rdtype: dns.rdatatype.RdataType,
1072 covers: dns.rdatatype.RdataType,
1073 ) -> None:
1074 node = self._maybe_cow(name)
1075 node.delete_rdataset(self.zone.rdclass, rdtype, covers)
1076 if len(node) == 0:
1077 del self.nodes[name]
1078
1079
1080 @dns.immutable.immutable
1081 class ImmutableVersion(Version):
1082 def __init__(self, version: Version):
1083 if not isinstance(version, WritableVersion):
1084 raise ValueError(
1085 "a dns.zone.ImmutableVersion requires a dns.zone.WritableVersion"
1086 )
1087 # We tell super() that it's a replacement as we don't want it
1088 # to copy the nodes, as we're about to do that with an
1089 # immutable Dict.
1090 super().__init__(version.zone, True)
1091 # set the right id!
1092 self.id = version.id
1093 # keep the origin
1094 self.origin = version.origin
1095 # Make changed nodes immutable
1096 for name in version.changed:
1097 node = version.nodes.get(name)
1098 # it might not exist if we deleted it in the version
1099 if node:
1100 version.nodes[name] = ImmutableVersionedNode(node)
1101 # We're changing the type of the nodes dictionary here on purpose, so
1102 # we ignore the mypy error.
1103 self.nodes = dns.immutable.Dict(
1104 version.nodes, True, self.zone.map_factory
1105 ) # type: ignore
1106
1107
1108 class Transaction(dns.transaction.Transaction):
1109 def __init__(self, zone, replacement, version=None, make_immutable=False):
1110 read_only = version is not None
1111 super().__init__(zone, replacement, read_only)
1112 self.version = version
1113 self.make_immutable = make_immutable
1114
1115 @property
1116 def zone(self):
1117 return self.manager
1118
1119 def _setup_version(self):
1120 assert self.version is None
1121 factory = self.manager.writable_version_factory # pyright: ignore
1122 if factory is None:
1123 factory = WritableVersion
1124 self.version = factory(self.zone, self.replacement) # pyright: ignore
1125
1126 def _get_rdataset(self, name, rdtype, covers):
1127 assert self.version is not None
1128 return self.version.get_rdataset(name, rdtype, covers)
1129
1130 def _put_rdataset(self, name, rdataset):
1131 assert not self.read_only
1132 assert self.version is not None
1133 self.version.put_rdataset(name, rdataset)
1134
1135 def _delete_name(self, name):
1136 assert not self.read_only
1137 assert self.version is not None
1138 self.version.delete_node(name)
1139
1140 def _delete_rdataset(self, name, rdtype, covers):
1141 assert not self.read_only
1142 assert self.version is not None
1143 self.version.delete_rdataset(name, rdtype, covers)
1144
1145 def _name_exists(self, name):
1146 assert self.version is not None
1147 return self.version.get_node(name) is not None
1148
1149 def _changed(self):
1150 if self.read_only:
1151 return False
1152 else:
1153 assert self.version is not None
1154 return len(self.version.changed) > 0
1155
1156 def _end_transaction(self, commit):
1157 assert self.zone is not None
1158 assert self.version is not None
1159 if self.read_only:
1160 self.zone._end_read(self) # pyright: ignore
1161 elif commit and len(self.version.changed) > 0:
1162 if self.make_immutable:
1163 factory = self.manager.immutable_version_factory # pyright: ignore
1164 if factory is None:
1165 factory = ImmutableVersion
1166 version = factory(self.version)
1167 else:
1168 version = self.version
1169 self.zone._commit_version( # pyright: ignore
1170 self, version, self.version.origin
1171 )
1172
1173 else:
1174 # rollback
1175 self.zone._end_write(self) # pyright: ignore
1176
1177 def _set_origin(self, origin):
1178 assert self.version is not None
1179 if self.version.origin is None:
1180 self.version.origin = origin
1181
1182 def _iterate_rdatasets(self):
1183 assert self.version is not None
1184 for name, node in self.version.items():
1185 for rdataset in node:
1186 yield (name, rdataset)
1187
1188 def _iterate_names(self):
1189 assert self.version is not None
1190 return self.version.keys()
1191
1192 def _get_node(self, name):
1193 assert self.version is not None
1194 return self.version.get_node(name)
1195
1196 def _origin_information(self):
1197 assert self.version is not None
1198 (absolute, relativize, effective) = self.manager.origin_information()
1199 if absolute is None and self.version.origin is not None:
1200 # No origin has been committed yet, but we've learned one as part of
1201 # this txn. Use it.
1202 absolute = self.version.origin
1203 if relativize:
1204 effective = dns.name.empty
1205 else:
1206 effective = absolute
1207 return (absolute, relativize, effective)
1208
1209
1210 def _from_text(
1211 text: Any,
1212 origin: dns.name.Name | str | None = None,
1213 rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
1214 relativize: bool = True,
1215 zone_factory: Any = Zone,
1216 filename: str | None = None,
1217 allow_include: bool = False,
1218 check_origin: bool = True,
1219 idna_codec: dns.name.IDNACodec | None = None,
1220 allow_directives: bool | Iterable[str] = True,
1221 ) -> Zone:
1222 # See the comments for the public APIs from_text() and from_file() for
1223 # details.
1224
1225 # 'text' can also be a file, but we don't publish that fact
1226 # since it's an implementation detail. The official file
1227 # interface is from_file().
1228
1229 if filename is None:
1230 filename = "<string>"
1231 zone = zone_factory(origin, rdclass, relativize=relativize)
1232 with zone.writer(True) as txn:
1233 tok = dns.tokenizer.Tokenizer(text, filename, idna_codec=idna_codec)
1234 reader = dns.zonefile.Reader(
1235 tok,
1236 rdclass,
1237 txn,
1238 allow_include=allow_include,
1239 allow_directives=allow_directives,
1240 )
1241 try:
1242 reader.read()
1243 except dns.zonefile.UnknownOrigin:
1244 # for backwards compatibility
1245 raise UnknownOrigin
1246 # Now that we're done reading, do some basic checking of the zone.
1247 if check_origin:
1248 zone.check_origin()
1249 return zone
1250
1251
1252 def from_text(
1253 text: str,
1254 origin: dns.name.Name | str | None = None,
1255 rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
1256 relativize: bool = True,
1257 zone_factory: Any = Zone,
1258 filename: str | None = None,
1259 allow_include: bool = False,
1260 check_origin: bool = True,
1261 idna_codec: dns.name.IDNACodec | None = None,
1262 allow_directives: bool | Iterable[str] = True,
1263 ) -> Zone:
1264 """Build a zone object from a zone file format string.
1265
1266 *text*, a ``str``, the zone file format input.
1267
1268 *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
1269 of the zone; if not specified, the first ``$ORIGIN`` statement in the
1270 zone file will determine the origin of the zone.
1271
1272 *rdclass*, a ``dns.rdataclass.RdataClass``, the zone's rdata class; the default is
1273 class IN.
1274
1275 *relativize*, a ``bool``, determine's whether domain names are
1276 relativized to the zone's origin. The default is ``True``.
1277
1278 *zone_factory*, the zone factory to use or ``None``. If ``None``, then
1279 ``dns.zone.Zone`` will be used. The value may be any class or callable
1280 that returns a subclass of ``dns.zone.Zone``.
1281
1282 *filename*, a ``str`` or ``None``, the filename to emit when
1283 describing where an error occurred; the default is ``'<string>'``.
1284
1285 *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
1286 directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
1287 will raise a ``SyntaxError`` exception.
1288
1289 *check_origin*, a ``bool``. If ``True``, the default, then sanity
1290 checks of the origin node will be made by calling the zone's
1291 ``check_origin()`` method.
1292
1293 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
1294 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
1295 is used.
1296
1297 *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default,
1298 then directives are permitted, and the *allow_include* parameter controls whether
1299 ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive
1300 processing is done and any directive-like text will be treated as a regular owner
1301 name. If a non-empty iterable, then only the listed directives (including the
1302 ``$``) are allowed.
1303
1304 Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
1305
1306 Raises ``dns.zone.NoNS`` if there is no NS RRset.
1307
1308 Raises ``KeyError`` if there is no origin node.
1309
1310 Returns a subclass of ``dns.zone.Zone``.
1311 """
1312 return _from_text(
1313 text,
1314 origin,
1315 rdclass,
1316 relativize,
1317 zone_factory,
1318 filename,
1319 allow_include,
1320 check_origin,
1321 idna_codec,
1322 allow_directives,
1323 )
1324
1325
1326 def from_file(
1327 f: Any,
1328 origin: dns.name.Name | str | None = None,
1329 rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN,
1330 relativize: bool = True,
1331 zone_factory: Any = Zone,
1332 filename: str | None = None,
1333 allow_include: bool = True,
1334 check_origin: bool = True,
1335 idna_codec: dns.name.IDNACodec | None = None,
1336 allow_directives: bool | Iterable[str] = True,
1337 ) -> Zone:
1338 """Read a zone file and build a zone object.
1339
1340 *f*, a file or ``str``. If *f* is a string, it is treated
1341 as the name of a file to open.
1342
1343 *origin*, a ``dns.name.Name``, a ``str``, or ``None``. The origin
1344 of the zone; if not specified, the first ``$ORIGIN`` statement in the
1345 zone file will determine the origin of the zone.
1346
1347 *rdclass*, an ``int``, the zone's rdata class; the default is class IN.
1348
1349 *relativize*, a ``bool``, determine's whether domain names are
1350 relativized to the zone's origin. The default is ``True``.
1351
1352 *zone_factory*, the zone factory to use or ``None``. If ``None``, then
1353 ``dns.zone.Zone`` will be used. The value may be any class or callable
1354 that returns a subclass of ``dns.zone.Zone``.
1355
1356 *filename*, a ``str`` or ``None``, the filename to emit when
1357 describing where an error occurred; the default is ``'<string>'``.
1358
1359 *allow_include*, a ``bool``. If ``True``, the default, then ``$INCLUDE``
1360 directives are permitted. If ``False``, then encoutering a ``$INCLUDE``
1361 will raise a ``SyntaxError`` exception.
1362
1363 *check_origin*, a ``bool``. If ``True``, the default, then sanity
1364 checks of the origin node will be made by calling the zone's
1365 ``check_origin()`` method.
1366
1367 *idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA
1368 encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder
1369 is used.
1370
1371 *allow_directives*, a ``bool`` or an iterable of `str`. If ``True``, the default,
1372 then directives are permitted, and the *allow_include* parameter controls whether
1373 ``$INCLUDE`` is permitted. If ``False`` or an empty iterable, then no directive
1374 processing is done and any directive-like text will be treated as a regular owner
1375 name. If a non-empty iterable, then only the listed directives (including the
1376 ``$``) are allowed.
1377
1378 Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
1379
1380 Raises ``dns.zone.NoNS`` if there is no NS RRset.
1381
1382 Raises ``KeyError`` if there is no origin node.
1383
1384 Returns a subclass of ``dns.zone.Zone``.
1385 """
1386
1387 if isinstance(f, str):
1388 if filename is None:
1389 filename = f
1390 cm: contextlib.AbstractContextManager = open(f, encoding="utf-8")
1391 else:
1392 cm = contextlib.nullcontext(f)
1393 with cm as f:
1394 return _from_text(
1395 f,
1396 origin,
1397 rdclass,
1398 relativize,
1399 zone_factory,
1400 filename,
1401 allow_include,
1402 check_origin,
1403 idna_codec,
1404 allow_directives,
1405 )
1406 assert False # make mypy happy lgtm[py/unreachable-statement]
1407
1408
1409 def from_xfr(
1410 xfr: Any,
1411 zone_factory: Any = Zone,
1412 relativize: bool = True,
1413 check_origin: bool = True,
1414 ) -> Zone:
1415 """Convert the output of a zone transfer generator into a zone object.
1416
1417 *xfr*, a generator of ``dns.message.Message`` objects, typically
1418 ``dns.query.xfr()``.
1419
1420 *relativize*, a ``bool``, determine's whether domain names are
1421 relativized to the zone's origin. The default is ``True``.
1422 It is essential that the relativize setting matches the one specified
1423 to the generator.
1424
1425 *check_origin*, a ``bool``. If ``True``, the default, then sanity
1426 checks of the origin node will be made by calling the zone's
1427 ``check_origin()`` method.
1428
1429 Raises ``dns.zone.NoSOA`` if there is no SOA RRset.
1430
1431 Raises ``dns.zone.NoNS`` if there is no NS RRset.
1432
1433 Raises ``KeyError`` if there is no origin node.
1434
1435 Raises ``ValueError`` if no messages are yielded by the generator.
1436
1437 Returns a subclass of ``dns.zone.Zone``.
1438 """
1439
1440 z = None
1441 for r in xfr:
1442 if z is None:
1443 if relativize:
1444 origin = r.origin
1445 else:
1446 origin = r.answer[0].name
1447 rdclass = r.answer[0].rdclass
1448 z = zone_factory(origin, rdclass, relativize=relativize)
1449 for rrset in r.answer:
1450 znode = z.nodes.get(rrset.name)
1451 if not znode:
1452 znode = z.node_factory()
1453 z.nodes[rrset.name] = znode
1454 zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True)
1455 zrds.update_ttl(rrset.ttl)
1456 for rd in rrset:
1457 zrds.add(rd)
1458 if z is None:
1459 raise ValueError("empty transfer")
1460 if check_origin:
1461 z.check_origin()
1462 return z