| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
import selectors |
| 4 |
import socket |
| 5 |
import ssl |
| 6 |
import struct |
| 7 |
import threading |
| 8 |
import time |
| 9 |
|
| 10 |
import aioquic.h3.connection # type: ignore |
| 11 |
import aioquic.h3.events # type: ignore |
| 12 |
import aioquic.quic.configuration # type: ignore |
| 13 |
import aioquic.quic.connection # type: ignore |
| 14 |
import aioquic.quic.events # type: ignore |
| 15 |
|
| 16 |
import dns.exception |
| 17 |
import dns.inet |
| 18 |
from dns.quic._common import ( |
| 19 |
QUIC_MAX_DATAGRAM, |
| 20 |
BaseQuicConnection, |
| 21 |
BaseQuicManager, |
| 22 |
BaseQuicStream, |
| 23 |
UnexpectedEOF, |
| 24 |
) |
| 25 |
|
| 26 |
# Function used to create a socket. Can be overridden if needed in special |
| 27 |
# situations. |
| 28 |
socket_factory = socket.socket |
| 29 |
|
| 30 |
|
| 31 |
class SyncQuicStream(BaseQuicStream): |
| 32 |
def __init__(self, connection, stream_id): |
| 33 |
super().__init__(connection, stream_id) |
| 34 |
self._wake_up = threading.Condition() |
| 35 |
self._lock = threading.Lock() |
| 36 |
|
| 37 |
def wait_for(self, amount, expiration): |
| 38 |
while True: |
| 39 |
timeout = self._timeout_from_expiration(expiration) |
| 40 |
with self._lock: |
| 41 |
if self._buffer.have(amount): |
| 42 |
return |
| 43 |
self._expecting = amount |
| 44 |
with self._wake_up: |
| 45 |
if not self._wake_up.wait(timeout): |
| 46 |
raise dns.exception.Timeout |
| 47 |
self._expecting = 0 |
| 48 |
|
| 49 |
def wait_for_end(self, expiration): |
| 50 |
while True: |
| 51 |
timeout = self._timeout_from_expiration(expiration) |
| 52 |
with self._lock: |
| 53 |
if self._buffer.seen_end(): |
| 54 |
return |
| 55 |
with self._wake_up: |
| 56 |
if not self._wake_up.wait(timeout): |
| 57 |
raise dns.exception.Timeout |
| 58 |
|
| 59 |
def receive(self, timeout=None): |
| 60 |
expiration = self._expiration_from_timeout(timeout) |
| 61 |
if self._connection.is_h3(): |
| 62 |
self.wait_for_end(expiration) |
| 63 |
with self._lock: |
| 64 |
return self._buffer.get_all() |
| 65 |
else: |
| 66 |
self.wait_for(2, expiration) |
| 67 |
with self._lock: |
| 68 |
(size,) = struct.unpack("!H", self._buffer.get(2)) |
| 69 |
self.wait_for(size, expiration) |
| 70 |
with self._lock: |
| 71 |
return self._buffer.get(size) |
| 72 |
|
| 73 |
def send(self, datagram, is_end=False): |
| 74 |
data = self._encapsulate(datagram) |
| 75 |
self._connection.write(self._stream_id, data, is_end) |
| 76 |
|
| 77 |
def _add_input(self, data, is_end): |
| 78 |
if self._common_add_input(data, is_end): |
| 79 |
with self._wake_up: |
| 80 |
self._wake_up.notify() |
| 81 |
|
| 82 |
def close(self): |
| 83 |
with self._lock: |
| 84 |
self._close() |
| 85 |
|
| 86 |
def __enter__(self): |
| 87 |
return self |
| 88 |
|
| 89 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 90 |
self.close() |
| 91 |
with self._wake_up: |
| 92 |
self._wake_up.notify() |
| 93 |
return False |
| 94 |
|
| 95 |
|
| 96 |
class SyncQuicConnection(BaseQuicConnection): |
| 97 |
def __init__(self, connection, address, port, source, source_port, manager): |
| 98 |
super().__init__(connection, address, port, source, source_port, manager) |
| 99 |
self._socket = socket_factory(self._af, socket.SOCK_DGRAM, 0) |
| 100 |
if self._source is not None: |
| 101 |
try: |
| 102 |
self._socket.bind( |
| 103 |
dns.inet.low_level_address_tuple(self._source, self._af) |
| 104 |
) |
| 105 |
except Exception: |
| 106 |
self._socket.close() |
| 107 |
raise |
| 108 |
self._socket.connect(self._peer) |
| 109 |
(self._send_wakeup, self._receive_wakeup) = socket.socketpair() |
| 110 |
self._receive_wakeup.setblocking(False) |
| 111 |
self._socket.setblocking(False) |
| 112 |
self._handshake_complete = threading.Event() |
| 113 |
self._worker_thread = None |
| 114 |
self._lock = threading.Lock() |
| 115 |
|
| 116 |
def _read(self): |
| 117 |
count = 0 |
| 118 |
while count < 10: |
| 119 |
count += 1 |
| 120 |
try: |
| 121 |
datagram = self._socket.recv(QUIC_MAX_DATAGRAM) |
| 122 |
except BlockingIOError: |
| 123 |
return |
| 124 |
with self._lock: |
| 125 |
self._connection.receive_datagram(datagram, self._peer, time.time()) |
| 126 |
|
| 127 |
def _drain_wakeup(self): |
| 128 |
while True: |
| 129 |
try: |
| 130 |
self._receive_wakeup.recv(32) |
| 131 |
except BlockingIOError: |
| 132 |
return |
| 133 |
|
| 134 |
def _worker(self): |
| 135 |
try: |
| 136 |
with selectors.DefaultSelector() as sel: |
| 137 |
sel.register(self._socket, selectors.EVENT_READ, self._read) |
| 138 |
sel.register( |
| 139 |
self._receive_wakeup, selectors.EVENT_READ, self._drain_wakeup |
| 140 |
) |
| 141 |
while not self._done: |
| 142 |
(expiration, interval) = self._get_timer_values(False) |
| 143 |
items = sel.select(interval) |
| 144 |
for key, _ in items: |
| 145 |
key.data() |
| 146 |
with self._lock: |
| 147 |
self._handle_timer(expiration) |
| 148 |
self._handle_events() |
| 149 |
with self._lock: |
| 150 |
datagrams = self._connection.datagrams_to_send(time.time()) |
| 151 |
for datagram, _ in datagrams: |
| 152 |
try: |
| 153 |
self._socket.send(datagram) |
| 154 |
except BlockingIOError: |
| 155 |
# we let QUIC handle any lossage |
| 156 |
pass |
| 157 |
except Exception: |
| 158 |
# Eat all exceptions as we have no way to pass them back to the |
| 159 |
# caller currently. It might be nice to fix this in the future. |
| 160 |
pass |
| 161 |
finally: |
| 162 |
with self._lock: |
| 163 |
self._done = True |
| 164 |
self._socket.close() |
| 165 |
# Ensure anyone waiting for this gets woken up. |
| 166 |
self._handshake_complete.set() |
| 167 |
|
| 168 |
def _handle_events(self): |
| 169 |
while True: |
| 170 |
with self._lock: |
| 171 |
event = self._connection.next_event() |
| 172 |
if event is None: |
| 173 |
return |
| 174 |
if isinstance(event, aioquic.quic.events.StreamDataReceived): |
| 175 |
if self.is_h3(): |
| 176 |
assert self._h3_conn is not None |
| 177 |
h3_events = self._h3_conn.handle_event(event) |
| 178 |
for h3_event in h3_events: |
| 179 |
if isinstance(h3_event, aioquic.h3.events.HeadersReceived): |
| 180 |
with self._lock: |
| 181 |
stream = self._streams.get(event.stream_id) |
| 182 |
if stream: |
| 183 |
if stream._headers is None: |
| 184 |
stream._headers = h3_event.headers |
| 185 |
elif stream._trailers is None: |
| 186 |
stream._trailers = h3_event.headers |
| 187 |
if h3_event.stream_ended: |
| 188 |
stream._add_input(b"", True) |
| 189 |
elif isinstance(h3_event, aioquic.h3.events.DataReceived): |
| 190 |
with self._lock: |
| 191 |
stream = self._streams.get(event.stream_id) |
| 192 |
if stream: |
| 193 |
stream._add_input(h3_event.data, h3_event.stream_ended) |
| 194 |
else: |
| 195 |
with self._lock: |
| 196 |
stream = self._streams.get(event.stream_id) |
| 197 |
if stream: |
| 198 |
stream._add_input(event.data, event.end_stream) |
| 199 |
elif isinstance(event, aioquic.quic.events.HandshakeCompleted): |
| 200 |
self._handshake_complete.set() |
| 201 |
elif isinstance(event, aioquic.quic.events.ConnectionTerminated): |
| 202 |
with self._lock: |
| 203 |
self._done = True |
| 204 |
elif isinstance(event, aioquic.quic.events.StreamReset): |
| 205 |
with self._lock: |
| 206 |
stream = self._streams.get(event.stream_id) |
| 207 |
if stream: |
| 208 |
stream._add_input(b"", True) |
| 209 |
|
| 210 |
def write(self, stream, data, is_end=False): |
| 211 |
with self._lock: |
| 212 |
self._connection.send_stream_data(stream, data, is_end) |
| 213 |
self._send_wakeup.send(b"\x01") |
| 214 |
|
| 215 |
def send_headers(self, stream_id, headers, is_end=False): |
| 216 |
with self._lock: |
| 217 |
super().send_headers(stream_id, headers, is_end) |
| 218 |
if is_end: |
| 219 |
self._send_wakeup.send(b"\x01") |
| 220 |
|
| 221 |
def send_data(self, stream_id, data, is_end=False): |
| 222 |
with self._lock: |
| 223 |
super().send_data(stream_id, data, is_end) |
| 224 |
if is_end: |
| 225 |
self._send_wakeup.send(b"\x01") |
| 226 |
|
| 227 |
def run(self): |
| 228 |
if self._closed: |
| 229 |
return |
| 230 |
self._worker_thread = threading.Thread(target=self._worker) |
| 231 |
self._worker_thread.start() |
| 232 |
|
| 233 |
def make_stream(self, timeout=None): |
| 234 |
if not self._handshake_complete.wait(timeout): |
| 235 |
raise dns.exception.Timeout |
| 236 |
with self._lock: |
| 237 |
if self._done: |
| 238 |
raise UnexpectedEOF |
| 239 |
stream_id = self._connection.get_next_available_stream_id(False) |
| 240 |
stream = SyncQuicStream(self, stream_id) |
| 241 |
self._streams[stream_id] = stream |
| 242 |
return stream |
| 243 |
|
| 244 |
def close_stream(self, stream_id): |
| 245 |
with self._lock: |
| 246 |
super().close_stream(stream_id) |
| 247 |
|
| 248 |
def close(self): |
| 249 |
with self._lock: |
| 250 |
if self._closed: |
| 251 |
return |
| 252 |
if self._manager is not None: |
| 253 |
self._manager.closed(self._peer[0], self._peer[1]) |
| 254 |
self._closed = True |
| 255 |
self._connection.close() |
| 256 |
self._send_wakeup.send(b"\x01") |
| 257 |
if self._worker_thread is not None: |
| 258 |
self._worker_thread.join() |
| 259 |
|
| 260 |
|
| 261 |
class SyncQuicManager(BaseQuicManager): |
| 262 |
def __init__( |
| 263 |
self, conf=None, verify_mode=ssl.CERT_REQUIRED, server_name=None, h3=False |
| 264 |
): |
| 265 |
super().__init__(conf, verify_mode, SyncQuicConnection, server_name, h3) |
| 266 |
self._lock = threading.Lock() |
| 267 |
|
| 268 |
def connect( |
| 269 |
self, |
| 270 |
address, |
| 271 |
port=853, |
| 272 |
source=None, |
| 273 |
source_port=0, |
| 274 |
want_session_ticket=True, |
| 275 |
want_token=True, |
| 276 |
): |
| 277 |
with self._lock: |
| 278 |
(connection, start) = self._connect( |
| 279 |
address, port, source, source_port, want_session_ticket, want_token |
| 280 |
) |
| 281 |
if start: |
| 282 |
connection.run() |
| 283 |
return connection |
| 284 |
|
| 285 |
def closed(self, address, port): |
| 286 |
with self._lock: |
| 287 |
super().closed(address, port) |
| 288 |
|
| 289 |
def save_session_ticket(self, address, port, ticket): |
| 290 |
with self._lock: |
| 291 |
super().save_session_ticket(address, port, ticket) |
| 292 |
|
| 293 |
def save_token(self, address, port, token): |
| 294 |
with self._lock: |
| 295 |
super().save_token(address, port, token) |
| 296 |
|
| 297 |
def __enter__(self): |
| 298 |
return self |
| 299 |
|
| 300 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 301 |
# Copy the iterator into a list as exiting things will mutate the connections |
| 302 |
# table. |
| 303 |
connections = list(self._connections.values()) |
| 304 |
for connection in connections: |
| 305 |
connection.close() |
| 306 |
return False |