| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import socket |
| 5 |
import ssl |
| 6 |
import struct |
| 7 |
import time |
| 8 |
|
| 9 |
import aioquic.h3.connection # type: ignore |
| 10 |
import aioquic.h3.events # type: ignore |
| 11 |
import aioquic.quic.configuration # type: ignore |
| 12 |
import aioquic.quic.connection # type: ignore |
| 13 |
import aioquic.quic.events # type: ignore |
| 14 |
|
| 15 |
import dns.asyncbackend |
| 16 |
import dns.exception |
| 17 |
import dns.inet |
| 18 |
from dns.quic._common import ( |
| 19 |
QUIC_MAX_DATAGRAM, |
| 20 |
AsyncQuicConnection, |
| 21 |
AsyncQuicManager, |
| 22 |
BaseQuicStream, |
| 23 |
UnexpectedEOF, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
class AsyncioQuicStream(BaseQuicStream): |
| 28 |
def __init__(self, connection, stream_id): |
| 29 |
super().__init__(connection, stream_id) |
| 30 |
self._wake_up = asyncio.Condition() |
| 31 |
|
| 32 |
async def _wait_for_wake_up(self): |
| 33 |
async with self._wake_up: |
| 34 |
await self._wake_up.wait() |
| 35 |
|
| 36 |
async def wait_for(self, amount, expiration): |
| 37 |
while True: |
| 38 |
timeout = self._timeout_from_expiration(expiration) |
| 39 |
if self._buffer.have(amount): |
| 40 |
return |
| 41 |
self._expecting = amount |
| 42 |
try: |
| 43 |
await asyncio.wait_for(self._wait_for_wake_up(), timeout) |
| 44 |
except TimeoutError: |
| 45 |
raise dns.exception.Timeout |
| 46 |
self._expecting = 0 |
| 47 |
|
| 48 |
async def wait_for_end(self, expiration): |
| 49 |
while True: |
| 50 |
timeout = self._timeout_from_expiration(expiration) |
| 51 |
if self._buffer.seen_end(): |
| 52 |
return |
| 53 |
try: |
| 54 |
await asyncio.wait_for(self._wait_for_wake_up(), timeout) |
| 55 |
except TimeoutError: |
| 56 |
raise dns.exception.Timeout |
| 57 |
|
| 58 |
async def receive(self, timeout=None): |
| 59 |
expiration = self._expiration_from_timeout(timeout) |
| 60 |
if self._connection.is_h3(): |
| 61 |
await self.wait_for_end(expiration) |
| 62 |
return self._buffer.get_all() |
| 63 |
else: |
| 64 |
await self.wait_for(2, expiration) |
| 65 |
(size,) = struct.unpack("!H", self._buffer.get(2)) |
| 66 |
await self.wait_for(size, expiration) |
| 67 |
return self._buffer.get(size) |
| 68 |
|
| 69 |
async def send(self, datagram, is_end=False): |
| 70 |
data = self._encapsulate(datagram) |
| 71 |
await self._connection.write(self._stream_id, data, is_end) |
| 72 |
|
| 73 |
async def _add_input(self, data, is_end): |
| 74 |
if self._common_add_input(data, is_end): |
| 75 |
async with self._wake_up: |
| 76 |
self._wake_up.notify() |
| 77 |
|
| 78 |
async def close(self): |
| 79 |
self._close() |
| 80 |
|
| 81 |
# Streams are async context managers |
| 82 |
|
| 83 |
async def __aenter__(self): |
| 84 |
return self |
| 85 |
|
| 86 |
async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 87 |
await self.close() |
| 88 |
async with self._wake_up: |
| 89 |
self._wake_up.notify() |
| 90 |
return False |
| 91 |
|
| 92 |
|
| 93 |
class AsyncioQuicConnection(AsyncQuicConnection): |
| 94 |
def __init__(self, connection, address, port, source, source_port, manager=None): |
| 95 |
super().__init__(connection, address, port, source, source_port, manager) |
| 96 |
self._socket = None |
| 97 |
self._handshake_complete = asyncio.Event() |
| 98 |
self._socket_created = asyncio.Event() |
| 99 |
self._wake_timer = asyncio.Condition() |
| 100 |
self._receiver_task = None |
| 101 |
self._sender_task = None |
| 102 |
self._wake_pending = False |
| 103 |
|
| 104 |
async def _receiver(self): |
| 105 |
try: |
| 106 |
af = dns.inet.af_for_address(self._address) |
| 107 |
backend = dns.asyncbackend.get_backend("asyncio") |
| 108 |
# Note that peer is a low-level address tuple, but make_socket() wants |
| 109 |
# a high-level address tuple, so we convert. |
| 110 |
self._socket = await backend.make_socket( |
| 111 |
af, socket.SOCK_DGRAM, 0, self._source, (self._peer[0], self._peer[1]) |
| 112 |
) |
| 113 |
self._socket_created.set() |
| 114 |
async with self._socket: |
| 115 |
while not self._done: |
| 116 |
(datagram, address) = await self._socket.recvfrom( |
| 117 |
QUIC_MAX_DATAGRAM, None |
| 118 |
) |
| 119 |
if address[0] != self._peer[0] or address[1] != self._peer[1]: |
| 120 |
continue |
| 121 |
self._connection.receive_datagram(datagram, address, time.time()) |
| 122 |
# Wake up the timer in case the sender is sleeping, as there may be |
| 123 |
# stuff to send now. |
| 124 |
await self._wakeup() |
| 125 |
except Exception: |
| 126 |
pass |
| 127 |
finally: |
| 128 |
self._done = True |
| 129 |
await self._wakeup() |
| 130 |
self._handshake_complete.set() |
| 131 |
|
| 132 |
async def _wakeup(self): |
| 133 |
self._wake_pending = True |
| 134 |
async with self._wake_timer: |
| 135 |
self._wake_timer.notify_all() |
| 136 |
|
| 137 |
async def _wait_for_wake_timer(self): |
| 138 |
async with self._wake_timer: |
| 139 |
if not self._wake_pending: |
| 140 |
await self._wake_timer.wait() |
| 141 |
self._wake_pending = False |
| 142 |
|
| 143 |
async def _sender(self): |
| 144 |
await self._socket_created.wait() |
| 145 |
while not self._done: |
| 146 |
datagrams = self._connection.datagrams_to_send(time.time()) |
| 147 |
for datagram, address in datagrams: |
| 148 |
assert address == self._peer |
| 149 |
assert self._socket is not None |
| 150 |
await self._socket.sendto(datagram, self._peer, None) |
| 151 |
(expiration, interval) = self._get_timer_values() |
| 152 |
try: |
| 153 |
await asyncio.wait_for(self._wait_for_wake_timer(), interval) |
| 154 |
except Exception: |
| 155 |
pass |
| 156 |
self._handle_timer(expiration) |
| 157 |
await self._handle_events() |
| 158 |
|
| 159 |
async def _handle_events(self): |
| 160 |
count = 0 |
| 161 |
while True: |
| 162 |
event = self._connection.next_event() |
| 163 |
if event is None: |
| 164 |
return |
| 165 |
if isinstance(event, aioquic.quic.events.StreamDataReceived): |
| 166 |
if self.is_h3(): |
| 167 |
assert self._h3_conn is not None |
| 168 |
h3_events = self._h3_conn.handle_event(event) |
| 169 |
for h3_event in h3_events: |
| 170 |
if isinstance(h3_event, aioquic.h3.events.HeadersReceived): |
| 171 |
stream = self._streams.get(event.stream_id) |
| 172 |
if stream: |
| 173 |
if stream._headers is None: |
| 174 |
stream._headers = h3_event.headers |
| 175 |
elif stream._trailers is None: |
| 176 |
stream._trailers = h3_event.headers |
| 177 |
if h3_event.stream_ended: |
| 178 |
await stream._add_input(b"", True) |
| 179 |
elif isinstance(h3_event, aioquic.h3.events.DataReceived): |
| 180 |
stream = self._streams.get(event.stream_id) |
| 181 |
if stream: |
| 182 |
await stream._add_input( |
| 183 |
h3_event.data, h3_event.stream_ended |
| 184 |
) |
| 185 |
else: |
| 186 |
stream = self._streams.get(event.stream_id) |
| 187 |
if stream: |
| 188 |
await stream._add_input(event.data, event.end_stream) |
| 189 |
elif isinstance(event, aioquic.quic.events.HandshakeCompleted): |
| 190 |
self._handshake_complete.set() |
| 191 |
elif isinstance(event, aioquic.quic.events.ConnectionTerminated): |
| 192 |
self._done = True |
| 193 |
if self._receiver_task is not None: |
| 194 |
self._receiver_task.cancel() |
| 195 |
elif isinstance(event, aioquic.quic.events.StreamReset): |
| 196 |
stream = self._streams.get(event.stream_id) |
| 197 |
if stream: |
| 198 |
await stream._add_input(b"", True) |
| 199 |
|
| 200 |
count += 1 |
| 201 |
if count > 10: |
| 202 |
# yield |
| 203 |
count = 0 |
| 204 |
await asyncio.sleep(0) |
| 205 |
|
| 206 |
async def write(self, stream, data, is_end=False): |
| 207 |
self._connection.send_stream_data(stream, data, is_end) |
| 208 |
await self._wakeup() |
| 209 |
|
| 210 |
def run(self): |
| 211 |
if self._closed: |
| 212 |
return |
| 213 |
self._receiver_task = asyncio.Task(self._receiver()) |
| 214 |
self._sender_task = asyncio.Task(self._sender()) |
| 215 |
|
| 216 |
async def make_stream(self, timeout=None): |
| 217 |
try: |
| 218 |
await asyncio.wait_for(self._handshake_complete.wait(), timeout) |
| 219 |
except TimeoutError: |
| 220 |
raise dns.exception.Timeout |
| 221 |
if self._done: |
| 222 |
raise UnexpectedEOF |
| 223 |
stream_id = self._connection.get_next_available_stream_id(False) |
| 224 |
stream = AsyncioQuicStream(self, stream_id) |
| 225 |
self._streams[stream_id] = stream |
| 226 |
return stream |
| 227 |
|
| 228 |
async def close(self): |
| 229 |
if not self._closed: |
| 230 |
if self._manager is not None: |
| 231 |
self._manager.closed(self._peer[0], self._peer[1]) |
| 232 |
self._closed = True |
| 233 |
self._connection.close() |
| 234 |
# sender might be blocked on this, so set it |
| 235 |
self._socket_created.set() |
| 236 |
await self._wakeup() |
| 237 |
try: |
| 238 |
if self._receiver_task is not None: |
| 239 |
await self._receiver_task |
| 240 |
except asyncio.CancelledError: |
| 241 |
pass |
| 242 |
try: |
| 243 |
if self._sender_task is not None: |
| 244 |
await self._sender_task |
| 245 |
except asyncio.CancelledError: |
| 246 |
pass |
| 247 |
if self._socket is not None: |
| 248 |
await self._socket.close() |
| 249 |
|
| 250 |
|
| 251 |
class AsyncioQuicManager(AsyncQuicManager): |
| 252 |
def __init__( |
| 253 |
self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False |
| 254 |
): |
| 255 |
super().__init__(conf, verify_mode, AsyncioQuicConnection, server_name, h3) |
| 256 |
|
| 257 |
def connect( |
| 258 |
self, address, port=853, source=None, source_port=0, want_session_ticket=True |
| 259 |
): |
| 260 |
(connection, start) = self._connect( |
| 261 |
address, port, source, source_port, want_session_ticket |
| 262 |
) |
| 263 |
if start: |
| 264 |
connection.run() |
| 265 |
return connection |
| 266 |
|
| 267 |
async def __aenter__(self): |
| 268 |
return self |
| 269 |
|
| 270 |
async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 271 |
# Copy the iterator into a list as exiting things will mutate the connections |
| 272 |
# table. |
| 273 |
connections = list(self._connections.values()) |
| 274 |
for connection in connections: |
| 275 |
await connection.close() |
| 276 |
return False |