| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
# Copyright (C) 2003-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 stub resolver.""" |
| 19 |
|
| 20 |
import contextlib |
| 21 |
import random |
| 22 |
import socket |
| 23 |
import sys |
| 24 |
import threading |
| 25 |
import time |
| 26 |
import warnings |
| 27 |
from typing import Any, Dict, Iterator, List, Sequence, Tuple, cast |
| 28 |
from urllib.parse import urlparse |
| 29 |
|
| 30 |
import dns._ddr |
| 31 |
import dns.edns |
| 32 |
import dns.exception |
| 33 |
import dns.flags |
| 34 |
import dns.inet |
| 35 |
import dns.ipv4 |
| 36 |
import dns.ipv6 |
| 37 |
import dns.message |
| 38 |
import dns.name |
| 39 |
import dns.nameserver |
| 40 |
import dns.query |
| 41 |
import dns.rcode |
| 42 |
import dns.rdata |
| 43 |
import dns.rdataclass |
| 44 |
import dns.rdatatype |
| 45 |
import dns.rdtypes.ANY.PTR |
| 46 |
import dns.rdtypes.svcbbase |
| 47 |
import dns.reversename |
| 48 |
import dns.tsig |
| 49 |
|
| 50 |
if sys.platform == "win32": # pragma: no cover |
| 51 |
import dns.win32util |
| 52 |
|
| 53 |
|
| 54 |
class NXDOMAIN(dns.exception.DNSException): |
| 55 |
"""The DNS query name does not exist.""" |
| 56 |
|
| 57 |
supp_kwargs = {"qnames", "responses"} |
| 58 |
fmt = None # we have our own __str__ implementation |
| 59 |
|
| 60 |
# pylint: disable=arguments-differ |
| 61 |
|
| 62 |
# We do this as otherwise mypy complains about unexpected keyword argument |
| 63 |
# idna_exception |
| 64 |
def __init__(self, *args, **kwargs): |
| 65 |
super().__init__(*args, **kwargs) |
| 66 |
|
| 67 |
def _check_kwargs(self, qnames, responses=None): # pyright: ignore |
| 68 |
if not isinstance(qnames, list | tuple | set): |
| 69 |
raise AttributeError("qnames must be a list, tuple or set") |
| 70 |
if len(qnames) == 0: |
| 71 |
raise AttributeError("qnames must contain at least one element") |
| 72 |
if responses is None: |
| 73 |
responses = {} |
| 74 |
elif not isinstance(responses, dict): |
| 75 |
raise AttributeError("responses must be a dict(qname=response)") |
| 76 |
kwargs = dict(qnames=qnames, responses=responses) |
| 77 |
return kwargs |
| 78 |
|
| 79 |
def __str__(self) -> str: |
| 80 |
if "qnames" not in self.kwargs: |
| 81 |
return super().__str__() |
| 82 |
qnames = self.kwargs["qnames"] |
| 83 |
if len(qnames) > 1: |
| 84 |
msg = "None of DNS query names exist" |
| 85 |
else: |
| 86 |
msg = "The DNS query name does not exist" |
| 87 |
qnames = ", ".join(map(str, qnames)) |
| 88 |
return f"{msg}: {qnames}" |
| 89 |
|
| 90 |
@property |
| 91 |
def canonical_name(self): |
| 92 |
"""Return the unresolved canonical name.""" |
| 93 |
if "qnames" not in self.kwargs: |
| 94 |
raise TypeError("parametrized exception required") |
| 95 |
for qname in self.kwargs["qnames"]: |
| 96 |
response = self.kwargs["responses"][qname] |
| 97 |
try: |
| 98 |
cname = response.canonical_name() |
| 99 |
if cname != qname: |
| 100 |
return cname |
| 101 |
except Exception: # pragma: no cover |
| 102 |
# We can just eat this exception as it means there was |
| 103 |
# something wrong with the response. |
| 104 |
pass |
| 105 |
return self.kwargs["qnames"][0] |
| 106 |
|
| 107 |
def __add__(self, e_nx): |
| 108 |
"""Augment by results from another NXDOMAIN exception.""" |
| 109 |
qnames0 = list(self.kwargs.get("qnames", [])) |
| 110 |
responses0 = dict(self.kwargs.get("responses", {})) |
| 111 |
responses1 = e_nx.kwargs.get("responses", {}) |
| 112 |
for qname1 in e_nx.kwargs.get("qnames", []): |
| 113 |
if qname1 not in qnames0: |
| 114 |
qnames0.append(qname1) |
| 115 |
if qname1 in responses1: |
| 116 |
responses0[qname1] = responses1[qname1] |
| 117 |
return NXDOMAIN(qnames=qnames0, responses=responses0) |
| 118 |
|
| 119 |
def qnames(self): |
| 120 |
"""All of the names that were tried. |
| 121 |
|
| 122 |
Returns a list of ``dns.name.Name``. |
| 123 |
""" |
| 124 |
return self.kwargs["qnames"] |
| 125 |
|
| 126 |
def responses(self): |
| 127 |
"""A map from queried names to their NXDOMAIN responses. |
| 128 |
|
| 129 |
Returns a dict mapping a ``dns.name.Name`` to a |
| 130 |
``dns.message.Message``. |
| 131 |
""" |
| 132 |
return self.kwargs["responses"] |
| 133 |
|
| 134 |
def response(self, qname): |
| 135 |
"""The response for query *qname*. |
| 136 |
|
| 137 |
Returns a ``dns.message.Message``. |
| 138 |
""" |
| 139 |
return self.kwargs["responses"][qname] |
| 140 |
|
| 141 |
|
| 142 |
class YXDOMAIN(dns.exception.DNSException): |
| 143 |
"""The DNS query name is too long after DNAME substitution.""" |
| 144 |
|
| 145 |
|
| 146 |
ErrorTuple = Tuple[ |
| 147 |
str | None, |
| 148 |
bool, |
| 149 |
int, |
| 150 |
Exception | str, |
| 151 |
dns.message.Message | None, |
| 152 |
] |
| 153 |
|
| 154 |
|
| 155 |
def _errors_to_text(errors: List[ErrorTuple]) -> List[str]: |
| 156 |
"""Turn a resolution errors trace into a list of text.""" |
| 157 |
texts = [] |
| 158 |
for err in errors: |
| 159 |
texts.append(f"Server {err[0]} answered {err[3]}") |
| 160 |
return texts |
| 161 |
|
| 162 |
|
| 163 |
class LifetimeTimeout(dns.exception.Timeout): |
| 164 |
"""The resolution lifetime expired.""" |
| 165 |
|
| 166 |
msg = "The resolution lifetime expired." |
| 167 |
fmt = f"{msg[:-1]} after {{timeout:.3f}} seconds: {{errors}}" |
| 168 |
supp_kwargs = {"timeout", "errors"} |
| 169 |
|
| 170 |
# We do this as otherwise mypy complains about unexpected keyword argument |
| 171 |
# idna_exception |
| 172 |
def __init__(self, *args, **kwargs): |
| 173 |
super().__init__(*args, **kwargs) |
| 174 |
|
| 175 |
def _fmt_kwargs(self, **kwargs): |
| 176 |
srv_msgs = _errors_to_text(kwargs["errors"]) |
| 177 |
return super()._fmt_kwargs( |
| 178 |
timeout=kwargs["timeout"], errors="; ".join(srv_msgs) |
| 179 |
) |
| 180 |
|
| 181 |
|
| 182 |
# We added more detail to resolution timeouts, but they are still |
| 183 |
# subclasses of dns.exception.Timeout for backwards compatibility. We also |
| 184 |
# keep dns.resolver.Timeout defined for backwards compatibility. |
| 185 |
Timeout = LifetimeTimeout |
| 186 |
|
| 187 |
|
| 188 |
class NoAnswer(dns.exception.DNSException): |
| 189 |
"""The DNS response does not contain an answer to the question.""" |
| 190 |
|
| 191 |
fmt = "The DNS response does not contain an answer to the question: {query}" |
| 192 |
supp_kwargs = {"response"} |
| 193 |
|
| 194 |
# We do this as otherwise mypy complains about unexpected keyword argument |
| 195 |
# idna_exception |
| 196 |
def __init__(self, *args, **kwargs): |
| 197 |
super().__init__(*args, **kwargs) |
| 198 |
|
| 199 |
def _fmt_kwargs(self, **kwargs): |
| 200 |
return super()._fmt_kwargs(query=kwargs["response"].question) |
| 201 |
|
| 202 |
def response(self): |
| 203 |
return self.kwargs["response"] |
| 204 |
|
| 205 |
|
| 206 |
class NoNameservers(dns.exception.DNSException): |
| 207 |
"""All nameservers failed to answer the query. |
| 208 |
|
| 209 |
errors: list of servers and respective errors |
| 210 |
The type of errors is |
| 211 |
[(server IP address, any object convertible to string)]. |
| 212 |
Non-empty errors list will add explanatory message () |
| 213 |
""" |
| 214 |
|
| 215 |
msg = "All nameservers failed to answer the query." |
| 216 |
fmt = f"{msg[:-1]} {{query}}: {{errors}}" |
| 217 |
supp_kwargs = {"request", "errors"} |
| 218 |
|
| 219 |
# We do this as otherwise mypy complains about unexpected keyword argument |
| 220 |
# idna_exception |
| 221 |
def __init__(self, *args, **kwargs): |
| 222 |
super().__init__(*args, **kwargs) |
| 223 |
|
| 224 |
def _fmt_kwargs(self, **kwargs): |
| 225 |
srv_msgs = _errors_to_text(kwargs["errors"]) |
| 226 |
return super()._fmt_kwargs( |
| 227 |
query=kwargs["request"].question, errors="; ".join(srv_msgs) |
| 228 |
) |
| 229 |
|
| 230 |
|
| 231 |
class NotAbsolute(dns.exception.DNSException): |
| 232 |
"""An absolute domain name is required but a relative name was provided.""" |
| 233 |
|
| 234 |
|
| 235 |
class NoRootSOA(dns.exception.DNSException): |
| 236 |
"""There is no SOA RR at the DNS root name. This should never happen!""" |
| 237 |
|
| 238 |
|
| 239 |
class NoMetaqueries(dns.exception.DNSException): |
| 240 |
"""DNS metaqueries are not allowed.""" |
| 241 |
|
| 242 |
|
| 243 |
class NoResolverConfiguration(dns.exception.DNSException): |
| 244 |
"""Resolver configuration could not be read or specified no nameservers.""" |
| 245 |
|
| 246 |
|
| 247 |
class Answer: |
| 248 |
"""DNS stub resolver answer. |
| 249 |
|
| 250 |
Instances of this class bundle up the result of a successful DNS |
| 251 |
resolution. |
| 252 |
|
| 253 |
For convenience, the answer object implements much of the sequence |
| 254 |
protocol, forwarding to its ``rrset`` attribute. E.g. |
| 255 |
``for a in answer`` is equivalent to ``for a in answer.rrset``. |
| 256 |
``answer[i]`` is equivalent to ``answer.rrset[i]``, and |
| 257 |
``answer[i:j]`` is equivalent to ``answer.rrset[i:j]``. |
| 258 |
|
| 259 |
Note that CNAMEs or DNAMEs in the response may mean that answer |
| 260 |
RRset's name might not be the query name. |
| 261 |
""" |
| 262 |
|
| 263 |
def __init__( |
| 264 |
self, |
| 265 |
qname: dns.name.Name, |
| 266 |
rdtype: dns.rdatatype.RdataType, |
| 267 |
rdclass: dns.rdataclass.RdataClass, |
| 268 |
response: dns.message.QueryMessage, |
| 269 |
nameserver: str | None = None, |
| 270 |
port: int | None = None, |
| 271 |
) -> None: |
| 272 |
self.qname = qname |
| 273 |
self.rdtype = rdtype |
| 274 |
self.rdclass = rdclass |
| 275 |
self.response = response |
| 276 |
self.nameserver = nameserver |
| 277 |
self.port = port |
| 278 |
self.chaining_result = response.resolve_chaining() |
| 279 |
# Copy some attributes out of chaining_result for backwards |
| 280 |
# compatibility and convenience. |
| 281 |
self.canonical_name = self.chaining_result.canonical_name |
| 282 |
self.rrset = self.chaining_result.answer |
| 283 |
self.expiration = time.time() + self.chaining_result.minimum_ttl |
| 284 |
|
| 285 |
def __getattr__(self, attr): # pragma: no cover |
| 286 |
if self.rrset is not None: |
| 287 |
if attr == "name": |
| 288 |
return self.rrset.name |
| 289 |
elif attr == "ttl": |
| 290 |
return self.rrset.ttl |
| 291 |
elif attr == "covers": |
| 292 |
return self.rrset.covers |
| 293 |
elif attr == "rdclass": |
| 294 |
return self.rrset.rdclass |
| 295 |
elif attr == "rdtype": |
| 296 |
return self.rrset.rdtype |
| 297 |
else: |
| 298 |
raise AttributeError(attr) |
| 299 |
|
| 300 |
def __len__(self) -> int: |
| 301 |
return self.rrset is not None and len(self.rrset) or 0 |
| 302 |
|
| 303 |
def __iter__(self) -> Iterator[Any]: |
| 304 |
return self.rrset is not None and iter(self.rrset) or iter(tuple()) |
| 305 |
|
| 306 |
def __getitem__(self, i): |
| 307 |
if self.rrset is None: |
| 308 |
raise IndexError |
| 309 |
return self.rrset[i] |
| 310 |
|
| 311 |
def __delitem__(self, i): |
| 312 |
if self.rrset is None: |
| 313 |
raise IndexError |
| 314 |
del self.rrset[i] |
| 315 |
|
| 316 |
|
| 317 |
class Answers(dict): |
| 318 |
"""A dict of DNS stub resolver answers, indexed by type.""" |
| 319 |
|
| 320 |
|
| 321 |
class EmptyHostAnswers(dns.exception.DNSException): |
| 322 |
"""The HostAnswers has no addresses""" |
| 323 |
|
| 324 |
|
| 325 |
class HostAnswers(Answers): |
| 326 |
"""A dict of DNS stub resolver answers to a host name lookup, indexed by |
| 327 |
type. |
| 328 |
""" |
| 329 |
|
| 330 |
@classmethod |
| 331 |
def make( |
| 332 |
cls, |
| 333 |
v6: Answer | None = None, |
| 334 |
v4: Answer | None = None, |
| 335 |
add_empty: bool = True, |
| 336 |
) -> "HostAnswers": |
| 337 |
answers = HostAnswers() |
| 338 |
if v6 is not None and (add_empty or v6.rrset): |
| 339 |
answers[dns.rdatatype.AAAA] = v6 |
| 340 |
if v4 is not None and (add_empty or v4.rrset): |
| 341 |
answers[dns.rdatatype.A] = v4 |
| 342 |
return answers |
| 343 |
|
| 344 |
# Returns pairs of (address, family) from this result, potentially |
| 345 |
# filtering by address family. |
| 346 |
def addresses_and_families( |
| 347 |
self, family: int = socket.AF_UNSPEC |
| 348 |
) -> Iterator[Tuple[str, int]]: |
| 349 |
if family == socket.AF_UNSPEC: |
| 350 |
yield from self.addresses_and_families(socket.AF_INET6) |
| 351 |
yield from self.addresses_and_families(socket.AF_INET) |
| 352 |
return |
| 353 |
elif family == socket.AF_INET6: |
| 354 |
answer = self.get(dns.rdatatype.AAAA) |
| 355 |
elif family == socket.AF_INET: |
| 356 |
answer = self.get(dns.rdatatype.A) |
| 357 |
else: # pragma: no cover |
| 358 |
raise NotImplementedError(f"unknown address family {family}") |
| 359 |
if answer: |
| 360 |
for rdata in answer: |
| 361 |
yield (rdata.address, family) |
| 362 |
|
| 363 |
# Returns addresses from this result, potentially filtering by |
| 364 |
# address family. |
| 365 |
def addresses(self, family: int = socket.AF_UNSPEC) -> Iterator[str]: |
| 366 |
return (pair[0] for pair in self.addresses_and_families(family)) |
| 367 |
|
| 368 |
# Returns the canonical name from this result. |
| 369 |
def canonical_name(self) -> dns.name.Name: |
| 370 |
answer = self.get(dns.rdatatype.AAAA, self.get(dns.rdatatype.A)) |
| 371 |
if answer is None: |
| 372 |
raise EmptyHostAnswers |
| 373 |
return answer.canonical_name |
| 374 |
|
| 375 |
|
| 376 |
class CacheStatistics: |
| 377 |
"""Cache Statistics""" |
| 378 |
|
| 379 |
def __init__(self, hits: int = 0, misses: int = 0) -> None: |
| 380 |
self.hits = hits |
| 381 |
self.misses = misses |
| 382 |
|
| 383 |
def reset(self) -> None: |
| 384 |
self.hits = 0 |
| 385 |
self.misses = 0 |
| 386 |
|
| 387 |
def clone(self) -> "CacheStatistics": |
| 388 |
return CacheStatistics(self.hits, self.misses) |
| 389 |
|
| 390 |
|
| 391 |
class CacheBase: |
| 392 |
def __init__(self) -> None: |
| 393 |
self.lock = threading.Lock() |
| 394 |
self.statistics = CacheStatistics() |
| 395 |
|
| 396 |
def reset_statistics(self) -> None: |
| 397 |
"""Reset all statistics to zero.""" |
| 398 |
with self.lock: |
| 399 |
self.statistics.reset() |
| 400 |
|
| 401 |
def hits(self) -> int: |
| 402 |
"""How many hits has the cache had?""" |
| 403 |
with self.lock: |
| 404 |
return self.statistics.hits |
| 405 |
|
| 406 |
def misses(self) -> int: |
| 407 |
"""How many misses has the cache had?""" |
| 408 |
with self.lock: |
| 409 |
return self.statistics.misses |
| 410 |
|
| 411 |
def get_statistics_snapshot(self) -> CacheStatistics: |
| 412 |
"""Return a consistent snapshot of all the statistics. |
| 413 |
|
| 414 |
If running with multiple threads, it's better to take a |
| 415 |
snapshot than to call statistics methods such as hits() and |
| 416 |
misses() individually. |
| 417 |
""" |
| 418 |
with self.lock: |
| 419 |
return self.statistics.clone() |
| 420 |
|
| 421 |
|
| 422 |
CacheKey = Tuple[dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass] |
| 423 |
|
| 424 |
|
| 425 |
class Cache(CacheBase): |
| 426 |
"""Simple thread-safe DNS answer cache.""" |
| 427 |
|
| 428 |
def __init__(self, cleaning_interval: float = 300.0) -> None: |
| 429 |
"""*cleaning_interval*, a ``float`` is the number of seconds between |
| 430 |
periodic cleanings. |
| 431 |
""" |
| 432 |
|
| 433 |
super().__init__() |
| 434 |
self.data: Dict[CacheKey, Answer] = {} |
| 435 |
self.cleaning_interval = cleaning_interval |
| 436 |
self.next_cleaning: float = time.time() + self.cleaning_interval |
| 437 |
|
| 438 |
def _maybe_clean(self) -> None: |
| 439 |
"""Clean the cache if it's time to do so.""" |
| 440 |
|
| 441 |
now = time.time() |
| 442 |
if self.next_cleaning <= now: |
| 443 |
keys_to_delete = [] |
| 444 |
for k, v in self.data.items(): |
| 445 |
if v.expiration <= now: |
| 446 |
keys_to_delete.append(k) |
| 447 |
for k in keys_to_delete: |
| 448 |
del self.data[k] |
| 449 |
now = time.time() |
| 450 |
self.next_cleaning = now + self.cleaning_interval |
| 451 |
|
| 452 |
def get(self, key: CacheKey) -> Answer | None: |
| 453 |
"""Get the answer associated with *key*. |
| 454 |
|
| 455 |
Returns None if no answer is cached for the key. |
| 456 |
|
| 457 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 458 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 459 |
|
| 460 |
Returns a ``dns.resolver.Answer`` or ``None``. |
| 461 |
""" |
| 462 |
|
| 463 |
with self.lock: |
| 464 |
self._maybe_clean() |
| 465 |
v = self.data.get(key) |
| 466 |
if v is None or v.expiration <= time.time(): |
| 467 |
self.statistics.misses += 1 |
| 468 |
return None |
| 469 |
self.statistics.hits += 1 |
| 470 |
return v |
| 471 |
|
| 472 |
def put(self, key: CacheKey, value: Answer) -> None: |
| 473 |
"""Associate key and value in the cache. |
| 474 |
|
| 475 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 476 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 477 |
|
| 478 |
*value*, a ``dns.resolver.Answer``, the answer. |
| 479 |
""" |
| 480 |
|
| 481 |
with self.lock: |
| 482 |
self._maybe_clean() |
| 483 |
self.data[key] = value |
| 484 |
|
| 485 |
def flush(self, key: CacheKey | None = None) -> None: |
| 486 |
"""Flush the cache. |
| 487 |
|
| 488 |
If *key* is not ``None``, only that item is flushed. Otherwise the entire cache |
| 489 |
is flushed. |
| 490 |
|
| 491 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 492 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 493 |
""" |
| 494 |
|
| 495 |
with self.lock: |
| 496 |
if key is not None: |
| 497 |
if key in self.data: |
| 498 |
del self.data[key] |
| 499 |
else: |
| 500 |
self.data = {} |
| 501 |
self.next_cleaning = time.time() + self.cleaning_interval |
| 502 |
|
| 503 |
|
| 504 |
class LRUCacheNode: |
| 505 |
"""LRUCache node.""" |
| 506 |
|
| 507 |
def __init__(self, key, value): |
| 508 |
self.key = key |
| 509 |
self.value = value |
| 510 |
self.hits = 0 |
| 511 |
self.prev = self |
| 512 |
self.next = self |
| 513 |
|
| 514 |
def link_after(self, node: "LRUCacheNode") -> None: |
| 515 |
self.prev = node |
| 516 |
self.next = node.next |
| 517 |
node.next.prev = self |
| 518 |
node.next = self |
| 519 |
|
| 520 |
def unlink(self) -> None: |
| 521 |
self.next.prev = self.prev |
| 522 |
self.prev.next = self.next |
| 523 |
|
| 524 |
|
| 525 |
class LRUCache(CacheBase): |
| 526 |
"""Thread-safe, bounded, least-recently-used DNS answer cache. |
| 527 |
|
| 528 |
This cache is better than the simple cache (above) if you're |
| 529 |
running a web crawler or other process that does a lot of |
| 530 |
resolutions. The LRUCache has a maximum number of nodes, and when |
| 531 |
it is full, the least-recently used node is removed to make space |
| 532 |
for a new one. |
| 533 |
""" |
| 534 |
|
| 535 |
def __init__(self, max_size: int = 100000) -> None: |
| 536 |
"""*max_size*, an ``int``, is the maximum number of nodes to cache; |
| 537 |
it must be greater than 0. |
| 538 |
""" |
| 539 |
|
| 540 |
super().__init__() |
| 541 |
self.data: Dict[CacheKey, LRUCacheNode] = {} |
| 542 |
self.set_max_size(max_size) |
| 543 |
self.sentinel: LRUCacheNode = LRUCacheNode(None, None) |
| 544 |
self.sentinel.prev = self.sentinel |
| 545 |
self.sentinel.next = self.sentinel |
| 546 |
|
| 547 |
def set_max_size(self, max_size: int) -> None: |
| 548 |
if max_size < 1: |
| 549 |
max_size = 1 |
| 550 |
self.max_size = max_size |
| 551 |
|
| 552 |
def get(self, key: CacheKey) -> Answer | None: |
| 553 |
"""Get the answer associated with *key*. |
| 554 |
|
| 555 |
Returns None if no answer is cached for the key. |
| 556 |
|
| 557 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 558 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 559 |
|
| 560 |
Returns a ``dns.resolver.Answer`` or ``None``. |
| 561 |
""" |
| 562 |
|
| 563 |
with self.lock: |
| 564 |
node = self.data.get(key) |
| 565 |
if node is None: |
| 566 |
self.statistics.misses += 1 |
| 567 |
return None |
| 568 |
# Unlink because we're either going to move the node to the front |
| 569 |
# of the LRU list or we're going to free it. |
| 570 |
node.unlink() |
| 571 |
if node.value.expiration <= time.time(): |
| 572 |
del self.data[node.key] |
| 573 |
self.statistics.misses += 1 |
| 574 |
return None |
| 575 |
node.link_after(self.sentinel) |
| 576 |
self.statistics.hits += 1 |
| 577 |
node.hits += 1 |
| 578 |
return node.value |
| 579 |
|
| 580 |
def get_hits_for_key(self, key: CacheKey) -> int: |
| 581 |
"""Return the number of cache hits associated with the specified key.""" |
| 582 |
with self.lock: |
| 583 |
node = self.data.get(key) |
| 584 |
if node is None or node.value.expiration <= time.time(): |
| 585 |
return 0 |
| 586 |
else: |
| 587 |
return node.hits |
| 588 |
|
| 589 |
def put(self, key: CacheKey, value: Answer) -> None: |
| 590 |
"""Associate key and value in the cache. |
| 591 |
|
| 592 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 593 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 594 |
|
| 595 |
*value*, a ``dns.resolver.Answer``, the answer. |
| 596 |
""" |
| 597 |
|
| 598 |
with self.lock: |
| 599 |
node = self.data.get(key) |
| 600 |
if node is not None: |
| 601 |
node.unlink() |
| 602 |
del self.data[node.key] |
| 603 |
while len(self.data) >= self.max_size: |
| 604 |
gnode = self.sentinel.prev |
| 605 |
gnode.unlink() |
| 606 |
del self.data[gnode.key] |
| 607 |
node = LRUCacheNode(key, value) |
| 608 |
node.link_after(self.sentinel) |
| 609 |
self.data[key] = node |
| 610 |
|
| 611 |
def flush(self, key: CacheKey | None = None) -> None: |
| 612 |
"""Flush the cache. |
| 613 |
|
| 614 |
If *key* is not ``None``, only that item is flushed. Otherwise the entire cache |
| 615 |
is flushed. |
| 616 |
|
| 617 |
*key*, a ``(dns.name.Name, dns.rdatatype.RdataType, dns.rdataclass.RdataClass)`` |
| 618 |
tuple whose values are the query name, rdtype, and rdclass respectively. |
| 619 |
""" |
| 620 |
|
| 621 |
with self.lock: |
| 622 |
if key is not None: |
| 623 |
node = self.data.get(key) |
| 624 |
if node is not None: |
| 625 |
node.unlink() |
| 626 |
del self.data[node.key] |
| 627 |
else: |
| 628 |
gnode = self.sentinel.next |
| 629 |
while gnode != self.sentinel: |
| 630 |
next = gnode.next |
| 631 |
gnode.unlink() |
| 632 |
gnode = next |
| 633 |
self.data = {} |
| 634 |
|
| 635 |
|
| 636 |
class _Resolution: |
| 637 |
"""Helper class for dns.resolver.Resolver.resolve(). |
| 638 |
|
| 639 |
All of the "business logic" of resolution is encapsulated in this |
| 640 |
class, allowing us to have multiple resolve() implementations |
| 641 |
using different I/O schemes without copying all of the |
| 642 |
complicated logic. |
| 643 |
|
| 644 |
This class is a "friend" to dns.resolver.Resolver and manipulates |
| 645 |
resolver data structures directly. |
| 646 |
""" |
| 647 |
|
| 648 |
def __init__( |
| 649 |
self, |
| 650 |
resolver: "BaseResolver", |
| 651 |
qname: dns.name.Name | str, |
| 652 |
rdtype: dns.rdatatype.RdataType | str, |
| 653 |
rdclass: dns.rdataclass.RdataClass | str, |
| 654 |
tcp: bool, |
| 655 |
raise_on_no_answer: bool, |
| 656 |
search: bool | None, |
| 657 |
) -> None: |
| 658 |
if isinstance(qname, str): |
| 659 |
qname = dns.name.from_text(qname, None) |
| 660 |
rdtype = dns.rdatatype.RdataType.make(rdtype) |
| 661 |
if dns.rdatatype.is_metatype(rdtype): |
| 662 |
raise NoMetaqueries |
| 663 |
rdclass = dns.rdataclass.RdataClass.make(rdclass) |
| 664 |
if dns.rdataclass.is_metaclass(rdclass): |
| 665 |
raise NoMetaqueries |
| 666 |
self.resolver = resolver |
| 667 |
self.qnames_to_try = resolver._get_qnames_to_try(qname, search) |
| 668 |
self.qnames = self.qnames_to_try[:] |
| 669 |
self.rdtype = rdtype |
| 670 |
self.rdclass = rdclass |
| 671 |
self.tcp = tcp |
| 672 |
self.raise_on_no_answer = raise_on_no_answer |
| 673 |
self.nxdomain_responses: Dict[dns.name.Name, dns.message.QueryMessage] = {} |
| 674 |
# Initialize other things to help analysis tools |
| 675 |
self.qname = dns.name.empty |
| 676 |
self.nameservers: List[dns.nameserver.Nameserver] = [] |
| 677 |
self.current_nameservers: List[dns.nameserver.Nameserver] = [] |
| 678 |
self.errors: List[ErrorTuple] = [] |
| 679 |
self.nameserver: dns.nameserver.Nameserver | None = None |
| 680 |
self.tcp_attempt = False |
| 681 |
self.retry_with_tcp = False |
| 682 |
self.request: dns.message.QueryMessage | None = None |
| 683 |
self.backoff = 0.0 |
| 684 |
|
| 685 |
def next_request( |
| 686 |
self, |
| 687 |
) -> Tuple[dns.message.QueryMessage | None, Answer | None]: |
| 688 |
"""Get the next request to send, and check the cache. |
| 689 |
|
| 690 |
Returns a (request, answer) tuple. At most one of request or |
| 691 |
answer will not be None. |
| 692 |
""" |
| 693 |
|
| 694 |
# We return a tuple instead of Union[Message,Answer] as it lets |
| 695 |
# the caller avoid isinstance(). |
| 696 |
|
| 697 |
while len(self.qnames) > 0: |
| 698 |
self.qname = self.qnames.pop(0) |
| 699 |
|
| 700 |
# Do we know the answer? |
| 701 |
if self.resolver.cache: |
| 702 |
answer = self.resolver.cache.get( |
| 703 |
(self.qname, self.rdtype, self.rdclass) |
| 704 |
) |
| 705 |
if answer is not None: |
| 706 |
if answer.rrset is None and self.raise_on_no_answer: |
| 707 |
raise NoAnswer(response=answer.response) |
| 708 |
else: |
| 709 |
return (None, answer) |
| 710 |
answer = self.resolver.cache.get( |
| 711 |
(self.qname, dns.rdatatype.ANY, self.rdclass) |
| 712 |
) |
| 713 |
if answer is not None and answer.response.rcode() == dns.rcode.NXDOMAIN: |
| 714 |
# cached NXDOMAIN; record it and continue to next |
| 715 |
# name. |
| 716 |
self.nxdomain_responses[self.qname] = answer.response |
| 717 |
continue |
| 718 |
|
| 719 |
# Build the request |
| 720 |
request = dns.message.make_query(self.qname, self.rdtype, self.rdclass) |
| 721 |
if self.resolver.keyname is not None: |
| 722 |
request.use_tsig( |
| 723 |
self.resolver.keyring, |
| 724 |
self.resolver.keyname, |
| 725 |
algorithm=self.resolver.keyalgorithm, |
| 726 |
) |
| 727 |
request.use_edns( |
| 728 |
self.resolver.edns, |
| 729 |
self.resolver.ednsflags, |
| 730 |
self.resolver.payload, |
| 731 |
options=self.resolver.ednsoptions, |
| 732 |
) |
| 733 |
if self.resolver.flags is not None: |
| 734 |
request.flags = self.resolver.flags |
| 735 |
|
| 736 |
self.nameservers = self.resolver._enrich_nameservers( |
| 737 |
self.resolver._nameservers, |
| 738 |
self.resolver.nameserver_ports, |
| 739 |
self.resolver.port, |
| 740 |
) |
| 741 |
if self.resolver.rotate: |
| 742 |
random.shuffle(self.nameservers) |
| 743 |
self.current_nameservers = self.nameservers[:] |
| 744 |
self.errors = [] |
| 745 |
self.nameserver = None |
| 746 |
self.tcp_attempt = False |
| 747 |
self.retry_with_tcp = False |
| 748 |
self.request = request |
| 749 |
self.backoff = 0.10 |
| 750 |
|
| 751 |
return (request, None) |
| 752 |
|
| 753 |
# |
| 754 |
# We've tried everything and only gotten NXDOMAINs. (We know |
| 755 |
# it's only NXDOMAINs as anything else would have returned |
| 756 |
# before now.) |
| 757 |
# |
| 758 |
raise NXDOMAIN(qnames=self.qnames_to_try, responses=self.nxdomain_responses) |
| 759 |
|
| 760 |
def next_nameserver(self) -> Tuple[dns.nameserver.Nameserver, bool, float]: |
| 761 |
if self.retry_with_tcp: |
| 762 |
assert self.nameserver is not None |
| 763 |
assert not self.nameserver.is_always_max_size() |
| 764 |
self.tcp_attempt = True |
| 765 |
self.retry_with_tcp = False |
| 766 |
return (self.nameserver, True, 0) |
| 767 |
|
| 768 |
backoff = 0.0 |
| 769 |
if not self.current_nameservers: |
| 770 |
if len(self.nameservers) == 0: |
| 771 |
# Out of things to try! |
| 772 |
raise NoNameservers(request=self.request, errors=self.errors) |
| 773 |
self.current_nameservers = self.nameservers[:] |
| 774 |
backoff = self.backoff |
| 775 |
self.backoff = min(self.backoff * 2, 2) |
| 776 |
|
| 777 |
self.nameserver = self.current_nameservers.pop(0) |
| 778 |
self.tcp_attempt = self.tcp or self.nameserver.is_always_max_size() |
| 779 |
return (self.nameserver, self.tcp_attempt, backoff) |
| 780 |
|
| 781 |
def query_result( |
| 782 |
self, response: dns.message.Message | None, ex: Exception | None |
| 783 |
) -> Tuple[Answer | None, bool]: |
| 784 |
# |
| 785 |
# returns an (answer: Answer, end_loop: bool) tuple. |
| 786 |
# |
| 787 |
assert self.nameserver is not None |
| 788 |
if ex: |
| 789 |
# Exception during I/O or from_wire() |
| 790 |
assert response is None |
| 791 |
self.errors.append( |
| 792 |
( |
| 793 |
str(self.nameserver), |
| 794 |
self.tcp_attempt, |
| 795 |
self.nameserver.answer_port(), |
| 796 |
ex, |
| 797 |
response, |
| 798 |
) |
| 799 |
) |
| 800 |
if ( |
| 801 |
isinstance(ex, dns.exception.FormError) |
| 802 |
or isinstance(ex, EOFError) |
| 803 |
or isinstance(ex, OSError) |
| 804 |
or isinstance(ex, NotImplementedError) |
| 805 |
): |
| 806 |
# This nameserver is no good, take it out of the mix. |
| 807 |
self.nameservers.remove(self.nameserver) |
| 808 |
elif isinstance(ex, dns.message.Truncated): |
| 809 |
if self.tcp_attempt: |
| 810 |
# Truncation with TCP is no good! |
| 811 |
self.nameservers.remove(self.nameserver) |
| 812 |
else: |
| 813 |
self.retry_with_tcp = True |
| 814 |
return (None, False) |
| 815 |
# We got an answer! |
| 816 |
assert response is not None |
| 817 |
assert isinstance(response, dns.message.QueryMessage) |
| 818 |
rcode = response.rcode() |
| 819 |
if rcode == dns.rcode.NOERROR: |
| 820 |
try: |
| 821 |
answer = Answer( |
| 822 |
self.qname, |
| 823 |
self.rdtype, |
| 824 |
self.rdclass, |
| 825 |
response, |
| 826 |
self.nameserver.answer_nameserver(), |
| 827 |
self.nameserver.answer_port(), |
| 828 |
) |
| 829 |
except Exception as e: |
| 830 |
self.errors.append( |
| 831 |
( |
| 832 |
str(self.nameserver), |
| 833 |
self.tcp_attempt, |
| 834 |
self.nameserver.answer_port(), |
| 835 |
e, |
| 836 |
response, |
| 837 |
) |
| 838 |
) |
| 839 |
# The nameserver is no good, take it out of the mix. |
| 840 |
self.nameservers.remove(self.nameserver) |
| 841 |
return (None, False) |
| 842 |
if self.resolver.cache: |
| 843 |
self.resolver.cache.put((self.qname, self.rdtype, self.rdclass), answer) |
| 844 |
if answer.rrset is None and self.raise_on_no_answer: |
| 845 |
raise NoAnswer(response=answer.response) |
| 846 |
return (answer, True) |
| 847 |
elif rcode == dns.rcode.NXDOMAIN: |
| 848 |
# Further validate the response by making an Answer, even |
| 849 |
# if we aren't going to cache it. |
| 850 |
try: |
| 851 |
answer = Answer( |
| 852 |
self.qname, dns.rdatatype.ANY, dns.rdataclass.IN, response |
| 853 |
) |
| 854 |
except Exception as e: |
| 855 |
self.errors.append( |
| 856 |
( |
| 857 |
str(self.nameserver), |
| 858 |
self.tcp_attempt, |
| 859 |
self.nameserver.answer_port(), |
| 860 |
e, |
| 861 |
response, |
| 862 |
) |
| 863 |
) |
| 864 |
# The nameserver is no good, take it out of the mix. |
| 865 |
self.nameservers.remove(self.nameserver) |
| 866 |
return (None, False) |
| 867 |
self.nxdomain_responses[self.qname] = response |
| 868 |
if self.resolver.cache: |
| 869 |
self.resolver.cache.put( |
| 870 |
(self.qname, dns.rdatatype.ANY, self.rdclass), answer |
| 871 |
) |
| 872 |
# Make next_nameserver() return None, so caller breaks its |
| 873 |
# inner loop and calls next_request(). |
| 874 |
return (None, True) |
| 875 |
elif rcode == dns.rcode.YXDOMAIN: |
| 876 |
yex = YXDOMAIN() |
| 877 |
self.errors.append( |
| 878 |
( |
| 879 |
str(self.nameserver), |
| 880 |
self.tcp_attempt, |
| 881 |
self.nameserver.answer_port(), |
| 882 |
yex, |
| 883 |
response, |
| 884 |
) |
| 885 |
) |
| 886 |
raise yex |
| 887 |
else: |
| 888 |
# |
| 889 |
# We got a response, but we're not happy with the |
| 890 |
# rcode in it. |
| 891 |
# |
| 892 |
if rcode != dns.rcode.SERVFAIL or not self.resolver.retry_servfail: |
| 893 |
self.nameservers.remove(self.nameserver) |
| 894 |
self.errors.append( |
| 895 |
( |
| 896 |
str(self.nameserver), |
| 897 |
self.tcp_attempt, |
| 898 |
self.nameserver.answer_port(), |
| 899 |
dns.rcode.to_text(rcode), |
| 900 |
response, |
| 901 |
) |
| 902 |
) |
| 903 |
return (None, False) |
| 904 |
|
| 905 |
|
| 906 |
class BaseResolver: |
| 907 |
"""DNS stub resolver.""" |
| 908 |
|
| 909 |
# We initialize in reset() |
| 910 |
# |
| 911 |
# pylint: disable=attribute-defined-outside-init |
| 912 |
|
| 913 |
domain: dns.name.Name |
| 914 |
nameserver_ports: Dict[str, int] |
| 915 |
port: int |
| 916 |
search: List[dns.name.Name] |
| 917 |
use_search_by_default: bool |
| 918 |
timeout: float |
| 919 |
lifetime: float |
| 920 |
keyring: Any | None |
| 921 |
keyname: dns.name.Name | str | None |
| 922 |
keyalgorithm: dns.name.Name | str |
| 923 |
edns: int |
| 924 |
ednsflags: int |
| 925 |
ednsoptions: List[dns.edns.Option] | None |
| 926 |
payload: int |
| 927 |
cache: Any |
| 928 |
flags: int | None |
| 929 |
retry_servfail: bool |
| 930 |
rotate: bool |
| 931 |
ndots: int | None |
| 932 |
_nameservers: Sequence[str | dns.nameserver.Nameserver] |
| 933 |
|
| 934 |
def __init__( |
| 935 |
self, filename: str = "/etc/resolv.conf", configure: bool = True |
| 936 |
) -> None: |
| 937 |
"""*filename*, a ``str`` or file object, specifying a file |
| 938 |
in standard /etc/resolv.conf format. This parameter is meaningful |
| 939 |
only when *configure* is true and the platform is POSIX. |
| 940 |
|
| 941 |
*configure*, a ``bool``. If True (the default), the resolver |
| 942 |
instance is configured in the normal fashion for the operating |
| 943 |
system the resolver is running on. (I.e. by reading a |
| 944 |
/etc/resolv.conf file on POSIX systems and from the registry |
| 945 |
on Windows systems.) |
| 946 |
""" |
| 947 |
|
| 948 |
self.reset() |
| 949 |
if configure: |
| 950 |
if sys.platform == "win32": # pragma: no cover |
| 951 |
self.read_registry() |
| 952 |
elif filename: |
| 953 |
self.read_resolv_conf(filename) |
| 954 |
|
| 955 |
def reset(self) -> None: |
| 956 |
"""Reset all resolver configuration to the defaults.""" |
| 957 |
|
| 958 |
self.domain = dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) |
| 959 |
if len(self.domain) == 0: # pragma: no cover |
| 960 |
self.domain = dns.name.root |
| 961 |
self._nameservers = [] |
| 962 |
self.nameserver_ports = {} |
| 963 |
self.port = 53 |
| 964 |
self.search = [] |
| 965 |
self.use_search_by_default = False |
| 966 |
self.timeout = 2.0 |
| 967 |
self.lifetime = 5.0 |
| 968 |
self.keyring = None |
| 969 |
self.keyname = None |
| 970 |
self.keyalgorithm = dns.tsig.default_algorithm |
| 971 |
self.edns = -1 |
| 972 |
self.ednsflags = 0 |
| 973 |
self.ednsoptions = None |
| 974 |
self.payload = 0 |
| 975 |
self.cache = None |
| 976 |
self.flags = None |
| 977 |
self.retry_servfail = False |
| 978 |
self.rotate = False |
| 979 |
self.ndots = None |
| 980 |
|
| 981 |
def read_resolv_conf(self, f: Any) -> None: |
| 982 |
"""Process *f* as a file in the /etc/resolv.conf format. If f is |
| 983 |
a ``str``, it is used as the name of the file to open; otherwise it |
| 984 |
is treated as the file itself. |
| 985 |
|
| 986 |
Interprets the following items: |
| 987 |
|
| 988 |
- nameserver - name server IP address |
| 989 |
|
| 990 |
- domain - local domain name |
| 991 |
|
| 992 |
- search - search list for host-name lookup |
| 993 |
|
| 994 |
- options - supported options are rotate, timeout, edns0, and ndots |
| 995 |
|
| 996 |
""" |
| 997 |
|
| 998 |
nameservers = [] |
| 999 |
if isinstance(f, str): |
| 1000 |
try: |
| 1001 |
cm: contextlib.AbstractContextManager = open(f, encoding="utf-8") |
| 1002 |
except OSError: |
| 1003 |
# /etc/resolv.conf doesn't exist, can't be read, etc. |
| 1004 |
raise NoResolverConfiguration(f"cannot open {f}") |
| 1005 |
else: |
| 1006 |
cm = contextlib.nullcontext(f) |
| 1007 |
with cm as f: |
| 1008 |
for l in f: |
| 1009 |
if len(l) == 0 or l[0] == "#" or l[0] == ";": |
| 1010 |
continue |
| 1011 |
tokens = l.split() |
| 1012 |
|
| 1013 |
# Any line containing less than 2 tokens is malformed |
| 1014 |
if len(tokens) < 2: |
| 1015 |
continue |
| 1016 |
|
| 1017 |
if tokens[0] == "nameserver": |
| 1018 |
nameservers.append(tokens[1]) |
| 1019 |
elif tokens[0] == "domain": |
| 1020 |
self.domain = dns.name.from_text(tokens[1]) |
| 1021 |
# domain and search are exclusive |
| 1022 |
self.search = [] |
| 1023 |
elif tokens[0] == "search": |
| 1024 |
# the last search wins |
| 1025 |
self.search = [] |
| 1026 |
for suffix in tokens[1:]: |
| 1027 |
self.search.append(dns.name.from_text(suffix)) |
| 1028 |
# We don't set domain as it is not used if |
| 1029 |
# len(self.search) > 0 |
| 1030 |
elif tokens[0] == "options": |
| 1031 |
for opt in tokens[1:]: |
| 1032 |
if opt == "rotate": |
| 1033 |
self.rotate = True |
| 1034 |
elif opt == "edns0": |
| 1035 |
self.use_edns() |
| 1036 |
elif "timeout" in opt: |
| 1037 |
try: |
| 1038 |
self.timeout = int(opt.split(":")[1]) |
| 1039 |
except (ValueError, IndexError): |
| 1040 |
pass |
| 1041 |
elif "ndots" in opt: |
| 1042 |
try: |
| 1043 |
self.ndots = int(opt.split(":")[1]) |
| 1044 |
except (ValueError, IndexError): |
| 1045 |
pass |
| 1046 |
if len(nameservers) == 0: |
| 1047 |
raise NoResolverConfiguration("no nameservers") |
| 1048 |
# Assigning directly instead of appending means we invoke the |
| 1049 |
# setter logic, with additonal checking and enrichment. |
| 1050 |
self.nameservers = nameservers |
| 1051 |
|
| 1052 |
def read_registry(self) -> None: # pragma: no cover |
| 1053 |
"""Extract resolver configuration from the Windows registry.""" |
| 1054 |
try: |
| 1055 |
info = dns.win32util.get_dns_info() # type: ignore |
| 1056 |
if info.domain is not None: |
| 1057 |
self.domain = info.domain |
| 1058 |
self.nameservers = info.nameservers |
| 1059 |
self.search = info.search |
| 1060 |
except AttributeError: |
| 1061 |
raise NotImplementedError |
| 1062 |
|
| 1063 |
def _compute_timeout( |
| 1064 |
self, |
| 1065 |
start: float, |
| 1066 |
lifetime: float | None = None, |
| 1067 |
errors: List[ErrorTuple] | None = None, |
| 1068 |
) -> float: |
| 1069 |
lifetime = self.lifetime if lifetime is None else lifetime |
| 1070 |
now = time.time() |
| 1071 |
duration = now - start |
| 1072 |
if errors is None: |
| 1073 |
errors = [] |
| 1074 |
if duration < 0: |
| 1075 |
if duration < -1: |
| 1076 |
# Time going backwards is bad. Just give up. |
| 1077 |
raise LifetimeTimeout(timeout=duration, errors=errors) |
| 1078 |
else: |
| 1079 |
# Time went backwards, but only a little. This can |
| 1080 |
# happen, e.g. under vmware with older linux kernels. |
| 1081 |
# Pretend it didn't happen. |
| 1082 |
duration = 0 |
| 1083 |
if duration >= lifetime: |
| 1084 |
raise LifetimeTimeout(timeout=duration, errors=errors) |
| 1085 |
return min(lifetime - duration, self.timeout) |
| 1086 |
|
| 1087 |
def _get_qnames_to_try( |
| 1088 |
self, qname: dns.name.Name, search: bool | None |
| 1089 |
) -> List[dns.name.Name]: |
| 1090 |
# This is a separate method so we can unit test the search |
| 1091 |
# rules without requiring the Internet. |
| 1092 |
if search is None: |
| 1093 |
search = self.use_search_by_default |
| 1094 |
qnames_to_try = [] |
| 1095 |
if qname.is_absolute(): |
| 1096 |
qnames_to_try.append(qname) |
| 1097 |
else: |
| 1098 |
abs_qname = qname.concatenate(dns.name.root) |
| 1099 |
if search: |
| 1100 |
if len(self.search) > 0: |
| 1101 |
# There is a search list, so use it exclusively |
| 1102 |
search_list = self.search[:] |
| 1103 |
elif self.domain != dns.name.root and self.domain is not None: |
| 1104 |
# We have some notion of a domain that isn't the root, so |
| 1105 |
# use it as the search list. |
| 1106 |
search_list = [self.domain] |
| 1107 |
else: |
| 1108 |
search_list = [] |
| 1109 |
# Figure out the effective ndots (default is 1) |
| 1110 |
if self.ndots is None: |
| 1111 |
ndots = 1 |
| 1112 |
else: |
| 1113 |
ndots = self.ndots |
| 1114 |
for suffix in search_list: |
| 1115 |
qnames_to_try.append(qname + suffix) |
| 1116 |
if len(qname) > ndots: |
| 1117 |
# The name has at least ndots dots, so we should try an |
| 1118 |
# absolute query first. |
| 1119 |
qnames_to_try.insert(0, abs_qname) |
| 1120 |
else: |
| 1121 |
# The name has less than ndots dots, so we should search |
| 1122 |
# first, then try the absolute name. |
| 1123 |
qnames_to_try.append(abs_qname) |
| 1124 |
else: |
| 1125 |
qnames_to_try.append(abs_qname) |
| 1126 |
return qnames_to_try |
| 1127 |
|
| 1128 |
def use_tsig( |
| 1129 |
self, |
| 1130 |
keyring: Any, |
| 1131 |
keyname: dns.name.Name | str | None = None, |
| 1132 |
algorithm: dns.name.Name | str = dns.tsig.default_algorithm, |
| 1133 |
) -> None: |
| 1134 |
"""Add a TSIG signature to each query. |
| 1135 |
|
| 1136 |
The parameters are passed to ``dns.message.Message.use_tsig()``; |
| 1137 |
see its documentation for details. |
| 1138 |
""" |
| 1139 |
|
| 1140 |
self.keyring = keyring |
| 1141 |
self.keyname = keyname |
| 1142 |
self.keyalgorithm = algorithm |
| 1143 |
|
| 1144 |
def use_edns( |
| 1145 |
self, |
| 1146 |
edns: int | bool | None = 0, |
| 1147 |
ednsflags: int = 0, |
| 1148 |
payload: int = dns.message.DEFAULT_EDNS_PAYLOAD, |
| 1149 |
options: List[dns.edns.Option] | None = None, |
| 1150 |
) -> None: |
| 1151 |
"""Configure EDNS behavior. |
| 1152 |
|
| 1153 |
*edns*, an ``int``, is the EDNS level to use. Specifying |
| 1154 |
``None``, ``False``, or ``-1`` means "do not use EDNS", and in this case |
| 1155 |
the other parameters are ignored. Specifying ``True`` is |
| 1156 |
equivalent to specifying 0, i.e. "use EDNS0". |
| 1157 |
|
| 1158 |
*ednsflags*, an ``int``, the EDNS flag values. |
| 1159 |
|
| 1160 |
*payload*, an ``int``, is the EDNS sender's payload field, which is the |
| 1161 |
maximum size of UDP datagram the sender can handle. I.e. how big |
| 1162 |
a response to this message can be. |
| 1163 |
|
| 1164 |
*options*, a list of ``dns.edns.Option`` objects or ``None``, the EDNS |
| 1165 |
options. |
| 1166 |
""" |
| 1167 |
|
| 1168 |
if edns is None or edns is False: |
| 1169 |
edns = -1 |
| 1170 |
elif edns is True: |
| 1171 |
edns = 0 |
| 1172 |
self.edns = edns |
| 1173 |
self.ednsflags = ednsflags |
| 1174 |
self.payload = payload |
| 1175 |
self.ednsoptions = options |
| 1176 |
|
| 1177 |
def set_flags(self, flags: int) -> None: |
| 1178 |
"""Overrides the default flags with your own. |
| 1179 |
|
| 1180 |
*flags*, an ``int``, the message flags to use. |
| 1181 |
""" |
| 1182 |
|
| 1183 |
self.flags = flags |
| 1184 |
|
| 1185 |
@classmethod |
| 1186 |
def _enrich_nameservers( |
| 1187 |
cls, |
| 1188 |
nameservers: Sequence[str | dns.nameserver.Nameserver], |
| 1189 |
nameserver_ports: Dict[str, int], |
| 1190 |
default_port: int, |
| 1191 |
) -> List[dns.nameserver.Nameserver]: |
| 1192 |
enriched_nameservers = [] |
| 1193 |
if isinstance(nameservers, list | tuple): |
| 1194 |
for nameserver in nameservers: |
| 1195 |
enriched_nameserver: dns.nameserver.Nameserver |
| 1196 |
if isinstance(nameserver, dns.nameserver.Nameserver): |
| 1197 |
enriched_nameserver = nameserver |
| 1198 |
elif dns.inet.is_address(nameserver): |
| 1199 |
port = nameserver_ports.get(nameserver, default_port) |
| 1200 |
enriched_nameserver = dns.nameserver.Do53Nameserver( |
| 1201 |
nameserver, port |
| 1202 |
) |
| 1203 |
else: |
| 1204 |
try: |
| 1205 |
if urlparse(nameserver).scheme != "https": |
| 1206 |
raise NotImplementedError |
| 1207 |
except Exception: |
| 1208 |
raise ValueError( |
| 1209 |
f"nameserver {nameserver} is not a " |
| 1210 |
"dns.nameserver.Nameserver instance or text form, " |
| 1211 |
"IP address, nor a valid https URL" |
| 1212 |
) |
| 1213 |
enriched_nameserver = dns.nameserver.DoHNameserver(nameserver) |
| 1214 |
enriched_nameservers.append(enriched_nameserver) |
| 1215 |
else: |
| 1216 |
raise ValueError( |
| 1217 |
f"nameservers must be a list or tuple (not a {type(nameservers)})" |
| 1218 |
) |
| 1219 |
return enriched_nameservers |
| 1220 |
|
| 1221 |
@property |
| 1222 |
def nameservers( |
| 1223 |
self, |
| 1224 |
) -> Sequence[str | dns.nameserver.Nameserver]: |
| 1225 |
return self._nameservers |
| 1226 |
|
| 1227 |
@nameservers.setter |
| 1228 |
def nameservers( |
| 1229 |
self, nameservers: Sequence[str | dns.nameserver.Nameserver] |
| 1230 |
) -> None: |
| 1231 |
""" |
| 1232 |
*nameservers*, a ``list`` or ``tuple`` of nameservers, where a nameserver is either |
| 1233 |
a string interpretable as a nameserver, or a ``dns.nameserver.Nameserver`` |
| 1234 |
instance. |
| 1235 |
|
| 1236 |
Raises ``ValueError`` if *nameservers* is not a list of nameservers. |
| 1237 |
""" |
| 1238 |
# We just call _enrich_nameservers() for checking |
| 1239 |
self._enrich_nameservers(nameservers, self.nameserver_ports, self.port) |
| 1240 |
self._nameservers = nameservers |
| 1241 |
|
| 1242 |
|
| 1243 |
class Resolver(BaseResolver): |
| 1244 |
"""DNS stub resolver.""" |
| 1245 |
|
| 1246 |
def resolve( |
| 1247 |
self, |
| 1248 |
qname: dns.name.Name | str, |
| 1249 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 1250 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 1251 |
tcp: bool = False, |
| 1252 |
source: str | None = None, |
| 1253 |
raise_on_no_answer: bool = True, |
| 1254 |
source_port: int = 0, |
| 1255 |
lifetime: float | None = None, |
| 1256 |
search: bool | None = None, |
| 1257 |
) -> Answer: # pylint: disable=arguments-differ |
| 1258 |
"""Query nameservers to find the answer to the question. |
| 1259 |
|
| 1260 |
The *qname*, *rdtype*, and *rdclass* parameters may be objects |
| 1261 |
of the appropriate type, or strings that can be converted into objects |
| 1262 |
of the appropriate type. |
| 1263 |
|
| 1264 |
*qname*, a ``dns.name.Name`` or ``str``, the query name. |
| 1265 |
|
| 1266 |
*rdtype*, an ``int`` or ``str``, the query type. |
| 1267 |
|
| 1268 |
*rdclass*, an ``int`` or ``str``, the query class. |
| 1269 |
|
| 1270 |
*tcp*, a ``bool``. If ``True``, use TCP to make the query. |
| 1271 |
|
| 1272 |
*source*, a ``str`` or ``None``. If not ``None``, bind to this IP |
| 1273 |
address when making queries. |
| 1274 |
|
| 1275 |
*raise_on_no_answer*, a ``bool``. If ``True``, raise |
| 1276 |
``dns.resolver.NoAnswer`` if there's no answer to the question. |
| 1277 |
|
| 1278 |
*source_port*, an ``int``, the port from which to send the message. |
| 1279 |
|
| 1280 |
*lifetime*, a ``float``, how many seconds a query should run |
| 1281 |
before timing out. |
| 1282 |
|
| 1283 |
*search*, a ``bool`` or ``None``, determines whether the |
| 1284 |
search list configured in the system's resolver configuration |
| 1285 |
are used for relative names, and whether the resolver's domain |
| 1286 |
may be added to relative names. The default is ``None``, |
| 1287 |
which causes the value of the resolver's |
| 1288 |
``use_search_by_default`` attribute to be used. |
| 1289 |
|
| 1290 |
Raises ``dns.resolver.LifetimeTimeout`` if no answers could be found |
| 1291 |
in the specified lifetime. |
| 1292 |
|
| 1293 |
Raises ``dns.resolver.NXDOMAIN`` if the query name does not exist. |
| 1294 |
|
| 1295 |
Raises ``dns.resolver.YXDOMAIN`` if the query name is too long after |
| 1296 |
DNAME substitution. |
| 1297 |
|
| 1298 |
Raises ``dns.resolver.NoAnswer`` if *raise_on_no_answer* is |
| 1299 |
``True`` and the query name exists but has no RRset of the |
| 1300 |
desired type and class. |
| 1301 |
|
| 1302 |
Raises ``dns.resolver.NoNameservers`` if no non-broken |
| 1303 |
nameservers are available to answer the question. |
| 1304 |
|
| 1305 |
Returns a ``dns.resolver.Answer`` instance. |
| 1306 |
|
| 1307 |
""" |
| 1308 |
|
| 1309 |
resolution = _Resolution( |
| 1310 |
self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search |
| 1311 |
) |
| 1312 |
start = time.time() |
| 1313 |
while True: |
| 1314 |
(request, answer) = resolution.next_request() |
| 1315 |
# Note we need to say "if answer is not None" and not just |
| 1316 |
# "if answer" because answer implements __len__, and python |
| 1317 |
# will call that. We want to return if we have an answer |
| 1318 |
# object, including in cases where its length is 0. |
| 1319 |
if answer is not None: |
| 1320 |
# cache hit! |
| 1321 |
return answer |
| 1322 |
assert request is not None # needed for type checking |
| 1323 |
done = False |
| 1324 |
while not done: |
| 1325 |
(nameserver, tcp, backoff) = resolution.next_nameserver() |
| 1326 |
if backoff: |
| 1327 |
time.sleep(backoff) |
| 1328 |
timeout = self._compute_timeout(start, lifetime, resolution.errors) |
| 1329 |
try: |
| 1330 |
response = nameserver.query( |
| 1331 |
request, |
| 1332 |
timeout=timeout, |
| 1333 |
source=source, |
| 1334 |
source_port=source_port, |
| 1335 |
max_size=tcp, |
| 1336 |
) |
| 1337 |
except Exception as ex: |
| 1338 |
(_, done) = resolution.query_result(None, ex) |
| 1339 |
continue |
| 1340 |
(answer, done) = resolution.query_result(response, None) |
| 1341 |
# Note we need to say "if answer is not None" and not just |
| 1342 |
# "if answer" because answer implements __len__, and python |
| 1343 |
# will call that. We want to return if we have an answer |
| 1344 |
# object, including in cases where its length is 0. |
| 1345 |
if answer is not None: |
| 1346 |
return answer |
| 1347 |
|
| 1348 |
def query( |
| 1349 |
self, |
| 1350 |
qname: dns.name.Name | str, |
| 1351 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 1352 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 1353 |
tcp: bool = False, |
| 1354 |
source: str | None = None, |
| 1355 |
raise_on_no_answer: bool = True, |
| 1356 |
source_port: int = 0, |
| 1357 |
lifetime: float | None = None, |
| 1358 |
) -> Answer: # pragma: no cover |
| 1359 |
"""Query nameservers to find the answer to the question. |
| 1360 |
|
| 1361 |
This method calls resolve() with ``search=True``, and is |
| 1362 |
provided for backwards compatibility with prior versions of |
| 1363 |
dnspython. See the documentation for the resolve() method for |
| 1364 |
further details. |
| 1365 |
""" |
| 1366 |
warnings.warn( |
| 1367 |
"please use dns.resolver.Resolver.resolve() instead", |
| 1368 |
DeprecationWarning, |
| 1369 |
stacklevel=2, |
| 1370 |
) |
| 1371 |
return self.resolve( |
| 1372 |
qname, |
| 1373 |
rdtype, |
| 1374 |
rdclass, |
| 1375 |
tcp, |
| 1376 |
source, |
| 1377 |
raise_on_no_answer, |
| 1378 |
source_port, |
| 1379 |
lifetime, |
| 1380 |
True, |
| 1381 |
) |
| 1382 |
|
| 1383 |
def resolve_address(self, ipaddr: str, *args: Any, **kwargs: Any) -> Answer: |
| 1384 |
"""Use a resolver to run a reverse query for PTR records. |
| 1385 |
|
| 1386 |
This utilizes the resolve() method to perform a PTR lookup on the |
| 1387 |
specified IP address. |
| 1388 |
|
| 1389 |
*ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get |
| 1390 |
the PTR record for. |
| 1391 |
|
| 1392 |
All other arguments that can be passed to the resolve() function |
| 1393 |
except for rdtype and rdclass are also supported by this |
| 1394 |
function. |
| 1395 |
""" |
| 1396 |
# We make a modified kwargs for type checking happiness, as otherwise |
| 1397 |
# we get a legit warning about possibly having rdtype and rdclass |
| 1398 |
# in the kwargs more than once. |
| 1399 |
modified_kwargs: Dict[str, Any] = {} |
| 1400 |
modified_kwargs.update(kwargs) |
| 1401 |
modified_kwargs["rdtype"] = dns.rdatatype.PTR |
| 1402 |
modified_kwargs["rdclass"] = dns.rdataclass.IN |
| 1403 |
return self.resolve( |
| 1404 |
dns.reversename.from_address(ipaddr), *args, **modified_kwargs |
| 1405 |
) |
| 1406 |
|
| 1407 |
def resolve_name( |
| 1408 |
self, |
| 1409 |
name: dns.name.Name | str, |
| 1410 |
family: int = socket.AF_UNSPEC, |
| 1411 |
**kwargs: Any, |
| 1412 |
) -> HostAnswers: |
| 1413 |
"""Use a resolver to query for address records. |
| 1414 |
|
| 1415 |
This utilizes the resolve() method to perform A and/or AAAA lookups on |
| 1416 |
the specified name. |
| 1417 |
|
| 1418 |
*qname*, a ``dns.name.Name`` or ``str``, the name to resolve. |
| 1419 |
|
| 1420 |
*family*, an ``int``, the address family. If socket.AF_UNSPEC |
| 1421 |
(the default), both A and AAAA records will be retrieved. |
| 1422 |
|
| 1423 |
All other arguments that can be passed to the resolve() function |
| 1424 |
except for rdtype and rdclass are also supported by this |
| 1425 |
function. |
| 1426 |
""" |
| 1427 |
# We make a modified kwargs for type checking happiness, as otherwise |
| 1428 |
# we get a legit warning about possibly having rdtype and rdclass |
| 1429 |
# in the kwargs more than once. |
| 1430 |
modified_kwargs: Dict[str, Any] = {} |
| 1431 |
modified_kwargs.update(kwargs) |
| 1432 |
modified_kwargs.pop("rdtype", None) |
| 1433 |
modified_kwargs["rdclass"] = dns.rdataclass.IN |
| 1434 |
|
| 1435 |
if family == socket.AF_INET: |
| 1436 |
v4 = self.resolve(name, dns.rdatatype.A, **modified_kwargs) |
| 1437 |
return HostAnswers.make(v4=v4) |
| 1438 |
elif family == socket.AF_INET6: |
| 1439 |
v6 = self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) |
| 1440 |
return HostAnswers.make(v6=v6) |
| 1441 |
elif family != socket.AF_UNSPEC: # pragma: no cover |
| 1442 |
raise NotImplementedError(f"unknown address family {family}") |
| 1443 |
|
| 1444 |
raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) |
| 1445 |
lifetime = modified_kwargs.pop("lifetime", None) |
| 1446 |
start = time.time() |
| 1447 |
v6 = self.resolve( |
| 1448 |
name, |
| 1449 |
dns.rdatatype.AAAA, |
| 1450 |
raise_on_no_answer=False, |
| 1451 |
lifetime=self._compute_timeout(start, lifetime), |
| 1452 |
**modified_kwargs, |
| 1453 |
) |
| 1454 |
# Note that setting name ensures we query the same name |
| 1455 |
# for A as we did for AAAA. (This is just in case search lists |
| 1456 |
# are active by default in the resolver configuration and |
| 1457 |
# we might be talking to a server that says NXDOMAIN when it |
| 1458 |
# wants to say NOERROR no data. |
| 1459 |
name = v6.qname |
| 1460 |
v4 = self.resolve( |
| 1461 |
name, |
| 1462 |
dns.rdatatype.A, |
| 1463 |
raise_on_no_answer=False, |
| 1464 |
lifetime=self._compute_timeout(start, lifetime), |
| 1465 |
**modified_kwargs, |
| 1466 |
) |
| 1467 |
answers = HostAnswers.make(v6=v6, v4=v4, add_empty=not raise_on_no_answer) |
| 1468 |
if not answers: |
| 1469 |
raise NoAnswer(response=v6.response) |
| 1470 |
return answers |
| 1471 |
|
| 1472 |
# pylint: disable=redefined-outer-name |
| 1473 |
|
| 1474 |
def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: |
| 1475 |
"""Determine the canonical name of *name*. |
| 1476 |
|
| 1477 |
The canonical name is the name the resolver uses for queries |
| 1478 |
after all CNAME and DNAME renamings have been applied. |
| 1479 |
|
| 1480 |
*name*, a ``dns.name.Name`` or ``str``, the query name. |
| 1481 |
|
| 1482 |
This method can raise any exception that ``resolve()`` can |
| 1483 |
raise, other than ``dns.resolver.NoAnswer`` and |
| 1484 |
``dns.resolver.NXDOMAIN``. |
| 1485 |
|
| 1486 |
Returns a ``dns.name.Name``. |
| 1487 |
""" |
| 1488 |
try: |
| 1489 |
answer = self.resolve(name, raise_on_no_answer=False) |
| 1490 |
canonical_name = answer.canonical_name |
| 1491 |
except NXDOMAIN as e: |
| 1492 |
canonical_name = e.canonical_name |
| 1493 |
return canonical_name |
| 1494 |
|
| 1495 |
# pylint: enable=redefined-outer-name |
| 1496 |
|
| 1497 |
def try_ddr(self, lifetime: float = 5.0) -> None: |
| 1498 |
"""Try to update the resolver's nameservers using Discovery of Designated |
| 1499 |
Resolvers (DDR). If successful, the resolver will subsequently use |
| 1500 |
DNS-over-HTTPS or DNS-over-TLS for future queries. |
| 1501 |
|
| 1502 |
*lifetime*, a float, is the maximum time to spend attempting DDR. The default |
| 1503 |
is 5 seconds. |
| 1504 |
|
| 1505 |
If the SVCB query is successful and results in a non-empty list of nameservers, |
| 1506 |
then the resolver's nameservers are set to the returned servers in priority |
| 1507 |
order. |
| 1508 |
|
| 1509 |
The current implementation does not use any address hints from the SVCB record, |
| 1510 |
nor does it resolve addresses for the SCVB target name, rather it assumes that |
| 1511 |
the bootstrap nameserver will always be one of the addresses and uses it. |
| 1512 |
A future revision to the code may offer fuller support. The code verifies that |
| 1513 |
the bootstrap nameserver is in the Subject Alternative Name field of the |
| 1514 |
TLS certficate. |
| 1515 |
""" |
| 1516 |
try: |
| 1517 |
expiration = time.time() + lifetime |
| 1518 |
answer = self.resolve( |
| 1519 |
dns._ddr._local_resolver_name, "SVCB", lifetime=lifetime |
| 1520 |
) |
| 1521 |
timeout = dns.query._remaining(expiration) |
| 1522 |
nameservers = dns._ddr._get_nameservers_sync(answer, timeout) |
| 1523 |
if len(nameservers) > 0: |
| 1524 |
self.nameservers = nameservers |
| 1525 |
except Exception: # pragma: no cover |
| 1526 |
pass |
| 1527 |
|
| 1528 |
|
| 1529 |
#: The default resolver. |
| 1530 |
default_resolver: Resolver | None = None |
| 1531 |
|
| 1532 |
|
| 1533 |
def get_default_resolver() -> Resolver: |
| 1534 |
"""Get the default resolver, initializing it if necessary.""" |
| 1535 |
if default_resolver is None: |
| 1536 |
reset_default_resolver() |
| 1537 |
assert default_resolver is not None |
| 1538 |
return default_resolver |
| 1539 |
|
| 1540 |
|
| 1541 |
def reset_default_resolver() -> None: |
| 1542 |
"""Re-initialize default resolver. |
| 1543 |
|
| 1544 |
Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX |
| 1545 |
systems) will be re-read immediately. |
| 1546 |
""" |
| 1547 |
|
| 1548 |
global default_resolver |
| 1549 |
default_resolver = Resolver() |
| 1550 |
|
| 1551 |
|
| 1552 |
def resolve( |
| 1553 |
qname: dns.name.Name | str, |
| 1554 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 1555 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 1556 |
tcp: bool = False, |
| 1557 |
source: str | None = None, |
| 1558 |
raise_on_no_answer: bool = True, |
| 1559 |
source_port: int = 0, |
| 1560 |
lifetime: float | None = None, |
| 1561 |
search: bool | None = None, |
| 1562 |
) -> Answer: # pragma: no cover |
| 1563 |
"""Query nameservers to find the answer to the question. |
| 1564 |
|
| 1565 |
This is a convenience function that uses the default resolver |
| 1566 |
object to make the query. |
| 1567 |
|
| 1568 |
See ``dns.resolver.Resolver.resolve`` for more information on the |
| 1569 |
parameters. |
| 1570 |
""" |
| 1571 |
|
| 1572 |
return get_default_resolver().resolve( |
| 1573 |
qname, |
| 1574 |
rdtype, |
| 1575 |
rdclass, |
| 1576 |
tcp, |
| 1577 |
source, |
| 1578 |
raise_on_no_answer, |
| 1579 |
source_port, |
| 1580 |
lifetime, |
| 1581 |
search, |
| 1582 |
) |
| 1583 |
|
| 1584 |
|
| 1585 |
def query( |
| 1586 |
qname: dns.name.Name | str, |
| 1587 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 1588 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 1589 |
tcp: bool = False, |
| 1590 |
source: str | None = None, |
| 1591 |
raise_on_no_answer: bool = True, |
| 1592 |
source_port: int = 0, |
| 1593 |
lifetime: float | None = None, |
| 1594 |
) -> Answer: # pragma: no cover |
| 1595 |
"""Query nameservers to find the answer to the question. |
| 1596 |
|
| 1597 |
This method calls resolve() with ``search=True``, and is |
| 1598 |
provided for backwards compatibility with prior versions of |
| 1599 |
dnspython. See the documentation for the resolve() method for |
| 1600 |
further details. |
| 1601 |
""" |
| 1602 |
warnings.warn( |
| 1603 |
"please use dns.resolver.resolve() instead", DeprecationWarning, stacklevel=2 |
| 1604 |
) |
| 1605 |
return resolve( |
| 1606 |
qname, |
| 1607 |
rdtype, |
| 1608 |
rdclass, |
| 1609 |
tcp, |
| 1610 |
source, |
| 1611 |
raise_on_no_answer, |
| 1612 |
source_port, |
| 1613 |
lifetime, |
| 1614 |
True, |
| 1615 |
) |
| 1616 |
|
| 1617 |
|
| 1618 |
def resolve_address(ipaddr: str, *args: Any, **kwargs: Any) -> Answer: |
| 1619 |
"""Use a resolver to run a reverse query for PTR records. |
| 1620 |
|
| 1621 |
See ``dns.resolver.Resolver.resolve_address`` for more information on the |
| 1622 |
parameters. |
| 1623 |
""" |
| 1624 |
|
| 1625 |
return get_default_resolver().resolve_address(ipaddr, *args, **kwargs) |
| 1626 |
|
| 1627 |
|
| 1628 |
def resolve_name( |
| 1629 |
name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any |
| 1630 |
) -> HostAnswers: |
| 1631 |
"""Use a resolver to query for address records. |
| 1632 |
|
| 1633 |
See ``dns.resolver.Resolver.resolve_name`` for more information on the |
| 1634 |
parameters. |
| 1635 |
""" |
| 1636 |
|
| 1637 |
return get_default_resolver().resolve_name(name, family, **kwargs) |
| 1638 |
|
| 1639 |
|
| 1640 |
def canonical_name(name: dns.name.Name | str) -> dns.name.Name: |
| 1641 |
"""Determine the canonical name of *name*. |
| 1642 |
|
| 1643 |
See ``dns.resolver.Resolver.canonical_name`` for more information on the |
| 1644 |
parameters and possible exceptions. |
| 1645 |
""" |
| 1646 |
|
| 1647 |
return get_default_resolver().canonical_name(name) |
| 1648 |
|
| 1649 |
|
| 1650 |
def try_ddr(lifetime: float = 5.0) -> None: # pragma: no cover |
| 1651 |
"""Try to update the default resolver's nameservers using Discovery of Designated |
| 1652 |
Resolvers (DDR). If successful, the resolver will subsequently use |
| 1653 |
DNS-over-HTTPS or DNS-over-TLS for future queries. |
| 1654 |
|
| 1655 |
See :py:func:`dns.resolver.Resolver.try_ddr` for more information. |
| 1656 |
""" |
| 1657 |
return get_default_resolver().try_ddr(lifetime) |
| 1658 |
|
| 1659 |
|
| 1660 |
def zone_for_name( |
| 1661 |
name: dns.name.Name | str, |
| 1662 |
rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, |
| 1663 |
tcp: bool = False, |
| 1664 |
resolver: Resolver | None = None, |
| 1665 |
lifetime: float | None = None, |
| 1666 |
) -> dns.name.Name: # pyright: ignore[reportReturnType] |
| 1667 |
"""Find the name of the zone which contains the specified name. |
| 1668 |
|
| 1669 |
*name*, an absolute ``dns.name.Name`` or ``str``, the query name. |
| 1670 |
|
| 1671 |
*rdclass*, an ``int``, the query class. |
| 1672 |
|
| 1673 |
*tcp*, a ``bool``. If ``True``, use TCP to make the query. |
| 1674 |
|
| 1675 |
*resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. |
| 1676 |
If ``None``, the default, then the default resolver is used. |
| 1677 |
|
| 1678 |
*lifetime*, a ``float``, the total time to allow for the queries needed |
| 1679 |
to determine the zone. If ``None``, the default, then only the individual |
| 1680 |
query limits of the resolver apply. |
| 1681 |
|
| 1682 |
Raises ``dns.resolver.NoRootSOA`` if there is no SOA RR at the DNS |
| 1683 |
root. (This is only likely to happen if you're using non-default |
| 1684 |
root servers in your network and they are misconfigured.) |
| 1685 |
|
| 1686 |
Raises ``dns.resolver.LifetimeTimeout`` if the answer could not be |
| 1687 |
found in the allotted lifetime. |
| 1688 |
|
| 1689 |
Returns a ``dns.name.Name``. |
| 1690 |
""" |
| 1691 |
|
| 1692 |
if isinstance(name, str): |
| 1693 |
name = dns.name.from_text(name, dns.name.root) |
| 1694 |
if resolver is None: |
| 1695 |
resolver = get_default_resolver() |
| 1696 |
if not name.is_absolute(): |
| 1697 |
raise NotAbsolute(name) |
| 1698 |
start = time.time() |
| 1699 |
expiration: float | None |
| 1700 |
if lifetime is not None: |
| 1701 |
expiration = start + lifetime |
| 1702 |
else: |
| 1703 |
expiration = None |
| 1704 |
while 1: |
| 1705 |
try: |
| 1706 |
rlifetime: float | None |
| 1707 |
if expiration is not None: |
| 1708 |
rlifetime = expiration - time.time() |
| 1709 |
if rlifetime <= 0: |
| 1710 |
rlifetime = 0 |
| 1711 |
else: |
| 1712 |
rlifetime = None |
| 1713 |
answer = resolver.resolve( |
| 1714 |
name, dns.rdatatype.SOA, rdclass, tcp, lifetime=rlifetime |
| 1715 |
) |
| 1716 |
assert answer.rrset is not None |
| 1717 |
if answer.rrset.name == name: |
| 1718 |
return name |
| 1719 |
# otherwise we were CNAMEd or DNAMEd and need to look higher |
| 1720 |
except (NXDOMAIN, NoAnswer) as e: |
| 1721 |
if isinstance(e, NXDOMAIN): |
| 1722 |
response = e.responses().get(name) |
| 1723 |
else: |
| 1724 |
response = e.response() # pylint: disable=no-value-for-parameter |
| 1725 |
if response: |
| 1726 |
for rrs in response.authority: |
| 1727 |
if rrs.rdtype == dns.rdatatype.SOA and rrs.rdclass == rdclass: |
| 1728 |
(nr, _, _) = rrs.name.fullcompare(name) |
| 1729 |
if nr == dns.name.NAMERELN_SUPERDOMAIN: |
| 1730 |
# We're doing a proper superdomain check as |
| 1731 |
# if the name were equal we ought to have gotten |
| 1732 |
# it in the answer section! We are ignoring the |
| 1733 |
# possibility that the authority is insane and |
| 1734 |
# is including multiple SOA RRs for different |
| 1735 |
# authorities. |
| 1736 |
return rrs.name |
| 1737 |
# we couldn't extract anything useful from the response (e.g. it's |
| 1738 |
# a type 3 NXDOMAIN) |
| 1739 |
try: |
| 1740 |
name = name.parent() |
| 1741 |
except dns.name.NoParent: |
| 1742 |
raise NoRootSOA |
| 1743 |
|
| 1744 |
|
| 1745 |
def make_resolver_at( |
| 1746 |
where: dns.name.Name | str, |
| 1747 |
port: int = 53, |
| 1748 |
family: int = socket.AF_UNSPEC, |
| 1749 |
resolver: Resolver | None = None, |
| 1750 |
) -> Resolver: |
| 1751 |
"""Make a stub resolver using the specified destination as the full resolver. |
| 1752 |
|
| 1753 |
*where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the |
| 1754 |
full resolver. |
| 1755 |
|
| 1756 |
*port*, an ``int``, the port to use. If not specified, the default is 53. |
| 1757 |
|
| 1758 |
*family*, an ``int``, the address family to use. This parameter is used if |
| 1759 |
*where* is not an address. The default is ``socket.AF_UNSPEC`` in which case |
| 1760 |
the first address returned by ``resolve_name()`` will be used, otherwise the |
| 1761 |
first address of the specified family will be used. |
| 1762 |
|
| 1763 |
*resolver*, a ``dns.resolver.Resolver`` or ``None``, the resolver to use for |
| 1764 |
resolution of hostnames. If not specified, the default resolver will be used. |
| 1765 |
|
| 1766 |
Returns a ``dns.resolver.Resolver`` or raises an exception. |
| 1767 |
""" |
| 1768 |
if resolver is None: |
| 1769 |
resolver = get_default_resolver() |
| 1770 |
nameservers: List[str | dns.nameserver.Nameserver] = [] |
| 1771 |
if isinstance(where, str) and dns.inet.is_address(where): |
| 1772 |
nameservers.append(dns.nameserver.Do53Nameserver(where, port)) |
| 1773 |
else: |
| 1774 |
for address in resolver.resolve_name(where, family).addresses(): |
| 1775 |
nameservers.append(dns.nameserver.Do53Nameserver(address, port)) |
| 1776 |
res = Resolver(configure=False) |
| 1777 |
res.nameservers = nameservers |
| 1778 |
return res |
| 1779 |
|
| 1780 |
|
| 1781 |
def resolve_at( |
| 1782 |
where: dns.name.Name | str, |
| 1783 |
qname: dns.name.Name | str, |
| 1784 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 1785 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 1786 |
tcp: bool = False, |
| 1787 |
source: str | None = None, |
| 1788 |
raise_on_no_answer: bool = True, |
| 1789 |
source_port: int = 0, |
| 1790 |
lifetime: float | None = None, |
| 1791 |
search: bool | None = None, |
| 1792 |
port: int = 53, |
| 1793 |
family: int = socket.AF_UNSPEC, |
| 1794 |
resolver: Resolver | None = None, |
| 1795 |
) -> Answer: |
| 1796 |
"""Query nameservers to find the answer to the question. |
| 1797 |
|
| 1798 |
This is a convenience function that calls ``dns.resolver.make_resolver_at()`` to |
| 1799 |
make a resolver, and then uses it to resolve the query. |
| 1800 |
|
| 1801 |
See ``dns.resolver.Resolver.resolve`` for more information on the resolution |
| 1802 |
parameters, and ``dns.resolver.make_resolver_at`` for information about the resolver |
| 1803 |
parameters *where*, *port*, *family*, and *resolver*. |
| 1804 |
|
| 1805 |
If making more than one query, it is more efficient to call |
| 1806 |
``dns.resolver.make_resolver_at()`` and then use that resolver for the queries |
| 1807 |
instead of calling ``resolve_at()`` multiple times. |
| 1808 |
""" |
| 1809 |
return make_resolver_at(where, port, family, resolver).resolve( |
| 1810 |
qname, |
| 1811 |
rdtype, |
| 1812 |
rdclass, |
| 1813 |
tcp, |
| 1814 |
source, |
| 1815 |
raise_on_no_answer, |
| 1816 |
source_port, |
| 1817 |
lifetime, |
| 1818 |
search, |
| 1819 |
) |
| 1820 |
|
| 1821 |
|
| 1822 |
# |
| 1823 |
# Support for overriding the system resolver for all python code in the |
| 1824 |
# running process. |
| 1825 |
# |
| 1826 |
|
| 1827 |
_protocols_for_socktype: Dict[Any, List[Any]] = { |
| 1828 |
socket.SOCK_DGRAM: [socket.SOL_UDP], |
| 1829 |
socket.SOCK_STREAM: [socket.SOL_TCP], |
| 1830 |
} |
| 1831 |
|
| 1832 |
_resolver: Resolver | None = None |
| 1833 |
_original_getaddrinfo = socket.getaddrinfo |
| 1834 |
_original_getnameinfo = socket.getnameinfo |
| 1835 |
_original_getfqdn = socket.getfqdn |
| 1836 |
_original_gethostbyname = socket.gethostbyname |
| 1837 |
_original_gethostbyname_ex = socket.gethostbyname_ex |
| 1838 |
_original_gethostbyaddr = socket.gethostbyaddr |
| 1839 |
|
| 1840 |
|
| 1841 |
def _getaddrinfo( |
| 1842 |
host=None, service=None, family=socket.AF_UNSPEC, socktype=0, proto=0, flags=0 |
| 1843 |
): |
| 1844 |
if flags & socket.AI_NUMERICHOST != 0: |
| 1845 |
# Short circuit directly into the system's getaddrinfo(). We're |
| 1846 |
# not adding any value in this case, and this avoids infinite loops |
| 1847 |
# because dns.query.* needs to call getaddrinfo() for IPv6 scoping |
| 1848 |
# reasons. We will also do this short circuit below if we |
| 1849 |
# discover that the host is an address literal. |
| 1850 |
return _original_getaddrinfo(host, service, family, socktype, proto, flags) |
| 1851 |
if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0: |
| 1852 |
# Not implemented. We raise a gaierror as opposed to a |
| 1853 |
# NotImplementedError as it helps callers handle errors more |
| 1854 |
# appropriately. [Issue #316] |
| 1855 |
# |
| 1856 |
# We raise EAI_FAIL as opposed to EAI_SYSTEM because there is |
| 1857 |
# no EAI_SYSTEM on Windows [Issue #416]. We didn't go for |
| 1858 |
# EAI_BADFLAGS as the flags aren't bad, we just don't |
| 1859 |
# implement them. |
| 1860 |
raise socket.gaierror( |
| 1861 |
socket.EAI_FAIL, "Non-recoverable failure in name resolution" |
| 1862 |
) |
| 1863 |
if host is None and service is None: |
| 1864 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 1865 |
addrs = [] |
| 1866 |
canonical_name = None # pylint: disable=redefined-outer-name |
| 1867 |
# Is host None or an address literal? If so, use the system's |
| 1868 |
# getaddrinfo(). |
| 1869 |
if host is None: |
| 1870 |
return _original_getaddrinfo(host, service, family, socktype, proto, flags) |
| 1871 |
try: |
| 1872 |
# We don't care about the result of af_for_address(), we're just |
| 1873 |
# calling it so it raises an exception if host is not an IPv4 or |
| 1874 |
# IPv6 address. |
| 1875 |
dns.inet.af_for_address(host) |
| 1876 |
return _original_getaddrinfo(host, service, family, socktype, proto, flags) |
| 1877 |
except Exception: |
| 1878 |
pass |
| 1879 |
# Something needs resolution! |
| 1880 |
try: |
| 1881 |
assert _resolver is not None |
| 1882 |
answers = _resolver.resolve_name(host, family) |
| 1883 |
addrs = answers.addresses_and_families() |
| 1884 |
canonical_name = answers.canonical_name().to_text(True) |
| 1885 |
except NXDOMAIN: |
| 1886 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 1887 |
except Exception: |
| 1888 |
# We raise EAI_AGAIN here as the failure may be temporary |
| 1889 |
# (e.g. a timeout) and EAI_SYSTEM isn't defined on Windows. |
| 1890 |
# [Issue #416] |
| 1891 |
raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution") |
| 1892 |
port = None |
| 1893 |
try: |
| 1894 |
# Is it a port literal? |
| 1895 |
if service is None: |
| 1896 |
port = 0 |
| 1897 |
else: |
| 1898 |
port = int(service) |
| 1899 |
except Exception: |
| 1900 |
if flags & socket.AI_NUMERICSERV == 0: |
| 1901 |
try: |
| 1902 |
port = socket.getservbyname(service) # pyright: ignore |
| 1903 |
except Exception: |
| 1904 |
pass |
| 1905 |
if port is None: |
| 1906 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 1907 |
tuples = [] |
| 1908 |
if socktype == 0: |
| 1909 |
socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM] |
| 1910 |
else: |
| 1911 |
socktypes = [socktype] |
| 1912 |
if flags & socket.AI_CANONNAME != 0: |
| 1913 |
cname = canonical_name |
| 1914 |
else: |
| 1915 |
cname = "" |
| 1916 |
for addr, af in addrs: |
| 1917 |
for socktype in socktypes: |
| 1918 |
for sockproto in _protocols_for_socktype[socktype]: |
| 1919 |
proto = int(sockproto) |
| 1920 |
addr_tuple = dns.inet.low_level_address_tuple((addr, port), af) |
| 1921 |
tuples.append((af, socktype, proto, cname, addr_tuple)) |
| 1922 |
if len(tuples) == 0: |
| 1923 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 1924 |
return tuples |
| 1925 |
|
| 1926 |
|
| 1927 |
def _getnameinfo(sockaddr, flags=0): |
| 1928 |
host = sockaddr[0] |
| 1929 |
port = sockaddr[1] |
| 1930 |
if len(sockaddr) == 4: |
| 1931 |
scope = sockaddr[3] |
| 1932 |
family = socket.AF_INET6 |
| 1933 |
else: |
| 1934 |
scope = None |
| 1935 |
family = socket.AF_INET |
| 1936 |
tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) |
| 1937 |
if len(tuples) > 1: |
| 1938 |
raise OSError("sockaddr resolved to multiple addresses") |
| 1939 |
addr = tuples[0][4][0] |
| 1940 |
if flags & socket.NI_DGRAM: |
| 1941 |
pname = "udp" |
| 1942 |
else: |
| 1943 |
pname = "tcp" |
| 1944 |
assert isinstance(addr, str) |
| 1945 |
qname = dns.reversename.from_address(addr) |
| 1946 |
if flags & socket.NI_NUMERICHOST == 0: |
| 1947 |
try: |
| 1948 |
assert _resolver is not None |
| 1949 |
answer = _resolver.resolve(qname, "PTR") |
| 1950 |
assert answer.rrset is not None |
| 1951 |
rdata = cast(dns.rdtypes.ANY.PTR.PTR, answer.rrset[0]) |
| 1952 |
hostname = rdata.target.to_text(True) |
| 1953 |
except (NXDOMAIN, NoAnswer): |
| 1954 |
if flags & socket.NI_NAMEREQD: |
| 1955 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 1956 |
hostname = addr |
| 1957 |
if scope is not None: |
| 1958 |
hostname += "%" + str(scope) |
| 1959 |
else: |
| 1960 |
hostname = addr |
| 1961 |
if scope is not None: |
| 1962 |
hostname += "%" + str(scope) |
| 1963 |
if flags & socket.NI_NUMERICSERV: |
| 1964 |
service = str(port) |
| 1965 |
else: |
| 1966 |
service = socket.getservbyport(port, pname) |
| 1967 |
return (hostname, service) |
| 1968 |
|
| 1969 |
|
| 1970 |
def _getfqdn(name=None): |
| 1971 |
if name is None: |
| 1972 |
name = socket.gethostname() |
| 1973 |
try: |
| 1974 |
(name, _, _) = _gethostbyaddr(name) |
| 1975 |
# Python's version checks aliases too, but our gethostbyname |
| 1976 |
# ignores them, so we do so here as well. |
| 1977 |
except Exception: # pragma: no cover |
| 1978 |
pass |
| 1979 |
return name |
| 1980 |
|
| 1981 |
|
| 1982 |
def _gethostbyname(name): |
| 1983 |
return _gethostbyname_ex(name)[2][0] |
| 1984 |
|
| 1985 |
|
| 1986 |
def _gethostbyname_ex(name): |
| 1987 |
aliases = [] |
| 1988 |
addresses = [] |
| 1989 |
tuples = _getaddrinfo( |
| 1990 |
name, 0, socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME |
| 1991 |
) |
| 1992 |
canonical = tuples[0][3] |
| 1993 |
for item in tuples: |
| 1994 |
addresses.append(item[4][0]) |
| 1995 |
# XXX we just ignore aliases |
| 1996 |
return (canonical, aliases, addresses) |
| 1997 |
|
| 1998 |
|
| 1999 |
def _gethostbyaddr(ip): |
| 2000 |
try: |
| 2001 |
dns.ipv6.inet_aton(ip) |
| 2002 |
sockaddr = (ip, 80, 0, 0) |
| 2003 |
family = socket.AF_INET6 |
| 2004 |
except Exception: |
| 2005 |
try: |
| 2006 |
dns.ipv4.inet_aton(ip) |
| 2007 |
except Exception: |
| 2008 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 2009 |
sockaddr = (ip, 80) |
| 2010 |
family = socket.AF_INET |
| 2011 |
(name, _) = _getnameinfo(sockaddr, socket.NI_NAMEREQD) |
| 2012 |
aliases = [] |
| 2013 |
addresses = [] |
| 2014 |
tuples = _getaddrinfo( |
| 2015 |
name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME |
| 2016 |
) |
| 2017 |
canonical = tuples[0][3] |
| 2018 |
# We only want to include an address from the tuples if it's the |
| 2019 |
# same as the one we asked about. We do this comparison in binary |
| 2020 |
# to avoid any differences in text representations. |
| 2021 |
bin_ip = dns.inet.inet_pton(family, ip) |
| 2022 |
for item in tuples: |
| 2023 |
addr = item[4][0] |
| 2024 |
assert isinstance(addr, str) |
| 2025 |
bin_addr = dns.inet.inet_pton(family, addr) |
| 2026 |
if bin_ip == bin_addr: |
| 2027 |
addresses.append(addr) |
| 2028 |
# XXX we just ignore aliases |
| 2029 |
return (canonical, aliases, addresses) |
| 2030 |
|
| 2031 |
|
| 2032 |
def override_system_resolver(resolver: Resolver | None = None) -> None: |
| 2033 |
"""Override the system resolver routines in the socket module with |
| 2034 |
versions which use dnspython's resolver. |
| 2035 |
|
| 2036 |
This can be useful in testing situations where you want to control |
| 2037 |
the resolution behavior of python code without having to change |
| 2038 |
the system's resolver settings (e.g. /etc/resolv.conf). |
| 2039 |
|
| 2040 |
The resolver to use may be specified; if it's not, the default |
| 2041 |
resolver will be used. |
| 2042 |
|
| 2043 |
resolver, a ``dns.resolver.Resolver`` or ``None``, the resolver to use. |
| 2044 |
""" |
| 2045 |
|
| 2046 |
if resolver is None: |
| 2047 |
resolver = get_default_resolver() |
| 2048 |
global _resolver |
| 2049 |
_resolver = resolver |
| 2050 |
socket.getaddrinfo = _getaddrinfo |
| 2051 |
socket.getnameinfo = _getnameinfo |
| 2052 |
socket.getfqdn = _getfqdn |
| 2053 |
socket.gethostbyname = _gethostbyname |
| 2054 |
socket.gethostbyname_ex = _gethostbyname_ex |
| 2055 |
socket.gethostbyaddr = _gethostbyaddr |
| 2056 |
|
| 2057 |
|
| 2058 |
def restore_system_resolver() -> None: |
| 2059 |
"""Undo the effects of prior override_system_resolver().""" |
| 2060 |
|
| 2061 |
global _resolver |
| 2062 |
_resolver = None |
| 2063 |
socket.getaddrinfo = _original_getaddrinfo |
| 2064 |
socket.getnameinfo = _original_getnameinfo |
| 2065 |
socket.getfqdn = _original_getfqdn |
| 2066 |
socket.gethostbyname = _original_gethostbyname |
| 2067 |
socket.gethostbyname_ex = _original_gethostbyname_ex |
| 2068 |
socket.gethostbyaddr = _original_gethostbyaddr |