| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
import base64 |
| 4 |
import copy |
| 5 |
import functools |
| 6 |
import socket |
| 7 |
import struct |
| 8 |
import time |
| 9 |
import urllib.parse |
| 10 |
from typing import Any |
| 11 |
|
| 12 |
import aioquic.h3.connection # type: ignore |
| 13 |
import aioquic.quic.configuration # type: ignore |
| 14 |
import aioquic.quic.connection # type: ignore |
| 15 |
|
| 16 |
import dns._tls_util |
| 17 |
import dns.inet |
| 18 |
|
| 19 |
QUIC_MAX_DATAGRAM = 2048 |
| 20 |
MAX_SESSION_TICKETS = 8 |
| 21 |
# If we hit the max sessions limit we will delete this many of the oldest connections. |
| 22 |
# The value must be a integer > 0 and <= MAX_SESSION_TICKETS. |
| 23 |
SESSIONS_TO_DELETE = MAX_SESSION_TICKETS // 4 |
| 24 |
|
| 25 |
|
| 26 |
class UnexpectedEOF(Exception): |
| 27 |
pass |
| 28 |
|
| 29 |
|
| 30 |
class Buffer: |
| 31 |
def __init__(self): |
| 32 |
self._buffer = b"" |
| 33 |
self._seen_end = False |
| 34 |
|
| 35 |
def put(self, data, is_end): |
| 36 |
if self._seen_end: |
| 37 |
return |
| 38 |
self._buffer += data |
| 39 |
if is_end: |
| 40 |
self._seen_end = True |
| 41 |
|
| 42 |
def have(self, amount): |
| 43 |
if len(self._buffer) >= amount: |
| 44 |
return True |
| 45 |
if self._seen_end: |
| 46 |
raise UnexpectedEOF |
| 47 |
return False |
| 48 |
|
| 49 |
def seen_end(self): |
| 50 |
return self._seen_end |
| 51 |
|
| 52 |
def get(self, amount): |
| 53 |
assert self.have(amount) |
| 54 |
data = self._buffer[:amount] |
| 55 |
self._buffer = self._buffer[amount:] |
| 56 |
return data |
| 57 |
|
| 58 |
def get_all(self): |
| 59 |
assert self.seen_end() |
| 60 |
data = self._buffer |
| 61 |
self._buffer = b"" |
| 62 |
return data |
| 63 |
|
| 64 |
|
| 65 |
class BaseQuicStream: |
| 66 |
def __init__(self, connection, stream_id): |
| 67 |
self._connection = connection |
| 68 |
self._stream_id = stream_id |
| 69 |
self._buffer = Buffer() |
| 70 |
self._expecting = 0 |
| 71 |
self._headers = None |
| 72 |
self._trailers = None |
| 73 |
|
| 74 |
def id(self): |
| 75 |
return self._stream_id |
| 76 |
|
| 77 |
def headers(self): |
| 78 |
return self._headers |
| 79 |
|
| 80 |
def trailers(self): |
| 81 |
return self._trailers |
| 82 |
|
| 83 |
def _expiration_from_timeout(self, timeout): |
| 84 |
if timeout is not None: |
| 85 |
expiration = time.time() + timeout |
| 86 |
else: |
| 87 |
expiration = None |
| 88 |
return expiration |
| 89 |
|
| 90 |
def _timeout_from_expiration(self, expiration): |
| 91 |
if expiration is not None: |
| 92 |
timeout = max(expiration - time.time(), 0.0) |
| 93 |
else: |
| 94 |
timeout = None |
| 95 |
return timeout |
| 96 |
|
| 97 |
# Subclass must implement receive() as sync / async and which returns a message |
| 98 |
# or raises. |
| 99 |
|
| 100 |
# Subclass must implement send() as sync / async and which takes a message and |
| 101 |
# an EOF indicator. |
| 102 |
|
| 103 |
def send_h3(self, url, datagram, post=True): |
| 104 |
if not self._connection.is_h3(): |
| 105 |
raise SyntaxError("cannot send H3 to a non-H3 connection") |
| 106 |
url_parts = urllib.parse.urlparse(url) |
| 107 |
path = url_parts.path.encode() |
| 108 |
if post: |
| 109 |
method = b"POST" |
| 110 |
else: |
| 111 |
method = b"GET" |
| 112 |
path += b"?dns=" + base64.urlsafe_b64encode(datagram).rstrip(b"=") |
| 113 |
headers = [ |
| 114 |
(b":method", method), |
| 115 |
(b":scheme", url_parts.scheme.encode()), |
| 116 |
(b":authority", url_parts.netloc.encode()), |
| 117 |
(b":path", path), |
| 118 |
(b"accept", b"application/dns-message"), |
| 119 |
] |
| 120 |
if post: |
| 121 |
headers.extend( |
| 122 |
[ |
| 123 |
(b"content-type", b"application/dns-message"), |
| 124 |
(b"content-length", str(len(datagram)).encode()), |
| 125 |
] |
| 126 |
) |
| 127 |
self._connection.send_headers(self._stream_id, headers, not post) |
| 128 |
if post: |
| 129 |
self._connection.send_data(self._stream_id, datagram, True) |
| 130 |
|
| 131 |
def _encapsulate(self, datagram): |
| 132 |
if self._connection.is_h3(): |
| 133 |
return datagram |
| 134 |
l = len(datagram) |
| 135 |
return struct.pack("!H", l) + datagram |
| 136 |
|
| 137 |
def _common_add_input(self, data, is_end): |
| 138 |
self._buffer.put(data, is_end) |
| 139 |
try: |
| 140 |
return ( |
| 141 |
self._expecting > 0 and self._buffer.have(self._expecting) |
| 142 |
) or self._buffer.seen_end |
| 143 |
except UnexpectedEOF: |
| 144 |
return True |
| 145 |
|
| 146 |
def _close(self): |
| 147 |
self._connection.close_stream(self._stream_id) |
| 148 |
self._buffer.put(b"", True) # send EOF in case we haven't seen it. |
| 149 |
|
| 150 |
|
| 151 |
class BaseQuicConnection: |
| 152 |
def __init__( |
| 153 |
self, |
| 154 |
connection, |
| 155 |
address, |
| 156 |
port, |
| 157 |
source=None, |
| 158 |
source_port=0, |
| 159 |
manager=None, |
| 160 |
): |
| 161 |
self._done = False |
| 162 |
self._connection = connection |
| 163 |
self._address = address |
| 164 |
self._port = port |
| 165 |
self._closed = False |
| 166 |
self._manager = manager |
| 167 |
self._streams = {} |
| 168 |
if manager is not None and manager.is_h3(): |
| 169 |
self._h3_conn = aioquic.h3.connection.H3Connection(connection, False) |
| 170 |
else: |
| 171 |
self._h3_conn = None |
| 172 |
self._af = dns.inet.af_for_address(address) |
| 173 |
self._peer = dns.inet.low_level_address_tuple((address, port)) |
| 174 |
if source is None and source_port != 0: |
| 175 |
if self._af == socket.AF_INET: |
| 176 |
source = "0.0.0.0" |
| 177 |
elif self._af == socket.AF_INET6: |
| 178 |
source = "::" |
| 179 |
else: |
| 180 |
raise NotImplementedError |
| 181 |
if source: |
| 182 |
self._source = (source, source_port) |
| 183 |
else: |
| 184 |
self._source = None |
| 185 |
|
| 186 |
def is_h3(self): |
| 187 |
return self._h3_conn is not None |
| 188 |
|
| 189 |
def close_stream(self, stream_id): |
| 190 |
del self._streams[stream_id] |
| 191 |
|
| 192 |
def send_headers(self, stream_id, headers, is_end=False): |
| 193 |
assert self._h3_conn is not None |
| 194 |
self._h3_conn.send_headers(stream_id, headers, is_end) |
| 195 |
|
| 196 |
def send_data(self, stream_id, data, is_end=False): |
| 197 |
assert self._h3_conn is not None |
| 198 |
self._h3_conn.send_data(stream_id, data, is_end) |
| 199 |
|
| 200 |
def _get_timer_values(self, closed_is_special=True): |
| 201 |
now = time.time() |
| 202 |
expiration = self._connection.get_timer() |
| 203 |
if expiration is None: |
| 204 |
expiration = now + 3600 # arbitrary "big" value |
| 205 |
interval = max(expiration - now, 0) |
| 206 |
if self._closed and closed_is_special: |
| 207 |
# lower sleep interval to avoid a race in the closing process |
| 208 |
# which can lead to higher latency closing due to sleeping when |
| 209 |
# we have events. |
| 210 |
interval = min(interval, 0.05) |
| 211 |
return (expiration, interval) |
| 212 |
|
| 213 |
def _handle_timer(self, expiration): |
| 214 |
now = time.time() |
| 215 |
if expiration <= now: |
| 216 |
self._connection.handle_timer(now) |
| 217 |
|
| 218 |
|
| 219 |
class AsyncQuicConnection(BaseQuicConnection): |
| 220 |
async def make_stream(self, timeout: float | None = None) -> Any: |
| 221 |
pass |
| 222 |
|
| 223 |
|
| 224 |
class BaseQuicManager: |
| 225 |
def __init__( |
| 226 |
self, conf, verify_mode, connection_factory, server_name=None, h3=False |
| 227 |
): |
| 228 |
self._connections = {} |
| 229 |
self._connection_factory = connection_factory |
| 230 |
self._session_tickets = {} |
| 231 |
self._tokens = {} |
| 232 |
self._h3 = h3 |
| 233 |
if conf is None: |
| 234 |
verify_path = None |
| 235 |
if isinstance(verify_mode, str): |
| 236 |
verify_path = verify_mode |
| 237 |
verify_mode = True |
| 238 |
if h3: |
| 239 |
alpn_protocols = ["h3"] |
| 240 |
else: |
| 241 |
alpn_protocols = ["doq", "doq-i03"] |
| 242 |
conf = aioquic.quic.configuration.QuicConfiguration( |
| 243 |
alpn_protocols=alpn_protocols, |
| 244 |
verify_mode=verify_mode, |
| 245 |
server_name=server_name, |
| 246 |
) |
| 247 |
if verify_path is not None: |
| 248 |
cafile, capath = dns._tls_util.convert_verify_to_cafile_and_capath( |
| 249 |
verify_path |
| 250 |
) |
| 251 |
conf.load_verify_locations(cafile=cafile, capath=capath) |
| 252 |
self._conf = conf |
| 253 |
|
| 254 |
def _connect( |
| 255 |
self, |
| 256 |
address, |
| 257 |
port=853, |
| 258 |
source=None, |
| 259 |
source_port=0, |
| 260 |
want_session_ticket=True, |
| 261 |
want_token=True, |
| 262 |
): |
| 263 |
connection = self._connections.get((address, port)) |
| 264 |
if connection is not None: |
| 265 |
return (connection, False) |
| 266 |
conf = self._conf |
| 267 |
if want_session_ticket: |
| 268 |
try: |
| 269 |
session_ticket = self._session_tickets.pop((address, port)) |
| 270 |
# We found a session ticket, so make a configuration that uses it. |
| 271 |
conf = copy.copy(conf) |
| 272 |
conf.session_ticket = session_ticket |
| 273 |
except KeyError: |
| 274 |
# No session ticket. |
| 275 |
pass |
| 276 |
# Whether or not we found a session ticket, we want a handler to save |
| 277 |
# one. |
| 278 |
session_ticket_handler = functools.partial( |
| 279 |
self.save_session_ticket, address, port |
| 280 |
) |
| 281 |
else: |
| 282 |
session_ticket_handler = None |
| 283 |
if want_token: |
| 284 |
try: |
| 285 |
token = self._tokens.pop((address, port)) |
| 286 |
# We found a token, so make a configuration that uses it. |
| 287 |
conf = copy.copy(conf) |
| 288 |
conf.token = token |
| 289 |
except KeyError: |
| 290 |
# No token |
| 291 |
pass |
| 292 |
# Whether or not we found a token, we want a handler to save # one. |
| 293 |
token_handler = functools.partial(self.save_token, address, port) |
| 294 |
else: |
| 295 |
token_handler = None |
| 296 |
|
| 297 |
qconn = aioquic.quic.connection.QuicConnection( |
| 298 |
configuration=conf, |
| 299 |
session_ticket_handler=session_ticket_handler, |
| 300 |
token_handler=token_handler, |
| 301 |
) |
| 302 |
lladdress = dns.inet.low_level_address_tuple((address, port)) |
| 303 |
qconn.connect(lladdress, time.time()) |
| 304 |
connection = self._connection_factory( |
| 305 |
qconn, address, port, source, source_port, self |
| 306 |
) |
| 307 |
self._connections[(address, port)] = connection |
| 308 |
return (connection, True) |
| 309 |
|
| 310 |
def closed(self, address, port): |
| 311 |
try: |
| 312 |
del self._connections[(address, port)] |
| 313 |
except KeyError: |
| 314 |
pass |
| 315 |
|
| 316 |
def is_h3(self): |
| 317 |
return self._h3 |
| 318 |
|
| 319 |
def save_session_ticket(self, address, port, ticket): |
| 320 |
# We rely on dictionaries keys() being in insertion order here. We |
| 321 |
# can't just popitem() as that would be LIFO which is the opposite of |
| 322 |
# what we want. |
| 323 |
l = len(self._session_tickets) |
| 324 |
if l >= MAX_SESSION_TICKETS: |
| 325 |
keys_to_delete = list(self._session_tickets.keys())[0:SESSIONS_TO_DELETE] |
| 326 |
for key in keys_to_delete: |
| 327 |
del self._session_tickets[key] |
| 328 |
self._session_tickets[(address, port)] = ticket |
| 329 |
|
| 330 |
def save_token(self, address, port, token): |
| 331 |
# We rely on dictionaries keys() being in insertion order here. We |
| 332 |
# can't just popitem() as that would be LIFO which is the opposite of |
| 333 |
# what we want. |
| 334 |
l = len(self._tokens) |
| 335 |
if l >= MAX_SESSION_TICKETS: |
| 336 |
keys_to_delete = list(self._tokens.keys())[0:SESSIONS_TO_DELETE] |
| 337 |
for key in keys_to_delete: |
| 338 |
del self._tokens[key] |
| 339 |
self._tokens[(address, port)] = token |
| 340 |
|
| 341 |
|
| 342 |
class AsyncQuicManager(BaseQuicManager): |
| 343 |
def connect(self, address, port=853, source=None, source_port=0): |
| 344 |
raise NotImplementedError |