| 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 |
"""Talk to a DNS server.""" |
| 19 |
|
| 20 |
import base64 |
| 21 |
import contextlib |
| 22 |
import random |
| 23 |
import socket |
| 24 |
import struct |
| 25 |
import time |
| 26 |
import urllib.parse |
| 27 |
from typing import Any, Dict, Optional, Tuple, cast |
| 28 |
|
| 29 |
import dns.asyncbackend |
| 30 |
import dns.exception |
| 31 |
import dns.inet |
| 32 |
import dns.message |
| 33 |
import dns.name |
| 34 |
import dns.quic |
| 35 |
import dns.rdatatype |
| 36 |
import dns.transaction |
| 37 |
import dns.tsig |
| 38 |
import dns.xfr |
| 39 |
from dns._asyncbackend import NullContext |
| 40 |
from dns.query import ( |
| 41 |
BadResponse, |
| 42 |
HTTPVersion, |
| 43 |
NoDOH, |
| 44 |
NoDOQ, |
| 45 |
UDPMode, |
| 46 |
_check_status, |
| 47 |
_compute_times, |
| 48 |
_matches_destination, |
| 49 |
_remaining, |
| 50 |
have_doh, |
| 51 |
make_ssl_context, |
| 52 |
) |
| 53 |
|
| 54 |
try: |
| 55 |
import ssl |
| 56 |
except ImportError: |
| 57 |
import dns._no_ssl as ssl # type: ignore |
| 58 |
|
| 59 |
if have_doh: |
| 60 |
import httpx |
| 61 |
|
| 62 |
# for brevity |
| 63 |
_lltuple = dns.inet.low_level_address_tuple |
| 64 |
|
| 65 |
|
| 66 |
def _source_tuple(af, address, port): |
| 67 |
# Make a high level source tuple, or return None if address and port |
| 68 |
# are both None |
| 69 |
if address or port: |
| 70 |
if address is None: |
| 71 |
if af == socket.AF_INET: |
| 72 |
address = "0.0.0.0" |
| 73 |
elif af == socket.AF_INET6: |
| 74 |
address = "::" |
| 75 |
else: |
| 76 |
raise NotImplementedError(f"unknown address family {af}") |
| 77 |
return (address, port) |
| 78 |
else: |
| 79 |
return None |
| 80 |
|
| 81 |
|
| 82 |
def _timeout(expiration, now=None): |
| 83 |
if expiration is not None: |
| 84 |
if not now: |
| 85 |
now = time.time() |
| 86 |
return max(expiration - now, 0) |
| 87 |
else: |
| 88 |
return None |
| 89 |
|
| 90 |
|
| 91 |
async def send_udp( |
| 92 |
sock: dns.asyncbackend.DatagramSocket, |
| 93 |
what: dns.message.Message | bytes, |
| 94 |
destination: Any, |
| 95 |
expiration: float | None = None, |
| 96 |
) -> Tuple[int, float]: |
| 97 |
"""Send a DNS message to the specified UDP socket. |
| 98 |
|
| 99 |
*sock*, a ``dns.asyncbackend.DatagramSocket``. |
| 100 |
|
| 101 |
*what*, a ``bytes`` or ``dns.message.Message``, the message to send. |
| 102 |
|
| 103 |
*destination*, a destination tuple appropriate for the address family |
| 104 |
of the socket, specifying where to send the query. |
| 105 |
|
| 106 |
*expiration*, a ``float`` or ``None``, the absolute time at which |
| 107 |
a timeout exception should be raised. If ``None``, no timeout will |
| 108 |
occur. The expiration value is meaningless for the asyncio backend, as |
| 109 |
asyncio's transport sendto() never blocks. |
| 110 |
|
| 111 |
Returns an ``(int, float)`` tuple of bytes sent and the sent time. |
| 112 |
""" |
| 113 |
|
| 114 |
if isinstance(what, dns.message.Message): |
| 115 |
what = what.to_wire() |
| 116 |
sent_time = time.time() |
| 117 |
n = await sock.sendto(what, destination, _timeout(expiration, sent_time)) |
| 118 |
return (n, sent_time) |
| 119 |
|
| 120 |
|
| 121 |
async def receive_udp( |
| 122 |
sock: dns.asyncbackend.DatagramSocket, |
| 123 |
destination: Any | None = None, |
| 124 |
expiration: float | None = None, |
| 125 |
ignore_unexpected: bool = False, |
| 126 |
one_rr_per_rrset: bool = False, |
| 127 |
keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, |
| 128 |
request_mac: bytes | None = b"", |
| 129 |
ignore_trailing: bool = False, |
| 130 |
raise_on_truncation: bool = False, |
| 131 |
ignore_errors: bool = False, |
| 132 |
query: dns.message.Message | None = None, |
| 133 |
) -> Any: |
| 134 |
"""Read a DNS message from a UDP socket. |
| 135 |
|
| 136 |
*sock*, a ``dns.asyncbackend.DatagramSocket``. |
| 137 |
|
| 138 |
See :py:func:`dns.query.receive_udp()` for the documentation of the other |
| 139 |
parameters, and exceptions. |
| 140 |
|
| 141 |
Returns a ``(dns.message.Message, float, tuple)`` tuple of the received message, the |
| 142 |
received time, and the address where the message arrived from. |
| 143 |
""" |
| 144 |
|
| 145 |
wire = b"" |
| 146 |
while True: |
| 147 |
(wire, from_address) = await sock.recvfrom(65535, _timeout(expiration)) |
| 148 |
if not _matches_destination( |
| 149 |
sock.family, from_address, destination, ignore_unexpected |
| 150 |
): |
| 151 |
continue |
| 152 |
received_time = time.time() |
| 153 |
try: |
| 154 |
r = dns.message.from_wire( |
| 155 |
wire, |
| 156 |
keyring=keyring, |
| 157 |
request_mac=request_mac, |
| 158 |
one_rr_per_rrset=one_rr_per_rrset, |
| 159 |
ignore_trailing=ignore_trailing, |
| 160 |
raise_on_truncation=raise_on_truncation, |
| 161 |
) |
| 162 |
except dns.message.Truncated as e: |
| 163 |
# See the comment in query.py for details. |
| 164 |
if ( |
| 165 |
ignore_errors |
| 166 |
and query is not None |
| 167 |
and not query.is_response(e.message()) |
| 168 |
): |
| 169 |
continue |
| 170 |
else: |
| 171 |
raise |
| 172 |
except Exception: |
| 173 |
if ignore_errors: |
| 174 |
continue |
| 175 |
else: |
| 176 |
raise |
| 177 |
if ignore_errors and query is not None and not query.is_response(r): |
| 178 |
continue |
| 179 |
return (r, received_time, from_address) |
| 180 |
|
| 181 |
|
| 182 |
async def udp( |
| 183 |
q: dns.message.Message, |
| 184 |
where: str, |
| 185 |
timeout: float | None = None, |
| 186 |
port: int = 53, |
| 187 |
source: str | None = None, |
| 188 |
source_port: int = 0, |
| 189 |
ignore_unexpected: bool = False, |
| 190 |
one_rr_per_rrset: bool = False, |
| 191 |
ignore_trailing: bool = False, |
| 192 |
raise_on_truncation: bool = False, |
| 193 |
sock: dns.asyncbackend.DatagramSocket | None = None, |
| 194 |
backend: dns.asyncbackend.Backend | None = None, |
| 195 |
ignore_errors: bool = False, |
| 196 |
) -> dns.message.Message: |
| 197 |
"""Return the response obtained after sending a query via UDP. |
| 198 |
|
| 199 |
*sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, |
| 200 |
the socket to use for the query. If ``None``, the default, a |
| 201 |
socket is created. Note that if a socket is provided, the |
| 202 |
*source*, *source_port*, and *backend* are ignored. |
| 203 |
|
| 204 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 205 |
the default, then dnspython will use the default backend. |
| 206 |
|
| 207 |
See :py:func:`dns.query.udp()` for the documentation of the other |
| 208 |
parameters, exceptions, and return type of this method. |
| 209 |
""" |
| 210 |
wire = q.to_wire() |
| 211 |
(begin_time, expiration) = _compute_times(timeout) |
| 212 |
af = dns.inet.af_for_address(where) |
| 213 |
destination = _lltuple((where, port), af) |
| 214 |
if sock: |
| 215 |
cm: contextlib.AbstractAsyncContextManager = NullContext(sock) |
| 216 |
else: |
| 217 |
if not backend: |
| 218 |
backend = dns.asyncbackend.get_default_backend() |
| 219 |
stuple = _source_tuple(af, source, source_port) |
| 220 |
if backend.datagram_connection_required(): |
| 221 |
dtuple = (where, port) |
| 222 |
else: |
| 223 |
dtuple = None |
| 224 |
cm = await backend.make_socket(af, socket.SOCK_DGRAM, 0, stuple, dtuple) |
| 225 |
async with cm as s: |
| 226 |
await send_udp(s, wire, destination, expiration) # pyright: ignore |
| 227 |
(r, received_time, _) = await receive_udp( |
| 228 |
s, # pyright: ignore |
| 229 |
destination, |
| 230 |
expiration, |
| 231 |
ignore_unexpected, |
| 232 |
one_rr_per_rrset, |
| 233 |
q.keyring, |
| 234 |
q.mac, |
| 235 |
ignore_trailing, |
| 236 |
raise_on_truncation, |
| 237 |
ignore_errors, |
| 238 |
q, |
| 239 |
) |
| 240 |
r.time = received_time - begin_time |
| 241 |
# We don't need to check q.is_response() if we are in ignore_errors mode |
| 242 |
# as receive_udp() will have checked it. |
| 243 |
if not (ignore_errors or q.is_response(r)): |
| 244 |
raise BadResponse |
| 245 |
return r |
| 246 |
|
| 247 |
|
| 248 |
async def udp_with_fallback( |
| 249 |
q: dns.message.Message, |
| 250 |
where: str, |
| 251 |
timeout: float | None = None, |
| 252 |
port: int = 53, |
| 253 |
source: str | None = None, |
| 254 |
source_port: int = 0, |
| 255 |
ignore_unexpected: bool = False, |
| 256 |
one_rr_per_rrset: bool = False, |
| 257 |
ignore_trailing: bool = False, |
| 258 |
udp_sock: dns.asyncbackend.DatagramSocket | None = None, |
| 259 |
tcp_sock: dns.asyncbackend.StreamSocket | None = None, |
| 260 |
backend: dns.asyncbackend.Backend | None = None, |
| 261 |
ignore_errors: bool = False, |
| 262 |
) -> Tuple[dns.message.Message, bool]: |
| 263 |
"""Return the response to the query, trying UDP first and falling back |
| 264 |
to TCP if UDP results in a truncated response. |
| 265 |
|
| 266 |
*udp_sock*, a ``dns.asyncbackend.DatagramSocket``, or ``None``, |
| 267 |
the socket to use for the UDP query. If ``None``, the default, a |
| 268 |
socket is created. Note that if a socket is provided the *source*, |
| 269 |
*source_port*, and *backend* are ignored for the UDP query. |
| 270 |
|
| 271 |
*tcp_sock*, a ``dns.asyncbackend.StreamSocket``, or ``None``, the |
| 272 |
socket to use for the TCP query. If ``None``, the default, a |
| 273 |
socket is created. Note that if a socket is provided *where*, |
| 274 |
*source*, *source_port*, and *backend* are ignored for the TCP query. |
| 275 |
|
| 276 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 277 |
the default, then dnspython will use the default backend. |
| 278 |
|
| 279 |
See :py:func:`dns.query.udp_with_fallback()` for the documentation |
| 280 |
of the other parameters, exceptions, and return type of this |
| 281 |
method. |
| 282 |
""" |
| 283 |
try: |
| 284 |
response = await udp( |
| 285 |
q, |
| 286 |
where, |
| 287 |
timeout, |
| 288 |
port, |
| 289 |
source, |
| 290 |
source_port, |
| 291 |
ignore_unexpected, |
| 292 |
one_rr_per_rrset, |
| 293 |
ignore_trailing, |
| 294 |
True, |
| 295 |
udp_sock, |
| 296 |
backend, |
| 297 |
ignore_errors, |
| 298 |
) |
| 299 |
return (response, False) |
| 300 |
except dns.message.Truncated: |
| 301 |
response = await tcp( |
| 302 |
q, |
| 303 |
where, |
| 304 |
timeout, |
| 305 |
port, |
| 306 |
source, |
| 307 |
source_port, |
| 308 |
one_rr_per_rrset, |
| 309 |
ignore_trailing, |
| 310 |
tcp_sock, |
| 311 |
backend, |
| 312 |
) |
| 313 |
return (response, True) |
| 314 |
|
| 315 |
|
| 316 |
async def send_tcp( |
| 317 |
sock: dns.asyncbackend.StreamSocket, |
| 318 |
what: dns.message.Message | bytes, |
| 319 |
expiration: float | None = None, |
| 320 |
) -> Tuple[int, float]: |
| 321 |
"""Send a DNS message to the specified TCP socket. |
| 322 |
|
| 323 |
*sock*, a ``dns.asyncbackend.StreamSocket``. |
| 324 |
|
| 325 |
See :py:func:`dns.query.send_tcp()` for the documentation of the other |
| 326 |
parameters, exceptions, and return type of this method. |
| 327 |
""" |
| 328 |
|
| 329 |
if isinstance(what, dns.message.Message): |
| 330 |
tcpmsg = what.to_wire(prepend_length=True) |
| 331 |
else: |
| 332 |
# copying the wire into tcpmsg is inefficient, but lets us |
| 333 |
# avoid writev() or doing a short write that would get pushed |
| 334 |
# onto the net |
| 335 |
tcpmsg = len(what).to_bytes(2, "big") + what |
| 336 |
sent_time = time.time() |
| 337 |
await sock.sendall(tcpmsg, _timeout(expiration, sent_time)) |
| 338 |
return (len(tcpmsg), sent_time) |
| 339 |
|
| 340 |
|
| 341 |
async def _read_exactly(sock, count, expiration): |
| 342 |
"""Read the specified number of bytes from stream. Keep trying until we |
| 343 |
either get the desired amount, or we hit EOF. |
| 344 |
""" |
| 345 |
s = b"" |
| 346 |
while count > 0: |
| 347 |
n = await sock.recv(count, _timeout(expiration)) |
| 348 |
if n == b"": |
| 349 |
raise EOFError("EOF") |
| 350 |
count = count - len(n) |
| 351 |
s = s + n |
| 352 |
return s |
| 353 |
|
| 354 |
|
| 355 |
async def receive_tcp( |
| 356 |
sock: dns.asyncbackend.StreamSocket, |
| 357 |
expiration: float | None = None, |
| 358 |
one_rr_per_rrset: bool = False, |
| 359 |
keyring: Dict[dns.name.Name, dns.tsig.Key] | None = None, |
| 360 |
request_mac: bytes | None = b"", |
| 361 |
ignore_trailing: bool = False, |
| 362 |
) -> Tuple[dns.message.Message, float]: |
| 363 |
"""Read a DNS message from a TCP socket. |
| 364 |
|
| 365 |
*sock*, a ``dns.asyncbackend.StreamSocket``. |
| 366 |
|
| 367 |
See :py:func:`dns.query.receive_tcp()` for the documentation of the other |
| 368 |
parameters, exceptions, and return type of this method. |
| 369 |
""" |
| 370 |
|
| 371 |
ldata = await _read_exactly(sock, 2, expiration) |
| 372 |
(l,) = struct.unpack("!H", ldata) |
| 373 |
wire = await _read_exactly(sock, l, expiration) |
| 374 |
received_time = time.time() |
| 375 |
r = dns.message.from_wire( |
| 376 |
wire, |
| 377 |
keyring=keyring, |
| 378 |
request_mac=request_mac, |
| 379 |
one_rr_per_rrset=one_rr_per_rrset, |
| 380 |
ignore_trailing=ignore_trailing, |
| 381 |
) |
| 382 |
return (r, received_time) |
| 383 |
|
| 384 |
|
| 385 |
async def tcp( |
| 386 |
q: dns.message.Message, |
| 387 |
where: str, |
| 388 |
timeout: float | None = None, |
| 389 |
port: int = 53, |
| 390 |
source: str | None = None, |
| 391 |
source_port: int = 0, |
| 392 |
one_rr_per_rrset: bool = False, |
| 393 |
ignore_trailing: bool = False, |
| 394 |
sock: dns.asyncbackend.StreamSocket | None = None, |
| 395 |
backend: dns.asyncbackend.Backend | None = None, |
| 396 |
) -> dns.message.Message: |
| 397 |
"""Return the response obtained after sending a query via TCP. |
| 398 |
|
| 399 |
*sock*, a ``dns.asyncbacket.StreamSocket``, or ``None``, the |
| 400 |
socket to use for the query. If ``None``, the default, a socket |
| 401 |
is created. Note that if a socket is provided |
| 402 |
*where*, *port*, *source*, *source_port*, and *backend* are ignored. |
| 403 |
|
| 404 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 405 |
the default, then dnspython will use the default backend. |
| 406 |
|
| 407 |
See :py:func:`dns.query.tcp()` for the documentation of the other |
| 408 |
parameters, exceptions, and return type of this method. |
| 409 |
""" |
| 410 |
|
| 411 |
wire = q.to_wire() |
| 412 |
(begin_time, expiration) = _compute_times(timeout) |
| 413 |
if sock: |
| 414 |
# Verify that the socket is connected, as if it's not connected, |
| 415 |
# it's not writable, and the polling in send_tcp() will time out or |
| 416 |
# hang forever. |
| 417 |
await sock.getpeername() |
| 418 |
cm: contextlib.AbstractAsyncContextManager = NullContext(sock) |
| 419 |
else: |
| 420 |
# These are simple (address, port) pairs, not family-dependent tuples |
| 421 |
# you pass to low-level socket code. |
| 422 |
af = dns.inet.af_for_address(where) |
| 423 |
stuple = _source_tuple(af, source, source_port) |
| 424 |
dtuple = (where, port) |
| 425 |
if not backend: |
| 426 |
backend = dns.asyncbackend.get_default_backend() |
| 427 |
cm = await backend.make_socket( |
| 428 |
af, socket.SOCK_STREAM, 0, stuple, dtuple, timeout |
| 429 |
) |
| 430 |
async with cm as s: |
| 431 |
await send_tcp(s, wire, expiration) # pyright: ignore |
| 432 |
(r, received_time) = await receive_tcp( |
| 433 |
s, # pyright: ignore |
| 434 |
expiration, |
| 435 |
one_rr_per_rrset, |
| 436 |
q.keyring, |
| 437 |
q.mac, |
| 438 |
ignore_trailing, |
| 439 |
) |
| 440 |
r.time = received_time - begin_time |
| 441 |
if not q.is_response(r): |
| 442 |
raise BadResponse |
| 443 |
return r |
| 444 |
|
| 445 |
|
| 446 |
async def tls( |
| 447 |
q: dns.message.Message, |
| 448 |
where: str, |
| 449 |
timeout: float | None = None, |
| 450 |
port: int = 853, |
| 451 |
source: str | None = None, |
| 452 |
source_port: int = 0, |
| 453 |
one_rr_per_rrset: bool = False, |
| 454 |
ignore_trailing: bool = False, |
| 455 |
sock: dns.asyncbackend.StreamSocket | None = None, |
| 456 |
backend: dns.asyncbackend.Backend | None = None, |
| 457 |
ssl_context: ssl.SSLContext | None = None, |
| 458 |
server_hostname: str | None = None, |
| 459 |
verify: bool | str = True, |
| 460 |
) -> dns.message.Message: |
| 461 |
"""Return the response obtained after sending a query via TLS. |
| 462 |
|
| 463 |
*sock*, an ``asyncbackend.StreamSocket``, or ``None``, the socket |
| 464 |
to use for the query. If ``None``, the default, a socket is |
| 465 |
created. Note that if a socket is provided, it must be a |
| 466 |
connected SSL stream socket, and *where*, *port*, |
| 467 |
*source*, *source_port*, *backend*, *ssl_context*, and *server_hostname* |
| 468 |
are ignored. |
| 469 |
|
| 470 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 471 |
the default, then dnspython will use the default backend. |
| 472 |
|
| 473 |
See :py:func:`dns.query.tls()` for the documentation of the other |
| 474 |
parameters, exceptions, and return type of this method. |
| 475 |
""" |
| 476 |
(begin_time, expiration) = _compute_times(timeout) |
| 477 |
if sock: |
| 478 |
cm: contextlib.AbstractAsyncContextManager = NullContext(sock) |
| 479 |
else: |
| 480 |
if ssl_context is None: |
| 481 |
ssl_context = make_ssl_context(verify, server_hostname is not None, ["dot"]) |
| 482 |
af = dns.inet.af_for_address(where) |
| 483 |
stuple = _source_tuple(af, source, source_port) |
| 484 |
dtuple = (where, port) |
| 485 |
if not backend: |
| 486 |
backend = dns.asyncbackend.get_default_backend() |
| 487 |
cm = await backend.make_socket( |
| 488 |
af, |
| 489 |
socket.SOCK_STREAM, |
| 490 |
0, |
| 491 |
stuple, |
| 492 |
dtuple, |
| 493 |
timeout, |
| 494 |
ssl_context, |
| 495 |
server_hostname, |
| 496 |
) |
| 497 |
async with cm as s: |
| 498 |
timeout = _timeout(expiration) |
| 499 |
response = await tcp( |
| 500 |
q, |
| 501 |
where, |
| 502 |
timeout, |
| 503 |
port, |
| 504 |
source, |
| 505 |
source_port, |
| 506 |
one_rr_per_rrset, |
| 507 |
ignore_trailing, |
| 508 |
s, |
| 509 |
backend, |
| 510 |
) |
| 511 |
end_time = time.time() |
| 512 |
response.time = end_time - begin_time |
| 513 |
return response |
| 514 |
|
| 515 |
|
| 516 |
def _maybe_get_resolver( |
| 517 |
resolver: Optional["dns.asyncresolver.Resolver"], # pyright: ignore |
| 518 |
) -> "dns.asyncresolver.Resolver": # pyright: ignore |
| 519 |
# We need a separate method for this to avoid overriding the global |
| 520 |
# variable "dns" with the as-yet undefined local variable "dns" |
| 521 |
# in https(). |
| 522 |
if resolver is None: |
| 523 |
# pylint: disable=import-outside-toplevel,redefined-outer-name |
| 524 |
import dns.asyncresolver |
| 525 |
|
| 526 |
resolver = dns.asyncresolver.Resolver() |
| 527 |
return resolver |
| 528 |
|
| 529 |
|
| 530 |
async def https( |
| 531 |
q: dns.message.Message, |
| 532 |
where: str, |
| 533 |
timeout: float | None = None, |
| 534 |
port: int = 443, |
| 535 |
source: str | None = None, |
| 536 |
source_port: int = 0, # pylint: disable=W0613 |
| 537 |
one_rr_per_rrset: bool = False, |
| 538 |
ignore_trailing: bool = False, |
| 539 |
client: Optional["httpx.AsyncClient|dns.quic.AsyncQuicConnection"] = None, |
| 540 |
path: str = "/dns-query", |
| 541 |
post: bool = True, |
| 542 |
verify: bool | str | ssl.SSLContext = True, |
| 543 |
bootstrap_address: str | None = None, |
| 544 |
resolver: Optional["dns.asyncresolver.Resolver"] = None, # pyright: ignore |
| 545 |
family: int = socket.AF_UNSPEC, |
| 546 |
http_version: HTTPVersion = HTTPVersion.DEFAULT, |
| 547 |
) -> dns.message.Message: |
| 548 |
"""Return the response obtained after sending a query via DNS-over-HTTPS. |
| 549 |
|
| 550 |
*client*, a ``httpx.AsyncClient``. If provided, the client to use for |
| 551 |
the query. |
| 552 |
|
| 553 |
Unlike the other dnspython async functions, a backend cannot be provided |
| 554 |
in this function because httpx always auto-detects the async backend. |
| 555 |
|
| 556 |
See :py:func:`dns.query.https()` for the documentation of the other |
| 557 |
parameters, exceptions, and return type of this method. |
| 558 |
""" |
| 559 |
|
| 560 |
try: |
| 561 |
af = dns.inet.af_for_address(where) |
| 562 |
except ValueError: |
| 563 |
af = None |
| 564 |
# we bind url and then override as pyright can't figure out all paths bind. |
| 565 |
url = where |
| 566 |
if af is not None and dns.inet.is_address(where): |
| 567 |
if af == socket.AF_INET: |
| 568 |
url = f"https://{where}:{port}{path}" |
| 569 |
elif af == socket.AF_INET6: |
| 570 |
url = f"https://[{where}]:{port}{path}" |
| 571 |
|
| 572 |
extensions = {} |
| 573 |
if bootstrap_address is None: |
| 574 |
# pylint: disable=possibly-used-before-assignment |
| 575 |
parsed = urllib.parse.urlparse(url) |
| 576 |
if parsed.hostname is None: |
| 577 |
raise ValueError("no hostname in URL") |
| 578 |
if dns.inet.is_address(parsed.hostname): |
| 579 |
bootstrap_address = parsed.hostname |
| 580 |
extensions["sni_hostname"] = parsed.hostname |
| 581 |
if parsed.port is not None: |
| 582 |
port = parsed.port |
| 583 |
|
| 584 |
if http_version == HTTPVersion.H3 or ( |
| 585 |
http_version == HTTPVersion.DEFAULT and not have_doh |
| 586 |
): |
| 587 |
if bootstrap_address is None: |
| 588 |
resolver = _maybe_get_resolver(resolver) |
| 589 |
assert parsed.hostname is not None # pyright: ignore |
| 590 |
answers = await resolver.resolve_name( # pyright: ignore |
| 591 |
parsed.hostname, family # pyright: ignore |
| 592 |
) |
| 593 |
bootstrap_address = random.choice(list(answers.addresses())) |
| 594 |
if client and not isinstance( |
| 595 |
client, dns.quic.AsyncQuicConnection |
| 596 |
): # pyright: ignore |
| 597 |
raise ValueError("client parameter must be a dns.quic.AsyncQuicConnection.") |
| 598 |
assert client is None or isinstance(client, dns.quic.AsyncQuicConnection) |
| 599 |
return await _http3( |
| 600 |
q, |
| 601 |
bootstrap_address, |
| 602 |
url, |
| 603 |
timeout, |
| 604 |
port, |
| 605 |
source, |
| 606 |
source_port, |
| 607 |
one_rr_per_rrset, |
| 608 |
ignore_trailing, |
| 609 |
verify=verify, |
| 610 |
post=post, |
| 611 |
connection=client, |
| 612 |
) |
| 613 |
|
| 614 |
if not have_doh: |
| 615 |
raise NoDOH # pragma: no cover |
| 616 |
# pylint: disable=possibly-used-before-assignment |
| 617 |
if client and not isinstance(client, httpx.AsyncClient): # pyright: ignore |
| 618 |
raise ValueError("client parameter must be an httpx.AsyncClient") |
| 619 |
# pylint: enable=possibly-used-before-assignment |
| 620 |
|
| 621 |
wire = q.to_wire() |
| 622 |
headers = {"accept": "application/dns-message"} |
| 623 |
|
| 624 |
h1 = http_version in (HTTPVersion.H1, HTTPVersion.DEFAULT) |
| 625 |
h2 = http_version in (HTTPVersion.H2, HTTPVersion.DEFAULT) |
| 626 |
|
| 627 |
backend = dns.asyncbackend.get_default_backend() |
| 628 |
|
| 629 |
if source is None: |
| 630 |
local_address = None |
| 631 |
local_port = 0 |
| 632 |
else: |
| 633 |
local_address = source |
| 634 |
local_port = source_port |
| 635 |
|
| 636 |
if client: |
| 637 |
cm: contextlib.AbstractAsyncContextManager = NullContext(client) |
| 638 |
else: |
| 639 |
transport = backend.get_transport_class()( |
| 640 |
local_address=local_address, |
| 641 |
http1=h1, |
| 642 |
http2=h2, |
| 643 |
verify=verify, |
| 644 |
local_port=local_port, |
| 645 |
bootstrap_address=bootstrap_address, |
| 646 |
resolver=resolver, |
| 647 |
family=family, |
| 648 |
) |
| 649 |
|
| 650 |
cm = httpx.AsyncClient( # pyright: ignore |
| 651 |
http1=h1, http2=h2, verify=verify, transport=transport # type: ignore |
| 652 |
) |
| 653 |
|
| 654 |
async with cm as the_client: |
| 655 |
# see https://tools.ietf.org/html/rfc8484#section-4.1.1 for DoH |
| 656 |
# GET and POST examples |
| 657 |
if post: |
| 658 |
headers.update( |
| 659 |
{ |
| 660 |
"content-type": "application/dns-message", |
| 661 |
"content-length": str(len(wire)), |
| 662 |
} |
| 663 |
) |
| 664 |
response = await backend.wait_for( |
| 665 |
the_client.post( # pyright: ignore |
| 666 |
url, |
| 667 |
headers=headers, |
| 668 |
content=wire, |
| 669 |
extensions=extensions, |
| 670 |
), |
| 671 |
timeout, |
| 672 |
) |
| 673 |
else: |
| 674 |
wire = base64.urlsafe_b64encode(wire).rstrip(b"=") |
| 675 |
twire = wire.decode() # httpx does a repr() if we give it bytes |
| 676 |
response = await backend.wait_for( |
| 677 |
the_client.get( # pyright: ignore |
| 678 |
url, |
| 679 |
headers=headers, |
| 680 |
params={"dns": twire}, |
| 681 |
extensions=extensions, |
| 682 |
), |
| 683 |
timeout, |
| 684 |
) |
| 685 |
|
| 686 |
# see https://tools.ietf.org/html/rfc8484#section-4.2.1 for info about DoH |
| 687 |
# status codes |
| 688 |
if response.status_code < 200 or response.status_code > 299: |
| 689 |
raise ValueError( |
| 690 |
f"{where} responded with status code {response.status_code}" |
| 691 |
f"\nResponse body: {response.content!r}" |
| 692 |
) |
| 693 |
r = dns.message.from_wire( |
| 694 |
response.content, |
| 695 |
keyring=q.keyring, |
| 696 |
request_mac=q.request_mac, |
| 697 |
one_rr_per_rrset=one_rr_per_rrset, |
| 698 |
ignore_trailing=ignore_trailing, |
| 699 |
) |
| 700 |
r.time = response.elapsed.total_seconds() |
| 701 |
if not q.is_response(r): |
| 702 |
raise BadResponse |
| 703 |
return r |
| 704 |
|
| 705 |
|
| 706 |
async def _http3( |
| 707 |
q: dns.message.Message, |
| 708 |
where: str, |
| 709 |
url: str, |
| 710 |
timeout: float | None = None, |
| 711 |
port: int = 443, |
| 712 |
source: str | None = None, |
| 713 |
source_port: int = 0, |
| 714 |
one_rr_per_rrset: bool = False, |
| 715 |
ignore_trailing: bool = False, |
| 716 |
verify: bool | str | ssl.SSLContext = True, |
| 717 |
backend: dns.asyncbackend.Backend | None = None, |
| 718 |
post: bool = True, |
| 719 |
connection: dns.quic.AsyncQuicConnection | None = None, |
| 720 |
) -> dns.message.Message: |
| 721 |
if not dns.quic.have_quic: |
| 722 |
raise NoDOH("DNS-over-HTTP3 is not available.") # pragma: no cover |
| 723 |
|
| 724 |
url_parts = urllib.parse.urlparse(url) |
| 725 |
hostname = url_parts.hostname |
| 726 |
assert hostname is not None |
| 727 |
if url_parts.port is not None: |
| 728 |
port = url_parts.port |
| 729 |
|
| 730 |
q.id = 0 |
| 731 |
wire = q.to_wire() |
| 732 |
the_connection: dns.quic.AsyncQuicConnection |
| 733 |
if connection: |
| 734 |
cfactory = dns.quic.null_factory |
| 735 |
mfactory = dns.quic.null_factory |
| 736 |
else: |
| 737 |
(cfactory, mfactory) = dns.quic.factories_for_backend(backend) |
| 738 |
|
| 739 |
async with cfactory() as context: |
| 740 |
async with mfactory( |
| 741 |
context, verify_mode=verify, server_name=hostname, h3=True |
| 742 |
) as the_manager: |
| 743 |
if connection: |
| 744 |
the_connection = connection |
| 745 |
else: |
| 746 |
the_connection = the_manager.connect( # pyright: ignore |
| 747 |
where, port, source, source_port |
| 748 |
) |
| 749 |
(start, expiration) = _compute_times(timeout) |
| 750 |
stream = await the_connection.make_stream(timeout) # pyright: ignore |
| 751 |
async with stream: |
| 752 |
# note that send_h3() does not need await |
| 753 |
stream.send_h3(url, wire, post) |
| 754 |
wire = await stream.receive(_remaining(expiration)) |
| 755 |
_check_status(stream.headers(), where, wire) |
| 756 |
finish = time.time() |
| 757 |
r = dns.message.from_wire( |
| 758 |
wire, |
| 759 |
keyring=q.keyring, |
| 760 |
request_mac=q.request_mac, |
| 761 |
one_rr_per_rrset=one_rr_per_rrset, |
| 762 |
ignore_trailing=ignore_trailing, |
| 763 |
) |
| 764 |
r.time = max(finish - start, 0.0) |
| 765 |
if not q.is_response(r): |
| 766 |
raise BadResponse |
| 767 |
return r |
| 768 |
|
| 769 |
|
| 770 |
async def quic( |
| 771 |
q: dns.message.Message, |
| 772 |
where: str, |
| 773 |
timeout: float | None = None, |
| 774 |
port: int = 853, |
| 775 |
source: str | None = None, |
| 776 |
source_port: int = 0, |
| 777 |
one_rr_per_rrset: bool = False, |
| 778 |
ignore_trailing: bool = False, |
| 779 |
connection: dns.quic.AsyncQuicConnection | None = None, |
| 780 |
verify: bool | str = True, |
| 781 |
backend: dns.asyncbackend.Backend | None = None, |
| 782 |
hostname: str | None = None, |
| 783 |
server_hostname: str | None = None, |
| 784 |
) -> dns.message.Message: |
| 785 |
"""Return the response obtained after sending an asynchronous query via |
| 786 |
DNS-over-QUIC. |
| 787 |
|
| 788 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 789 |
the default, then dnspython will use the default backend. |
| 790 |
|
| 791 |
See :py:func:`dns.query.quic()` for the documentation of the other |
| 792 |
parameters, exceptions, and return type of this method. |
| 793 |
""" |
| 794 |
|
| 795 |
if not dns.quic.have_quic: |
| 796 |
raise NoDOQ("DNS-over-QUIC is not available.") # pragma: no cover |
| 797 |
|
| 798 |
if server_hostname is not None and hostname is None: |
| 799 |
hostname = server_hostname |
| 800 |
|
| 801 |
q.id = 0 |
| 802 |
wire = q.to_wire() |
| 803 |
the_connection: dns.quic.AsyncQuicConnection |
| 804 |
if connection: |
| 805 |
cfactory = dns.quic.null_factory |
| 806 |
mfactory = dns.quic.null_factory |
| 807 |
the_connection = connection |
| 808 |
else: |
| 809 |
(cfactory, mfactory) = dns.quic.factories_for_backend(backend) |
| 810 |
|
| 811 |
async with cfactory() as context: |
| 812 |
async with mfactory( |
| 813 |
context, |
| 814 |
verify_mode=verify, |
| 815 |
server_name=server_hostname, |
| 816 |
) as the_manager: |
| 817 |
if not connection: |
| 818 |
the_connection = the_manager.connect( # pyright: ignore |
| 819 |
where, port, source, source_port |
| 820 |
) |
| 821 |
(start, expiration) = _compute_times(timeout) |
| 822 |
stream = await the_connection.make_stream(timeout) # pyright: ignore |
| 823 |
async with stream: |
| 824 |
await stream.send(wire, True) |
| 825 |
wire = await stream.receive(_remaining(expiration)) |
| 826 |
finish = time.time() |
| 827 |
r = dns.message.from_wire( |
| 828 |
wire, |
| 829 |
keyring=q.keyring, |
| 830 |
request_mac=q.request_mac, |
| 831 |
one_rr_per_rrset=one_rr_per_rrset, |
| 832 |
ignore_trailing=ignore_trailing, |
| 833 |
) |
| 834 |
r.time = max(finish - start, 0.0) |
| 835 |
if not q.is_response(r): |
| 836 |
raise BadResponse |
| 837 |
return r |
| 838 |
|
| 839 |
|
| 840 |
async def _inbound_xfr( |
| 841 |
txn_manager: dns.transaction.TransactionManager, |
| 842 |
s: dns.asyncbackend.Socket, |
| 843 |
query: dns.message.Message, |
| 844 |
serial: int | None, |
| 845 |
timeout: float | None, |
| 846 |
expiration: float, |
| 847 |
) -> Any: |
| 848 |
"""Given a socket, does the zone transfer.""" |
| 849 |
rdtype = query.question[0].rdtype |
| 850 |
is_ixfr = rdtype == dns.rdatatype.IXFR |
| 851 |
origin = txn_manager.from_wire_origin() |
| 852 |
wire = query.to_wire() |
| 853 |
is_udp = s.type == socket.SOCK_DGRAM |
| 854 |
if is_udp: |
| 855 |
udp_sock = cast(dns.asyncbackend.DatagramSocket, s) |
| 856 |
await udp_sock.sendto(wire, None, _timeout(expiration)) |
| 857 |
else: |
| 858 |
tcp_sock = cast(dns.asyncbackend.StreamSocket, s) |
| 859 |
tcpmsg = struct.pack("!H", len(wire)) + wire |
| 860 |
await tcp_sock.sendall(tcpmsg, expiration) |
| 861 |
with dns.xfr.Inbound(txn_manager, rdtype, serial, is_udp) as inbound: |
| 862 |
done = False |
| 863 |
tsig_ctx = None |
| 864 |
r: dns.message.Message | None = None |
| 865 |
while not done: |
| 866 |
(_, mexpiration) = _compute_times(timeout) |
| 867 |
if mexpiration is None or ( |
| 868 |
expiration is not None and mexpiration > expiration |
| 869 |
): |
| 870 |
mexpiration = expiration |
| 871 |
if is_udp: |
| 872 |
timeout = _timeout(mexpiration) |
| 873 |
(rwire, _) = await udp_sock.recvfrom(65535, timeout) # pyright: ignore |
| 874 |
else: |
| 875 |
ldata = await _read_exactly(tcp_sock, 2, mexpiration) # pyright: ignore |
| 876 |
(l,) = struct.unpack("!H", ldata) |
| 877 |
rwire = await _read_exactly(tcp_sock, l, mexpiration) # pyright: ignore |
| 878 |
r = dns.message.from_wire( |
| 879 |
rwire, |
| 880 |
keyring=query.keyring, |
| 881 |
request_mac=query.mac, |
| 882 |
xfr=True, |
| 883 |
origin=origin, |
| 884 |
tsig_ctx=tsig_ctx, |
| 885 |
multi=(not is_udp), |
| 886 |
one_rr_per_rrset=is_ixfr, |
| 887 |
) |
| 888 |
done = inbound.process_message(r) |
| 889 |
yield r |
| 890 |
tsig_ctx = r.tsig_ctx |
| 891 |
if query.keyring and r is not None and not r.had_tsig: |
| 892 |
raise dns.exception.FormError("missing TSIG") |
| 893 |
|
| 894 |
|
| 895 |
async def inbound_xfr( |
| 896 |
where: str, |
| 897 |
txn_manager: dns.transaction.TransactionManager, |
| 898 |
query: dns.message.Message | None = None, |
| 899 |
port: int = 53, |
| 900 |
timeout: float | None = None, |
| 901 |
lifetime: float | None = None, |
| 902 |
source: str | None = None, |
| 903 |
source_port: int = 0, |
| 904 |
udp_mode: UDPMode = UDPMode.NEVER, |
| 905 |
backend: dns.asyncbackend.Backend | None = None, |
| 906 |
) -> None: |
| 907 |
"""Conduct an inbound transfer and apply it via a transaction from the |
| 908 |
txn_manager. |
| 909 |
|
| 910 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 911 |
the default, then dnspython will use the default backend. |
| 912 |
|
| 913 |
See :py:func:`dns.query.inbound_xfr()` for the documentation of |
| 914 |
the other parameters, exceptions, and return type of this method. |
| 915 |
""" |
| 916 |
if query is None: |
| 917 |
(query, serial) = dns.xfr.make_query(txn_manager) |
| 918 |
else: |
| 919 |
serial = dns.xfr.extract_serial_from_query(query) |
| 920 |
af = dns.inet.af_for_address(where) |
| 921 |
stuple = _source_tuple(af, source, source_port) |
| 922 |
dtuple = (where, port) |
| 923 |
if not backend: |
| 924 |
backend = dns.asyncbackend.get_default_backend() |
| 925 |
(_, expiration) = _compute_times(lifetime) |
| 926 |
if query.question[0].rdtype == dns.rdatatype.IXFR and udp_mode != UDPMode.NEVER: |
| 927 |
s = await backend.make_socket( |
| 928 |
af, socket.SOCK_DGRAM, 0, stuple, dtuple, _timeout(expiration) |
| 929 |
) |
| 930 |
async with s: |
| 931 |
try: |
| 932 |
async for _ in _inbound_xfr( # pyright: ignore |
| 933 |
txn_manager, |
| 934 |
s, |
| 935 |
query, |
| 936 |
serial, |
| 937 |
timeout, |
| 938 |
expiration, # pyright: ignore |
| 939 |
): |
| 940 |
pass |
| 941 |
return |
| 942 |
except dns.xfr.UseTCP: |
| 943 |
if udp_mode == UDPMode.ONLY: |
| 944 |
raise |
| 945 |
|
| 946 |
s = await backend.make_socket( |
| 947 |
af, socket.SOCK_STREAM, 0, stuple, dtuple, _timeout(expiration) |
| 948 |
) |
| 949 |
async with s: |
| 950 |
async for _ in _inbound_xfr( # pyright: ignore |
| 951 |
txn_manager, s, query, serial, timeout, expiration # pyright: ignore |
| 952 |
): |
| 953 |
pass |