| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
"""trio async I/O library query support""" |
| 4 |
|
| 5 |
import socket |
| 6 |
|
| 7 |
import trio |
| 8 |
import trio.socket # type: ignore |
| 9 |
|
| 10 |
import dns._asyncbackend |
| 11 |
import dns._features |
| 12 |
import dns.exception |
| 13 |
import dns.inet |
| 14 |
|
| 15 |
if not dns._features.have("trio"): |
| 16 |
raise ImportError("trio not found or too old") |
| 17 |
|
| 18 |
|
| 19 |
def _maybe_timeout(timeout): |
| 20 |
if timeout is not None: |
| 21 |
return trio.move_on_after(timeout) |
| 22 |
else: |
| 23 |
return dns._asyncbackend.NullContext() |
| 24 |
|
| 25 |
|
| 26 |
# for brevity |
| 27 |
_lltuple = dns.inet.low_level_address_tuple |
| 28 |
|
| 29 |
# pylint: disable=redefined-outer-name |
| 30 |
|
| 31 |
|
| 32 |
class DatagramSocket(dns._asyncbackend.DatagramSocket): |
| 33 |
def __init__(self, sock): |
| 34 |
super().__init__(sock.family, socket.SOCK_DGRAM) |
| 35 |
self.socket = sock |
| 36 |
|
| 37 |
async def sendto(self, what, destination, timeout): |
| 38 |
with _maybe_timeout(timeout): |
| 39 |
if destination is None: |
| 40 |
return await self.socket.send(what) |
| 41 |
else: |
| 42 |
return await self.socket.sendto(what, destination) |
| 43 |
raise dns.exception.Timeout( |
| 44 |
timeout=timeout |
| 45 |
) # pragma: no cover lgtm[py/unreachable-statement] |
| 46 |
|
| 47 |
async def recvfrom(self, size, timeout): |
| 48 |
with _maybe_timeout(timeout): |
| 49 |
return await self.socket.recvfrom(size) |
| 50 |
raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] |
| 51 |
|
| 52 |
async def close(self): |
| 53 |
self.socket.close() |
| 54 |
|
| 55 |
async def getpeername(self): |
| 56 |
return self.socket.getpeername() |
| 57 |
|
| 58 |
async def getsockname(self): |
| 59 |
return self.socket.getsockname() |
| 60 |
|
| 61 |
async def getpeercert(self, timeout): |
| 62 |
raise NotImplementedError |
| 63 |
|
| 64 |
|
| 65 |
class StreamSocket(dns._asyncbackend.StreamSocket): |
| 66 |
def __init__(self, family, stream, tls=False): |
| 67 |
super().__init__(family, socket.SOCK_STREAM) |
| 68 |
self.stream = stream |
| 69 |
self.tls = tls |
| 70 |
|
| 71 |
async def sendall(self, what, timeout): |
| 72 |
with _maybe_timeout(timeout): |
| 73 |
return await self.stream.send_all(what) |
| 74 |
raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] |
| 75 |
|
| 76 |
async def recv(self, size, timeout): |
| 77 |
with _maybe_timeout(timeout): |
| 78 |
return await self.stream.receive_some(size) |
| 79 |
raise dns.exception.Timeout(timeout=timeout) # lgtm[py/unreachable-statement] |
| 80 |
|
| 81 |
async def close(self): |
| 82 |
await self.stream.aclose() |
| 83 |
|
| 84 |
async def getpeername(self): |
| 85 |
if self.tls: |
| 86 |
return self.stream.transport_stream.socket.getpeername() |
| 87 |
else: |
| 88 |
return self.stream.socket.getpeername() |
| 89 |
|
| 90 |
async def getsockname(self): |
| 91 |
if self.tls: |
| 92 |
return self.stream.transport_stream.socket.getsockname() |
| 93 |
else: |
| 94 |
return self.stream.socket.getsockname() |
| 95 |
|
| 96 |
async def getpeercert(self, timeout): |
| 97 |
if self.tls: |
| 98 |
with _maybe_timeout(timeout): |
| 99 |
await self.stream.do_handshake() |
| 100 |
return self.stream.getpeercert() |
| 101 |
else: |
| 102 |
raise NotImplementedError |
| 103 |
|
| 104 |
|
| 105 |
if dns._features.have("doh"): |
| 106 |
import httpcore |
| 107 |
import httpcore._backends.trio |
| 108 |
import httpx |
| 109 |
|
| 110 |
_CoreAsyncNetworkBackend = httpcore.AsyncNetworkBackend |
| 111 |
_CoreTrioStream = httpcore._backends.trio.TrioStream |
| 112 |
|
| 113 |
from dns.query import _compute_times, _expiration_for_this_attempt, _remaining |
| 114 |
|
| 115 |
class _NetworkBackend(_CoreAsyncNetworkBackend): |
| 116 |
def __init__(self, resolver, local_port, bootstrap_address, family): |
| 117 |
super().__init__() |
| 118 |
self._local_port = local_port |
| 119 |
self._resolver = resolver |
| 120 |
self._bootstrap_address = bootstrap_address |
| 121 |
self._family = family |
| 122 |
|
| 123 |
async def connect_tcp( |
| 124 |
self, host, port, timeout=None, local_address=None, socket_options=None |
| 125 |
): # pylint: disable=signature-differs |
| 126 |
addresses = [] |
| 127 |
_, expiration = _compute_times(timeout) |
| 128 |
if dns.inet.is_address(host): |
| 129 |
addresses.append(host) |
| 130 |
elif self._bootstrap_address is not None: |
| 131 |
addresses.append(self._bootstrap_address) |
| 132 |
else: |
| 133 |
timeout = _remaining(expiration) |
| 134 |
family = self._family |
| 135 |
if local_address: |
| 136 |
family = dns.inet.af_for_address(local_address) |
| 137 |
answers = await self._resolver.resolve_name( |
| 138 |
host, family=family, lifetime=timeout |
| 139 |
) |
| 140 |
addresses = answers.addresses() |
| 141 |
for address in addresses: |
| 142 |
try: |
| 143 |
af = dns.inet.af_for_address(address) |
| 144 |
if local_address is not None or self._local_port != 0: |
| 145 |
source = (local_address, self._local_port) |
| 146 |
else: |
| 147 |
source = None |
| 148 |
destination = (address, port) |
| 149 |
attempt_expiration = _expiration_for_this_attempt(2.0, expiration) |
| 150 |
timeout = _remaining(attempt_expiration) |
| 151 |
sock = await Backend().make_socket( |
| 152 |
af, socket.SOCK_STREAM, 0, source, destination, timeout |
| 153 |
) |
| 154 |
assert isinstance(sock, StreamSocket) |
| 155 |
return _CoreTrioStream(sock.stream) |
| 156 |
except Exception: |
| 157 |
continue |
| 158 |
raise httpcore.ConnectError |
| 159 |
|
| 160 |
async def connect_unix_socket( |
| 161 |
self, path, timeout=None, socket_options=None |
| 162 |
): # pylint: disable=signature-differs |
| 163 |
raise NotImplementedError |
| 164 |
|
| 165 |
async def sleep(self, seconds): # pylint: disable=signature-differs |
| 166 |
await trio.sleep(seconds) |
| 167 |
|
| 168 |
class _HTTPTransport(httpx.AsyncHTTPTransport): |
| 169 |
def __init__( |
| 170 |
self, |
| 171 |
*args, |
| 172 |
local_port=0, |
| 173 |
bootstrap_address=None, |
| 174 |
resolver=None, |
| 175 |
family=socket.AF_UNSPEC, |
| 176 |
**kwargs, |
| 177 |
): |
| 178 |
if resolver is None and bootstrap_address is None: |
| 179 |
# pylint: disable=import-outside-toplevel,redefined-outer-name |
| 180 |
import dns.asyncresolver |
| 181 |
|
| 182 |
resolver = dns.asyncresolver.Resolver() |
| 183 |
super().__init__(*args, **kwargs) |
| 184 |
self._pool._network_backend = _NetworkBackend( |
| 185 |
resolver, local_port, bootstrap_address, family |
| 186 |
) |
| 187 |
|
| 188 |
else: |
| 189 |
_HTTPTransport = dns._asyncbackend.NullTransport # type: ignore |
| 190 |
|
| 191 |
|
| 192 |
class Backend(dns._asyncbackend.Backend): |
| 193 |
def name(self): |
| 194 |
return "trio" |
| 195 |
|
| 196 |
async def make_socket( |
| 197 |
self, |
| 198 |
af, |
| 199 |
socktype, |
| 200 |
proto=0, |
| 201 |
source=None, |
| 202 |
destination=None, |
| 203 |
timeout=None, |
| 204 |
ssl_context=None, |
| 205 |
server_hostname=None, |
| 206 |
): |
| 207 |
s = trio.socket.socket(af, socktype, proto) |
| 208 |
stream = None |
| 209 |
try: |
| 210 |
if source: |
| 211 |
await s.bind(_lltuple(source, af)) |
| 212 |
if socktype == socket.SOCK_STREAM or destination is not None: |
| 213 |
connected = False |
| 214 |
with _maybe_timeout(timeout): |
| 215 |
assert destination is not None |
| 216 |
await s.connect(_lltuple(destination, af)) |
| 217 |
connected = True |
| 218 |
if not connected: |
| 219 |
raise dns.exception.Timeout( |
| 220 |
timeout=timeout |
| 221 |
) # lgtm[py/unreachable-statement] |
| 222 |
except Exception: # pragma: no cover |
| 223 |
s.close() |
| 224 |
raise |
| 225 |
if socktype == socket.SOCK_DGRAM: |
| 226 |
return DatagramSocket(s) |
| 227 |
elif socktype == socket.SOCK_STREAM: |
| 228 |
stream = trio.SocketStream(s) |
| 229 |
tls = False |
| 230 |
if ssl_context: |
| 231 |
tls = True |
| 232 |
try: |
| 233 |
stream = trio.SSLStream( |
| 234 |
stream, ssl_context, server_hostname=server_hostname |
| 235 |
) |
| 236 |
except Exception: # pragma: no cover |
| 237 |
await stream.aclose() |
| 238 |
raise |
| 239 |
return StreamSocket(af, stream, tls) |
| 240 |
raise NotImplementedError( |
| 241 |
"unsupported socket " + f"type {socktype}" |
| 242 |
) # pragma: no cover |
| 243 |
|
| 244 |
async def sleep(self, interval): |
| 245 |
await trio.sleep(interval) |
| 246 |
|
| 247 |
def get_transport_class(self): |
| 248 |
return _HTTPTransport |
| 249 |
|
| 250 |
async def wait_for(self, awaitable, timeout): |
| 251 |
with _maybe_timeout(timeout): |
| 252 |
return await awaitable |
| 253 |
raise dns.exception.Timeout( |
| 254 |
timeout=timeout |
| 255 |
) # pragma: no cover lgtm[py/unreachable-statement] |