| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
"""asyncio library query support""" |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import socket |
| 7 |
import sys |
| 8 |
|
| 9 |
import dns._asyncbackend |
| 10 |
import dns._features |
| 11 |
import dns.exception |
| 12 |
import dns.inet |
| 13 |
|
| 14 |
_is_win32 = sys.platform == "win32" |
| 15 |
|
| 16 |
|
| 17 |
def _get_running_loop(): |
| 18 |
try: |
| 19 |
return asyncio.get_running_loop() |
| 20 |
except AttributeError: # pragma: no cover |
| 21 |
return asyncio.get_event_loop() |
| 22 |
|
| 23 |
|
| 24 |
class _DatagramProtocol: |
| 25 |
def __init__(self): |
| 26 |
self.transport = None |
| 27 |
self.recvfrom = None |
| 28 |
|
| 29 |
def connection_made(self, transport): |
| 30 |
self.transport = transport |
| 31 |
|
| 32 |
def datagram_received(self, data, addr): |
| 33 |
if self.recvfrom and not self.recvfrom.done(): |
| 34 |
self.recvfrom.set_result((data, addr)) |
| 35 |
|
| 36 |
def error_received(self, exc): # pragma: no cover |
| 37 |
if self.recvfrom and not self.recvfrom.done(): |
| 38 |
self.recvfrom.set_exception(exc) |
| 39 |
|
| 40 |
def connection_lost(self, exc): |
| 41 |
if self.recvfrom and not self.recvfrom.done(): |
| 42 |
if exc is None: |
| 43 |
# EOF we triggered. Is there a better way to do this? |
| 44 |
try: |
| 45 |
raise EOFError("EOF") |
| 46 |
except EOFError as e: |
| 47 |
self.recvfrom.set_exception(e) |
| 48 |
else: |
| 49 |
self.recvfrom.set_exception(exc) |
| 50 |
|
| 51 |
def close(self): |
| 52 |
if self.transport is not None: |
| 53 |
self.transport.close() |
| 54 |
|
| 55 |
|
| 56 |
async def _maybe_wait_for(awaitable, timeout): |
| 57 |
if timeout is not None: |
| 58 |
try: |
| 59 |
return await asyncio.wait_for(awaitable, timeout) |
| 60 |
except asyncio.TimeoutError: |
| 61 |
raise dns.exception.Timeout(timeout=timeout) |
| 62 |
else: |
| 63 |
return await awaitable |
| 64 |
|
| 65 |
|
| 66 |
class DatagramSocket(dns._asyncbackend.DatagramSocket): |
| 67 |
def __init__(self, family, transport, protocol): |
| 68 |
super().__init__(family, socket.SOCK_DGRAM) |
| 69 |
self.transport = transport |
| 70 |
self.protocol = protocol |
| 71 |
|
| 72 |
async def sendto(self, what, destination, timeout): # pragma: no cover |
| 73 |
# no timeout for asyncio sendto |
| 74 |
self.transport.sendto(what, destination) |
| 75 |
return len(what) |
| 76 |
|
| 77 |
async def recvfrom(self, size, timeout): |
| 78 |
# ignore size as there's no way I know to tell protocol about it |
| 79 |
done = _get_running_loop().create_future() |
| 80 |
try: |
| 81 |
assert self.protocol.recvfrom is None |
| 82 |
self.protocol.recvfrom = done |
| 83 |
await _maybe_wait_for(done, timeout) |
| 84 |
return done.result() |
| 85 |
finally: |
| 86 |
self.protocol.recvfrom = None |
| 87 |
|
| 88 |
async def close(self): |
| 89 |
self.protocol.close() |
| 90 |
|
| 91 |
async def getpeername(self): |
| 92 |
return self.transport.get_extra_info("peername") |
| 93 |
|
| 94 |
async def getsockname(self): |
| 95 |
return self.transport.get_extra_info("sockname") |
| 96 |
|
| 97 |
async def getpeercert(self, timeout): |
| 98 |
raise NotImplementedError |
| 99 |
|
| 100 |
|
| 101 |
class StreamSocket(dns._asyncbackend.StreamSocket): |
| 102 |
def __init__(self, af, reader, writer): |
| 103 |
super().__init__(af, socket.SOCK_STREAM) |
| 104 |
self.reader = reader |
| 105 |
self.writer = writer |
| 106 |
|
| 107 |
async def sendall(self, what, timeout): |
| 108 |
self.writer.write(what) |
| 109 |
return await _maybe_wait_for(self.writer.drain(), timeout) |
| 110 |
|
| 111 |
async def recv(self, size, timeout): |
| 112 |
return await _maybe_wait_for(self.reader.read(size), timeout) |
| 113 |
|
| 114 |
async def close(self): |
| 115 |
self.writer.close() |
| 116 |
|
| 117 |
async def getpeername(self): |
| 118 |
return self.writer.get_extra_info("peername") |
| 119 |
|
| 120 |
async def getsockname(self): |
| 121 |
return self.writer.get_extra_info("sockname") |
| 122 |
|
| 123 |
async def getpeercert(self, timeout): |
| 124 |
return self.writer.get_extra_info("peercert") |
| 125 |
|
| 126 |
|
| 127 |
if dns._features.have("doh"): |
| 128 |
import anyio |
| 129 |
import httpcore |
| 130 |
import httpcore._backends.anyio |
| 131 |
import httpx |
| 132 |
|
| 133 |
_CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend |
| 134 |
_CoreAnyIOStream = httpcore._backends.anyio.AnyIOStream # pyright: ignore |
| 135 |
|
| 136 |
from dns.query import _compute_times, _expiration_for_this_attempt, _remaining |
| 137 |
|
| 138 |
class _NetworkBackend(_CoreAsyncNetworkBackend): |
| 139 |
def __init__(self, resolver, local_port, bootstrap_address, family): |
| 140 |
super().__init__() |
| 141 |
self._local_port = local_port |
| 142 |
self._resolver = resolver |
| 143 |
self._bootstrap_address = bootstrap_address |
| 144 |
self._family = family |
| 145 |
if local_port != 0: |
| 146 |
raise NotImplementedError( |
| 147 |
"the asyncio transport for HTTPX cannot set the local port" |
| 148 |
) |
| 149 |
|
| 150 |
async def connect_tcp( |
| 151 |
self, host, port, timeout=None, local_address=None, socket_options=None |
| 152 |
): # pylint: disable=signature-differs |
| 153 |
addresses = [] |
| 154 |
_, expiration = _compute_times(timeout) |
| 155 |
if dns.inet.is_address(host): |
| 156 |
addresses.append(host) |
| 157 |
elif self._bootstrap_address is not None: |
| 158 |
addresses.append(self._bootstrap_address) |
| 159 |
else: |
| 160 |
timeout = _remaining(expiration) |
| 161 |
family = self._family |
| 162 |
if local_address: |
| 163 |
family = dns.inet.af_for_address(local_address) |
| 164 |
answers = await self._resolver.resolve_name( |
| 165 |
host, family=family, lifetime=timeout |
| 166 |
) |
| 167 |
addresses = answers.addresses() |
| 168 |
for address in addresses: |
| 169 |
try: |
| 170 |
attempt_expiration = _expiration_for_this_attempt(2.0, expiration) |
| 171 |
timeout = _remaining(attempt_expiration) |
| 172 |
with anyio.fail_after(timeout): |
| 173 |
stream = await anyio.connect_tcp( |
| 174 |
remote_host=address, |
| 175 |
remote_port=port, |
| 176 |
local_host=local_address, |
| 177 |
) |
| 178 |
return _CoreAnyIOStream(stream) |
| 179 |
except Exception: |
| 180 |
pass |
| 181 |
raise httpcore.ConnectError |
| 182 |
|
| 183 |
async def connect_unix_socket( |
| 184 |
self, path, timeout=None, socket_options=None |
| 185 |
): # pylint: disable=signature-differs |
| 186 |
raise NotImplementedError |
| 187 |
|
| 188 |
async def sleep(self, seconds): # pylint: disable=signature-differs |
| 189 |
await anyio.sleep(seconds) |
| 190 |
|
| 191 |
class _HTTPTransport(httpx.AsyncHTTPTransport): |
| 192 |
def __init__( |
| 193 |
self, |
| 194 |
*args, |
| 195 |
local_port=0, |
| 196 |
bootstrap_address=None, |
| 197 |
resolver=None, |
| 198 |
family=socket.AF_UNSPEC, |
| 199 |
**kwargs, |
| 200 |
): |
| 201 |
if resolver is None and bootstrap_address is None: |
| 202 |
# pylint: disable=import-outside-toplevel,redefined-outer-name |
| 203 |
import dns.asyncresolver |
| 204 |
|
| 205 |
resolver = dns.asyncresolver.Resolver() |
| 206 |
super().__init__(*args, **kwargs) |
| 207 |
self._pool._network_backend = _NetworkBackend( |
| 208 |
resolver, local_port, bootstrap_address, family |
| 209 |
) |
| 210 |
|
| 211 |
else: |
| 212 |
_HTTPTransport = dns._asyncbackend.NullTransport # type: ignore |
| 213 |
|
| 214 |
|
| 215 |
class Backend(dns._asyncbackend.Backend): |
| 216 |
def name(self): |
| 217 |
return "asyncio" |
| 218 |
|
| 219 |
async def make_socket( |
| 220 |
self, |
| 221 |
af, |
| 222 |
socktype, |
| 223 |
proto=0, |
| 224 |
source=None, |
| 225 |
destination=None, |
| 226 |
timeout=None, |
| 227 |
ssl_context=None, |
| 228 |
server_hostname=None, |
| 229 |
): |
| 230 |
loop = _get_running_loop() |
| 231 |
if socktype == socket.SOCK_DGRAM: |
| 232 |
if _is_win32 and source is None: |
| 233 |
# Win32 wants explicit binding before recvfrom(). This is the |
| 234 |
# proper fix for [#637]. |
| 235 |
source = (dns.inet.any_for_af(af), 0) |
| 236 |
transport, protocol = await loop.create_datagram_endpoint( |
| 237 |
_DatagramProtocol, # pyright: ignore |
| 238 |
source, |
| 239 |
family=af, |
| 240 |
proto=proto, |
| 241 |
remote_addr=destination, |
| 242 |
) |
| 243 |
return DatagramSocket(af, transport, protocol) |
| 244 |
elif socktype == socket.SOCK_STREAM: |
| 245 |
if destination is None: |
| 246 |
# This shouldn't happen, but we check to make code analysis software |
| 247 |
# happier. |
| 248 |
raise ValueError("destination required for stream sockets") |
| 249 |
(r, w) = await _maybe_wait_for( |
| 250 |
asyncio.open_connection( |
| 251 |
destination[0], |
| 252 |
destination[1], |
| 253 |
ssl=ssl_context, |
| 254 |
family=af, |
| 255 |
proto=proto, |
| 256 |
local_addr=source, |
| 257 |
server_hostname=server_hostname, |
| 258 |
), |
| 259 |
timeout, |
| 260 |
) |
| 261 |
return StreamSocket(af, r, w) |
| 262 |
raise NotImplementedError( |
| 263 |
"unsupported socket " + f"type {socktype}" |
| 264 |
) # pragma: no cover |
| 265 |
|
| 266 |
async def sleep(self, interval): |
| 267 |
await asyncio.sleep(interval) |
| 268 |
|
| 269 |
def datagram_connection_required(self): |
| 270 |
return False |
| 271 |
|
| 272 |
def get_transport_class(self): |
| 273 |
return _HTTPTransport |
| 274 |
|
| 275 |
async def wait_for(self, awaitable, timeout): |
| 276 |
return await _maybe_wait_for(awaitable, timeout) |