| 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 re |
| 21 |
import sys |
| 22 |
from typing import Any, Iterable, List, Set, Tuple, cast |
| 23 |
|
| 24 |
import dns.exception |
| 25 |
import dns.grange |
| 26 |
import dns.name |
| 27 |
import dns.node |
| 28 |
import dns.rdata |
| 29 |
import dns.rdataclass |
| 30 |
import dns.rdatatype |
| 31 |
import dns.rdtypes.ANY.SOA |
| 32 |
import dns.rrset |
| 33 |
import dns.tokenizer |
| 34 |
import dns.transaction |
| 35 |
import dns.ttl |
| 36 |
|
| 37 |
|
| 38 |
class UnknownOrigin(dns.exception.DNSException): |
| 39 |
"""Unknown origin""" |
| 40 |
|
| 41 |
|
| 42 |
class CNAMEAndOtherData(dns.exception.DNSException): |
| 43 |
"""A node has a CNAME and other data""" |
| 44 |
|
| 45 |
|
| 46 |
def _check_cname_and_other_data(txn, name, rdataset): |
| 47 |
rdataset_kind = dns.node.NodeKind.classify_rdataset(rdataset) |
| 48 |
node = txn.get_node(name) |
| 49 |
if node is None: |
| 50 |
# empty nodes are neutral. |
| 51 |
return |
| 52 |
node_kind = node.classify() |
| 53 |
if ( |
| 54 |
node_kind == dns.node.NodeKind.CNAME |
| 55 |
and rdataset_kind == dns.node.NodeKind.REGULAR |
| 56 |
): |
| 57 |
raise CNAMEAndOtherData("rdataset type is not compatible with a CNAME node") |
| 58 |
elif ( |
| 59 |
node_kind == dns.node.NodeKind.REGULAR |
| 60 |
and rdataset_kind == dns.node.NodeKind.CNAME |
| 61 |
): |
| 62 |
raise CNAMEAndOtherData( |
| 63 |
"CNAME rdataset is not compatible with a regular data node" |
| 64 |
) |
| 65 |
# Otherwise at least one of the node and the rdataset is neutral, so |
| 66 |
# adding the rdataset is ok |
| 67 |
|
| 68 |
|
| 69 |
SavedStateType = Tuple[ |
| 70 |
dns.tokenizer.Tokenizer, |
| 71 |
dns.name.Name | None, # current_origin |
| 72 |
dns.name.Name | None, # last_name |
| 73 |
Any | None, # current_file |
| 74 |
int, # last_ttl |
| 75 |
bool, # last_ttl_known |
| 76 |
int, # default_ttl |
| 77 |
bool, |
| 78 |
] # default_ttl_known |
| 79 |
|
| 80 |
|
| 81 |
def _upper_dollarize(s): |
| 82 |
s = s.upper() |
| 83 |
if not s.startswith("$"): |
| 84 |
s = "$" + s |
| 85 |
return s |
| 86 |
|
| 87 |
|
| 88 |
class Reader: |
| 89 |
"""Read a DNS zone file into a transaction.""" |
| 90 |
|
| 91 |
def __init__( |
| 92 |
self, |
| 93 |
tok: dns.tokenizer.Tokenizer, |
| 94 |
rdclass: dns.rdataclass.RdataClass, |
| 95 |
txn: dns.transaction.Transaction, |
| 96 |
allow_include: bool = False, |
| 97 |
allow_directives: bool | Iterable[str] = True, |
| 98 |
force_name: dns.name.Name | None = None, |
| 99 |
force_ttl: int | None = None, |
| 100 |
force_rdclass: dns.rdataclass.RdataClass | None = None, |
| 101 |
force_rdtype: dns.rdatatype.RdataType | None = None, |
| 102 |
default_ttl: int | None = None, |
| 103 |
): |
| 104 |
self.tok = tok |
| 105 |
(self.zone_origin, self.relativize, _) = txn.manager.origin_information() |
| 106 |
self.current_origin = self.zone_origin |
| 107 |
self.last_ttl = 0 |
| 108 |
self.last_ttl_known = False |
| 109 |
if force_ttl is not None: |
| 110 |
default_ttl = force_ttl |
| 111 |
if default_ttl is None: |
| 112 |
self.default_ttl = 0 |
| 113 |
self.default_ttl_known = False |
| 114 |
else: |
| 115 |
self.default_ttl = default_ttl |
| 116 |
self.default_ttl_known = True |
| 117 |
self.last_name = self.current_origin |
| 118 |
self.zone_rdclass = rdclass |
| 119 |
self.txn = txn |
| 120 |
self.saved_state: List[SavedStateType] = [] |
| 121 |
self.current_file: Any | None = None |
| 122 |
self.allowed_directives: Set[str] |
| 123 |
if allow_directives is True: |
| 124 |
self.allowed_directives = {"$GENERATE", "$ORIGIN", "$TTL"} |
| 125 |
if allow_include: |
| 126 |
self.allowed_directives.add("$INCLUDE") |
| 127 |
elif allow_directives is False: |
| 128 |
# allow_include was ignored in earlier releases if allow_directives was |
| 129 |
# False, so we continue that. |
| 130 |
self.allowed_directives = set() |
| 131 |
else: |
| 132 |
# Note that if directives are explicitly specified, then allow_include |
| 133 |
# is ignored. |
| 134 |
self.allowed_directives = set(_upper_dollarize(d) for d in allow_directives) |
| 135 |
self.force_name = force_name |
| 136 |
self.force_ttl = force_ttl |
| 137 |
self.force_rdclass = force_rdclass |
| 138 |
self.force_rdtype = force_rdtype |
| 139 |
self.txn.check_put_rdataset(_check_cname_and_other_data) |
| 140 |
|
| 141 |
def _eat_line(self): |
| 142 |
while 1: |
| 143 |
token = self.tok.get() |
| 144 |
if token.is_eol_or_eof(): |
| 145 |
break |
| 146 |
|
| 147 |
def _get_identifier(self): |
| 148 |
token = self.tok.get() |
| 149 |
if not token.is_identifier(): |
| 150 |
raise dns.exception.SyntaxError |
| 151 |
return token |
| 152 |
|
| 153 |
def _rr_line(self): |
| 154 |
"""Process one line from a DNS zone file.""" |
| 155 |
token = None |
| 156 |
# Name |
| 157 |
if self.force_name is not None: |
| 158 |
name = self.force_name |
| 159 |
else: |
| 160 |
if self.current_origin is None: |
| 161 |
raise UnknownOrigin |
| 162 |
token = self.tok.get(want_leading=True) |
| 163 |
if not token.is_whitespace(): |
| 164 |
self.last_name = self.tok.as_name(token, self.current_origin) |
| 165 |
else: |
| 166 |
token = self.tok.get() |
| 167 |
if token.is_eol_or_eof(): |
| 168 |
# treat leading WS followed by EOL/EOF as if they were EOL/EOF. |
| 169 |
return |
| 170 |
self.tok.unget(token) |
| 171 |
name = self.last_name |
| 172 |
if name is None: |
| 173 |
raise dns.exception.SyntaxError("the last used name is undefined") |
| 174 |
assert self.zone_origin is not None |
| 175 |
if not name.is_subdomain(self.zone_origin): |
| 176 |
self._eat_line() |
| 177 |
return |
| 178 |
if self.relativize: |
| 179 |
name = name.relativize(self.zone_origin) |
| 180 |
|
| 181 |
# TTL |
| 182 |
if self.force_ttl is not None: |
| 183 |
ttl = self.force_ttl |
| 184 |
self.last_ttl = ttl |
| 185 |
self.last_ttl_known = True |
| 186 |
else: |
| 187 |
token = self._get_identifier() |
| 188 |
ttl = None |
| 189 |
try: |
| 190 |
ttl = dns.ttl.from_text(token.value) |
| 191 |
self.last_ttl = ttl |
| 192 |
self.last_ttl_known = True |
| 193 |
token = None |
| 194 |
except dns.ttl.BadTTL: |
| 195 |
self.tok.unget(token) |
| 196 |
|
| 197 |
# Class |
| 198 |
if self.force_rdclass is not None: |
| 199 |
rdclass = self.force_rdclass |
| 200 |
else: |
| 201 |
token = self._get_identifier() |
| 202 |
try: |
| 203 |
rdclass = dns.rdataclass.from_text(token.value) |
| 204 |
except dns.exception.SyntaxError: |
| 205 |
raise |
| 206 |
except Exception: |
| 207 |
rdclass = self.zone_rdclass |
| 208 |
self.tok.unget(token) |
| 209 |
if rdclass != self.zone_rdclass: |
| 210 |
raise dns.exception.SyntaxError("RR class is not zone's class") |
| 211 |
|
| 212 |
if ttl is None: |
| 213 |
# support for <class> <ttl> <type> syntax |
| 214 |
token = self._get_identifier() |
| 215 |
ttl = None |
| 216 |
try: |
| 217 |
ttl = dns.ttl.from_text(token.value) |
| 218 |
self.last_ttl = ttl |
| 219 |
self.last_ttl_known = True |
| 220 |
token = None |
| 221 |
except dns.ttl.BadTTL: |
| 222 |
if self.default_ttl_known: |
| 223 |
ttl = self.default_ttl |
| 224 |
elif self.last_ttl_known: |
| 225 |
ttl = self.last_ttl |
| 226 |
self.tok.unget(token) |
| 227 |
|
| 228 |
# Type |
| 229 |
if self.force_rdtype is not None: |
| 230 |
rdtype = self.force_rdtype |
| 231 |
else: |
| 232 |
token = self._get_identifier() |
| 233 |
try: |
| 234 |
rdtype = dns.rdatatype.from_text(token.value) |
| 235 |
except Exception: |
| 236 |
raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") |
| 237 |
|
| 238 |
try: |
| 239 |
rd = dns.rdata.from_text( |
| 240 |
rdclass, |
| 241 |
rdtype, |
| 242 |
self.tok, |
| 243 |
self.current_origin, |
| 244 |
self.relativize, |
| 245 |
self.zone_origin, |
| 246 |
) |
| 247 |
except dns.exception.SyntaxError: |
| 248 |
# Catch and reraise. |
| 249 |
raise |
| 250 |
except Exception: |
| 251 |
# All exceptions that occur in the processing of rdata |
| 252 |
# are treated as syntax errors. This is not strictly |
| 253 |
# correct, but it is correct almost all of the time. |
| 254 |
# We convert them to syntax errors so that we can emit |
| 255 |
# helpful filename:line info. |
| 256 |
(ty, va) = sys.exc_info()[:2] |
| 257 |
raise dns.exception.SyntaxError(f"caught exception {str(ty)}: {str(va)}") |
| 258 |
|
| 259 |
if not self.default_ttl_known and rdtype == dns.rdatatype.SOA: |
| 260 |
# The pre-RFC2308 and pre-BIND9 behavior inherits the zone default |
| 261 |
# TTL from the SOA minttl if no $TTL statement is present before the |
| 262 |
# SOA is parsed. |
| 263 |
soa_rd = cast(dns.rdtypes.ANY.SOA.SOA, rd) |
| 264 |
self.default_ttl = soa_rd.minimum |
| 265 |
self.default_ttl_known = True |
| 266 |
if ttl is None: |
| 267 |
# if we didn't have a TTL on the SOA, set it! |
| 268 |
ttl = soa_rd.minimum |
| 269 |
|
| 270 |
# TTL check. We had to wait until now to do this as the SOA RR's |
| 271 |
# own TTL can be inferred from its minimum. |
| 272 |
if ttl is None: |
| 273 |
raise dns.exception.SyntaxError("Missing default TTL value") |
| 274 |
|
| 275 |
self.txn.add(name, ttl, rd) |
| 276 |
|
| 277 |
def _parse_modify(self, side: str) -> Tuple[str, str, int, int, str]: |
| 278 |
# Here we catch everything in '{' '}' in a group so we can replace it |
| 279 |
# with ''. |
| 280 |
is_generate1 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$") |
| 281 |
is_generate2 = re.compile(r"^.*\$({(\+|-?)(\d+)}).*$") |
| 282 |
is_generate3 = re.compile(r"^.*\$({(\+|-?)(\d+),(\d+)}).*$") |
| 283 |
# Sometimes there are modifiers in the hostname. These come after |
| 284 |
# the dollar sign. They are in the form: ${offset[,width[,base]]}. |
| 285 |
# Make names |
| 286 |
mod = "" |
| 287 |
sign = "+" |
| 288 |
offset = "0" |
| 289 |
width = "0" |
| 290 |
base = "d" |
| 291 |
g1 = is_generate1.match(side) |
| 292 |
if g1: |
| 293 |
mod, sign, offset, width, base = g1.groups() |
| 294 |
if sign == "": |
| 295 |
sign = "+" |
| 296 |
else: |
| 297 |
g2 = is_generate2.match(side) |
| 298 |
if g2: |
| 299 |
mod, sign, offset = g2.groups() |
| 300 |
if sign == "": |
| 301 |
sign = "+" |
| 302 |
width = "0" |
| 303 |
base = "d" |
| 304 |
else: |
| 305 |
g3 = is_generate3.match(side) |
| 306 |
if g3: |
| 307 |
mod, sign, offset, width = g3.groups() |
| 308 |
if sign == "": |
| 309 |
sign = "+" |
| 310 |
base = "d" |
| 311 |
|
| 312 |
ioffset = int(offset) |
| 313 |
iwidth = int(width) |
| 314 |
|
| 315 |
if sign not in ["+", "-"]: |
| 316 |
raise dns.exception.SyntaxError(f"invalid offset sign {sign}") |
| 317 |
if base not in ["d", "o", "x", "X", "n", "N"]: |
| 318 |
raise dns.exception.SyntaxError(f"invalid type {base}") |
| 319 |
|
| 320 |
return mod, sign, ioffset, iwidth, base |
| 321 |
|
| 322 |
def _generate_line(self): |
| 323 |
# range lhs [ttl] [class] type rhs [ comment ] |
| 324 |
"""Process one line containing the GENERATE statement from a DNS |
| 325 |
zone file.""" |
| 326 |
if self.current_origin is None: |
| 327 |
raise UnknownOrigin |
| 328 |
|
| 329 |
token = self.tok.get() |
| 330 |
# Range (required) |
| 331 |
try: |
| 332 |
start, stop, step = dns.grange.from_text(token.value) |
| 333 |
token = self.tok.get() |
| 334 |
if not token.is_identifier(): |
| 335 |
raise dns.exception.SyntaxError |
| 336 |
except Exception: |
| 337 |
raise dns.exception.SyntaxError |
| 338 |
|
| 339 |
# lhs (required) |
| 340 |
try: |
| 341 |
lhs = token.value |
| 342 |
token = self.tok.get() |
| 343 |
if not token.is_identifier(): |
| 344 |
raise dns.exception.SyntaxError |
| 345 |
except Exception: |
| 346 |
raise dns.exception.SyntaxError |
| 347 |
|
| 348 |
# TTL |
| 349 |
try: |
| 350 |
ttl = dns.ttl.from_text(token.value) |
| 351 |
self.last_ttl = ttl |
| 352 |
self.last_ttl_known = True |
| 353 |
token = self.tok.get() |
| 354 |
if not token.is_identifier(): |
| 355 |
raise dns.exception.SyntaxError |
| 356 |
except dns.ttl.BadTTL: |
| 357 |
if not (self.last_ttl_known or self.default_ttl_known): |
| 358 |
raise dns.exception.SyntaxError("Missing default TTL value") |
| 359 |
if self.default_ttl_known: |
| 360 |
ttl = self.default_ttl |
| 361 |
elif self.last_ttl_known: |
| 362 |
ttl = self.last_ttl |
| 363 |
else: |
| 364 |
# We don't go to the extra "look at the SOA" level of effort for |
| 365 |
# $GENERATE, because the user really ought to have defined a TTL |
| 366 |
# somehow! |
| 367 |
raise dns.exception.SyntaxError("Missing default TTL value") |
| 368 |
|
| 369 |
# Class |
| 370 |
try: |
| 371 |
rdclass = dns.rdataclass.from_text(token.value) |
| 372 |
token = self.tok.get() |
| 373 |
if not token.is_identifier(): |
| 374 |
raise dns.exception.SyntaxError |
| 375 |
except dns.exception.SyntaxError: |
| 376 |
raise dns.exception.SyntaxError |
| 377 |
except Exception: |
| 378 |
rdclass = self.zone_rdclass |
| 379 |
if rdclass != self.zone_rdclass: |
| 380 |
raise dns.exception.SyntaxError("RR class is not zone's class") |
| 381 |
# Type |
| 382 |
try: |
| 383 |
rdtype = dns.rdatatype.from_text(token.value) |
| 384 |
token = self.tok.get() |
| 385 |
if not token.is_identifier(): |
| 386 |
raise dns.exception.SyntaxError |
| 387 |
except Exception: |
| 388 |
raise dns.exception.SyntaxError(f"unknown rdatatype '{token.value}'") |
| 389 |
|
| 390 |
# rhs (required) |
| 391 |
rhs = token.value |
| 392 |
|
| 393 |
def _calculate_index(counter: int, offset_sign: str, offset: int) -> int: |
| 394 |
"""Calculate the index from the counter and offset.""" |
| 395 |
if offset_sign == "-": |
| 396 |
offset *= -1 |
| 397 |
return counter + offset |
| 398 |
|
| 399 |
def _format_index(index: int, base: str, width: int) -> str: |
| 400 |
"""Format the index with the given base, and zero-fill it |
| 401 |
to the given width.""" |
| 402 |
if base in ["d", "o", "x", "X"]: |
| 403 |
return format(index, base).zfill(width) |
| 404 |
|
| 405 |
# base can only be n or N here |
| 406 |
hexa = _format_index(index, "x", width) |
| 407 |
nibbles = ".".join(hexa[::-1])[:width] |
| 408 |
if base == "N": |
| 409 |
nibbles = nibbles.upper() |
| 410 |
return nibbles |
| 411 |
|
| 412 |
lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs) |
| 413 |
rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs) |
| 414 |
for i in range(start, stop + 1, step): |
| 415 |
# +1 because bind is inclusive and python is exclusive |
| 416 |
|
| 417 |
lindex = _calculate_index(i, lsign, loffset) |
| 418 |
rindex = _calculate_index(i, rsign, roffset) |
| 419 |
|
| 420 |
lzfindex = _format_index(lindex, lbase, lwidth) |
| 421 |
rzfindex = _format_index(rindex, rbase, rwidth) |
| 422 |
|
| 423 |
name = lhs.replace(f"${lmod}", lzfindex) |
| 424 |
rdata = rhs.replace(f"${rmod}", rzfindex) |
| 425 |
|
| 426 |
self.last_name = dns.name.from_text( |
| 427 |
name, self.current_origin, self.tok.idna_codec |
| 428 |
) |
| 429 |
name = self.last_name |
| 430 |
assert self.zone_origin is not None |
| 431 |
if not name.is_subdomain(self.zone_origin): |
| 432 |
self._eat_line() |
| 433 |
return |
| 434 |
if self.relativize: |
| 435 |
name = name.relativize(self.zone_origin) |
| 436 |
|
| 437 |
try: |
| 438 |
rd = dns.rdata.from_text( |
| 439 |
rdclass, |
| 440 |
rdtype, |
| 441 |
rdata, |
| 442 |
self.current_origin, |
| 443 |
self.relativize, |
| 444 |
self.zone_origin, |
| 445 |
) |
| 446 |
except dns.exception.SyntaxError: |
| 447 |
# Catch and reraise. |
| 448 |
raise |
| 449 |
except Exception: |
| 450 |
# All exceptions that occur in the processing of rdata |
| 451 |
# are treated as syntax errors. This is not strictly |
| 452 |
# correct, but it is correct almost all of the time. |
| 453 |
# We convert them to syntax errors so that we can emit |
| 454 |
# helpful filename:line info. |
| 455 |
(ty, va) = sys.exc_info()[:2] |
| 456 |
raise dns.exception.SyntaxError( |
| 457 |
f"caught exception {str(ty)}: {str(va)}" |
| 458 |
) |
| 459 |
|
| 460 |
self.txn.add(name, ttl, rd) |
| 461 |
|
| 462 |
def read(self) -> None: |
| 463 |
"""Read a DNS zone file and build a zone object. |
| 464 |
|
| 465 |
@raises dns.zone.NoSOA: No SOA RR was found at the zone origin |
| 466 |
@raises dns.zone.NoNS: No NS RRset was found at the zone origin |
| 467 |
""" |
| 468 |
|
| 469 |
try: |
| 470 |
while 1: |
| 471 |
token = self.tok.get(True, True) |
| 472 |
if token.is_eof(): |
| 473 |
if self.current_file is not None: |
| 474 |
self.current_file.close() |
| 475 |
if len(self.saved_state) > 0: |
| 476 |
( |
| 477 |
self.tok, |
| 478 |
self.current_origin, |
| 479 |
self.last_name, |
| 480 |
self.current_file, |
| 481 |
self.last_ttl, |
| 482 |
self.last_ttl_known, |
| 483 |
self.default_ttl, |
| 484 |
self.default_ttl_known, |
| 485 |
) = self.saved_state.pop(-1) |
| 486 |
continue |
| 487 |
break |
| 488 |
elif token.is_eol(): |
| 489 |
continue |
| 490 |
elif token.is_comment(): |
| 491 |
self.tok.get_eol() |
| 492 |
continue |
| 493 |
elif token.value[0] == "$" and len(self.allowed_directives) > 0: |
| 494 |
# Note that we only run directive processing code if at least |
| 495 |
# one directive is allowed in order to be backwards compatible |
| 496 |
c = token.value.upper() |
| 497 |
if c not in self.allowed_directives: |
| 498 |
raise dns.exception.SyntaxError( |
| 499 |
f"zone file directive '{c}' is not allowed" |
| 500 |
) |
| 501 |
if c == "$TTL": |
| 502 |
token = self.tok.get() |
| 503 |
if not token.is_identifier(): |
| 504 |
raise dns.exception.SyntaxError("bad $TTL") |
| 505 |
self.default_ttl = dns.ttl.from_text(token.value) |
| 506 |
self.default_ttl_known = True |
| 507 |
self.tok.get_eol() |
| 508 |
elif c == "$ORIGIN": |
| 509 |
self.current_origin = self.tok.get_name() |
| 510 |
self.tok.get_eol() |
| 511 |
if self.zone_origin is None: |
| 512 |
self.zone_origin = self.current_origin |
| 513 |
self.txn._set_origin(self.current_origin) |
| 514 |
elif c == "$INCLUDE": |
| 515 |
token = self.tok.get() |
| 516 |
filename = token.value |
| 517 |
token = self.tok.get() |
| 518 |
new_origin: dns.name.Name | None |
| 519 |
if token.is_identifier(): |
| 520 |
new_origin = dns.name.from_text( |
| 521 |
token.value, self.current_origin, self.tok.idna_codec |
| 522 |
) |
| 523 |
self.tok.get_eol() |
| 524 |
elif not token.is_eol_or_eof(): |
| 525 |
raise dns.exception.SyntaxError("bad origin in $INCLUDE") |
| 526 |
else: |
| 527 |
new_origin = self.current_origin |
| 528 |
self.saved_state.append( |
| 529 |
( |
| 530 |
self.tok, |
| 531 |
self.current_origin, |
| 532 |
self.last_name, |
| 533 |
self.current_file, |
| 534 |
self.last_ttl, |
| 535 |
self.last_ttl_known, |
| 536 |
self.default_ttl, |
| 537 |
self.default_ttl_known, |
| 538 |
) |
| 539 |
) |
| 540 |
self.current_file = open(filename, encoding="utf-8") |
| 541 |
self.tok = dns.tokenizer.Tokenizer(self.current_file, filename) |
| 542 |
self.current_origin = new_origin |
| 543 |
elif c == "$GENERATE": |
| 544 |
self._generate_line() |
| 545 |
else: |
| 546 |
raise dns.exception.SyntaxError( |
| 547 |
f"Unknown zone file directive '{c}'" |
| 548 |
) |
| 549 |
continue |
| 550 |
self.tok.unget(token) |
| 551 |
self._rr_line() |
| 552 |
except dns.exception.SyntaxError as detail: |
| 553 |
(filename, line_number) = self.tok.where() |
| 554 |
if detail is None: |
| 555 |
detail = "syntax error" |
| 556 |
ex = dns.exception.SyntaxError(f"{filename}:{line_number}: {detail}") |
| 557 |
tb = sys.exc_info()[2] |
| 558 |
raise ex.with_traceback(tb) from None |
| 559 |
|
| 560 |
|
| 561 |
class RRsetsReaderTransaction(dns.transaction.Transaction): |
| 562 |
def __init__(self, manager, replacement, read_only): |
| 563 |
assert not read_only |
| 564 |
super().__init__(manager, replacement, read_only) |
| 565 |
self.rdatasets = {} |
| 566 |
|
| 567 |
def _get_rdataset(self, name, rdtype, covers): |
| 568 |
return self.rdatasets.get((name, rdtype, covers)) |
| 569 |
|
| 570 |
def _get_node(self, name): |
| 571 |
rdatasets = [] |
| 572 |
for (rdataset_name, _, _), rdataset in self.rdatasets.items(): |
| 573 |
if name == rdataset_name: |
| 574 |
rdatasets.append(rdataset) |
| 575 |
if len(rdatasets) == 0: |
| 576 |
return None |
| 577 |
node = dns.node.Node() |
| 578 |
node.rdatasets = rdatasets |
| 579 |
return node |
| 580 |
|
| 581 |
def _put_rdataset(self, name, rdataset): |
| 582 |
self.rdatasets[(name, rdataset.rdtype, rdataset.covers)] = rdataset |
| 583 |
|
| 584 |
def _delete_name(self, name): |
| 585 |
# First remove any changes involving the name |
| 586 |
remove = [] |
| 587 |
for key in self.rdatasets: |
| 588 |
if key[0] == name: |
| 589 |
remove.append(key) |
| 590 |
if len(remove) > 0: |
| 591 |
for key in remove: |
| 592 |
del self.rdatasets[key] |
| 593 |
|
| 594 |
def _delete_rdataset(self, name, rdtype, covers): |
| 595 |
try: |
| 596 |
del self.rdatasets[(name, rdtype, covers)] |
| 597 |
except KeyError: |
| 598 |
pass |
| 599 |
|
| 600 |
def _name_exists(self, name): |
| 601 |
for n, _, _ in self.rdatasets: |
| 602 |
if n == name: |
| 603 |
return True |
| 604 |
return False |
| 605 |
|
| 606 |
def _changed(self): |
| 607 |
return len(self.rdatasets) > 0 |
| 608 |
|
| 609 |
def _end_transaction(self, commit): |
| 610 |
if commit and self._changed(): |
| 611 |
rrsets = [] |
| 612 |
for (name, _, _), rdataset in self.rdatasets.items(): |
| 613 |
rrset = dns.rrset.RRset( |
| 614 |
name, rdataset.rdclass, rdataset.rdtype, rdataset.covers |
| 615 |
) |
| 616 |
rrset.update(rdataset) |
| 617 |
rrsets.append(rrset) |
| 618 |
self.manager.set_rrsets(rrsets) # pyright: ignore |
| 619 |
|
| 620 |
def _set_origin(self, origin): |
| 621 |
pass |
| 622 |
|
| 623 |
def _iterate_rdatasets(self): |
| 624 |
raise NotImplementedError # pragma: no cover |
| 625 |
|
| 626 |
def _iterate_names(self): |
| 627 |
raise NotImplementedError # pragma: no cover |
| 628 |
|
| 629 |
|
| 630 |
class RRSetsReaderManager(dns.transaction.TransactionManager): |
| 631 |
def __init__( |
| 632 |
self, |
| 633 |
origin: dns.name.Name | None = dns.name.root, |
| 634 |
relativize: bool = False, |
| 635 |
rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, |
| 636 |
): |
| 637 |
self.origin = origin |
| 638 |
self.relativize = relativize |
| 639 |
self.rdclass = rdclass |
| 640 |
self.rrsets: List[dns.rrset.RRset] = [] |
| 641 |
|
| 642 |
def reader(self): # pragma: no cover |
| 643 |
raise NotImplementedError |
| 644 |
|
| 645 |
def writer(self, replacement=False): |
| 646 |
assert replacement is True |
| 647 |
return RRsetsReaderTransaction(self, True, False) |
| 648 |
|
| 649 |
def get_class(self): |
| 650 |
return self.rdclass |
| 651 |
|
| 652 |
def origin_information(self): |
| 653 |
if self.relativize: |
| 654 |
effective = dns.name.empty |
| 655 |
else: |
| 656 |
effective = self.origin |
| 657 |
return (self.origin, self.relativize, effective) |
| 658 |
|
| 659 |
def set_rrsets(self, rrsets: List[dns.rrset.RRset]) -> None: |
| 660 |
self.rrsets = rrsets |
| 661 |
|
| 662 |
|
| 663 |
def read_rrsets( |
| 664 |
text: Any, |
| 665 |
name: dns.name.Name | str | None = None, |
| 666 |
ttl: int | None = None, |
| 667 |
rdclass: dns.rdataclass.RdataClass | str | None = dns.rdataclass.IN, |
| 668 |
default_rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 669 |
rdtype: dns.rdatatype.RdataType | str | None = None, |
| 670 |
default_ttl: int | str | None = None, |
| 671 |
idna_codec: dns.name.IDNACodec | None = None, |
| 672 |
origin: dns.name.Name | str | None = dns.name.root, |
| 673 |
relativize: bool = False, |
| 674 |
) -> List[dns.rrset.RRset]: |
| 675 |
"""Read one or more rrsets from the specified text, possibly subject |
| 676 |
to restrictions. |
| 677 |
|
| 678 |
*text*, a file object or a string, is the input to process. |
| 679 |
|
| 680 |
*name*, a string, ``dns.name.Name``, or ``None``, is the owner name of |
| 681 |
the rrset. If not ``None``, then the owner name is "forced", and the |
| 682 |
input must not specify an owner name. If ``None``, then any owner names |
| 683 |
are allowed and must be present in the input. |
| 684 |
|
| 685 |
*ttl*, an ``int``, string, or None. If not ``None``, the the TTL is |
| 686 |
forced to be the specified value and the input must not specify a TTL. |
| 687 |
If ``None``, then a TTL may be specified in the input. If it is not |
| 688 |
specified, then the *default_ttl* will be used. |
| 689 |
|
| 690 |
*rdclass*, a ``dns.rdataclass.RdataClass``, string, or ``None``. If |
| 691 |
not ``None``, then the class is forced to the specified value, and the |
| 692 |
input must not specify a class. If ``None``, then the input may specify |
| 693 |
a class that matches *default_rdclass*. Note that it is not possible to |
| 694 |
return rrsets with differing classes; specifying ``None`` for the class |
| 695 |
simply allows the user to optionally type a class as that may be convenient |
| 696 |
when cutting and pasting. |
| 697 |
|
| 698 |
*default_rdclass*, a ``dns.rdataclass.RdataClass`` or string. The class |
| 699 |
of the returned rrsets. |
| 700 |
|
| 701 |
*rdtype*, a ``dns.rdatatype.RdataType``, string, or ``None``. If not |
| 702 |
``None``, then the type is forced to the specified value, and the |
| 703 |
input must not specify a type. If ``None``, then a type must be present |
| 704 |
for each RR. |
| 705 |
|
| 706 |
*default_ttl*, an ``int``, string, or ``None``. If not ``None``, then if |
| 707 |
the TTL is not forced and is not specified, then this value will be used. |
| 708 |
if ``None``, then if the TTL is not forced an error will occur if the TTL |
| 709 |
is not specified. |
| 710 |
|
| 711 |
*idna_codec*, a ``dns.name.IDNACodec``, specifies the IDNA |
| 712 |
encoder/decoder. If ``None``, the default IDNA 2003 encoder/decoder |
| 713 |
is used. Note that codecs only apply to the owner name; dnspython does |
| 714 |
not do IDNA for names in rdata, as there is no IDNA zonefile format. |
| 715 |
|
| 716 |
*origin*, a string, ``dns.name.Name``, or ``None``, is the origin for any |
| 717 |
relative names in the input, and also the origin to relativize to if |
| 718 |
*relativize* is ``True``. |
| 719 |
|
| 720 |
*relativize*, a bool. If ``True``, names are relativized to the *origin*; |
| 721 |
if ``False`` then any relative names in the input are made absolute by |
| 722 |
appending the *origin*. |
| 723 |
""" |
| 724 |
if isinstance(origin, str): |
| 725 |
origin = dns.name.from_text(origin, dns.name.root, idna_codec) |
| 726 |
if isinstance(name, str): |
| 727 |
name = dns.name.from_text(name, origin, idna_codec) |
| 728 |
if isinstance(ttl, str): |
| 729 |
ttl = dns.ttl.from_text(ttl) |
| 730 |
if isinstance(default_ttl, str): |
| 731 |
default_ttl = dns.ttl.from_text(default_ttl) |
| 732 |
if rdclass is not None: |
| 733 |
rdclass = dns.rdataclass.RdataClass.make(rdclass) |
| 734 |
else: |
| 735 |
rdclass = None |
| 736 |
default_rdclass = dns.rdataclass.RdataClass.make(default_rdclass) |
| 737 |
if rdtype is not None: |
| 738 |
rdtype = dns.rdatatype.RdataType.make(rdtype) |
| 739 |
else: |
| 740 |
rdtype = None |
| 741 |
manager = RRSetsReaderManager(origin, relativize, default_rdclass) |
| 742 |
with manager.writer(True) as txn: |
| 743 |
tok = dns.tokenizer.Tokenizer(text, "<input>", idna_codec=idna_codec) |
| 744 |
reader = Reader( |
| 745 |
tok, |
| 746 |
default_rdclass, |
| 747 |
txn, |
| 748 |
allow_directives=False, |
| 749 |
force_name=name, |
| 750 |
force_ttl=ttl, |
| 751 |
force_rdclass=rdclass, |
| 752 |
force_rdtype=rdtype, |
| 753 |
default_ttl=default_ttl, |
| 754 |
) |
| 755 |
reader.read() |
| 756 |
return manager.rrsets |