| 1 |
import asyncio |
| 2 |
import contextlib |
| 3 |
import logging |
| 4 |
import os |
| 5 |
import ssl |
| 6 |
import sys |
| 7 |
import threading |
| 8 |
import traceback |
| 9 |
from enum import IntEnum |
| 10 |
from pathlib import Path |
| 11 |
from typing import Any, Dict, List, Optional, Tuple, cast |
| 12 |
from urllib.parse import urlparse |
| 13 |
|
| 14 |
from aioquic.buffer import Buffer |
| 15 |
from aioquic.asyncio import QuicConnectionProtocol, serve |
| 16 |
from aioquic.asyncio.client import connect |
| 17 |
from aioquic.asyncio.protocol import QuicStreamAdapter |
| 18 |
from aioquic.h3.connection import H3_ALPN, FrameType, H3Connection, ProtocolError, SettingsError |
| 19 |
from aioquic.h3.events import H3Event, HeadersReceived, WebTransportStreamDataReceived, DatagramReceived, DataReceived |
| 20 |
from aioquic.quic.configuration import QuicConfiguration |
| 21 |
from aioquic.quic.connection import logger as quic_connection_logger |
| 22 |
from aioquic.quic.connection import ( |
| 23 |
stream_is_client_initiated, |
| 24 |
stream_is_unidirectional, |
| 25 |
) |
| 26 |
from aioquic.quic.events import QuicEvent, ProtocolNegotiated, ConnectionTerminated, StreamReset |
| 27 |
from aioquic.tls import SessionTicket |
| 28 |
|
| 29 |
from tools import localpaths # noqa: F401 |
| 30 |
from wptserve import stash |
| 31 |
from .capsule import H3Capsule, H3CapsuleDecoder, CapsuleType |
| 32 |
|
| 33 |
""" |
| 34 |
A WebTransport over HTTP/3 server for testing. |
| 35 |
|
| 36 |
The server interprets the underlying protocols (WebTransport, HTTP/3 and QUIC) |
| 37 |
and passes events to a particular webtransport handler. From the standpoint of |
| 38 |
test authors, a webtransport handler is a Python script which contains some |
| 39 |
callback functions. See handler.py for available callbacks. |
| 40 |
""" |
| 41 |
|
| 42 |
SERVER_NAME = 'webtransport-h3-server' |
| 43 |
|
| 44 |
_logger: logging.Logger = logging.getLogger(__name__) |
| 45 |
_doc_root: str = "" |
| 46 |
|
| 47 |
# Set aioquic's log level to WARNING to suppress some INFO logs which are |
| 48 |
# recorded every connection close. |
| 49 |
quic_connection_logger.setLevel(logging.WARNING) |
| 50 |
|
| 51 |
|
| 52 |
class H3DatagramSetting(IntEnum): |
| 53 |
# https://datatracker.ietf.org/doc/html/draft-ietf-masque-h3-datagram-04#section-8.1 |
| 54 |
DRAFT04 = 0xffd277 |
| 55 |
# https://datatracker.ietf.org/doc/html/rfc9220#section-5-2.2.1 |
| 56 |
RFC = 0x33 |
| 57 |
|
| 58 |
|
| 59 |
class WebTransportHttp3Setting(IntEnum): |
| 60 |
# https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3-07#section-8.2 |
| 61 |
WEBTRANSPORT_MAX_SESSIONS_DRAFT07 = 0xc671706a |
| 62 |
|
| 63 |
|
| 64 |
class H3ConnectionWithDatagram(H3Connection): |
| 65 |
""" |
| 66 |
A H3Connection subclass, to make it work with the latest |
| 67 |
HTTP Datagram protocol. |
| 68 |
""" |
| 69 |
# https://datatracker.ietf.org/doc/html/rfc9220#name-iana-considerations |
| 70 |
ENABLE_CONNECT_PROTOCOL = 0x08 |
| 71 |
|
| 72 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 73 |
super().__init__(*args, **kwargs) |
| 74 |
self._datagram_setting: Optional[H3DatagramSetting] = None |
| 75 |
|
| 76 |
def _validate_settings(self, settings: Dict[int, int]) -> None: |
| 77 |
# aioquic doesn't recognize the RFC version of HTTP Datagrams yet. |
| 78 |
# Intentionally don't call `super()._validate_settings(settings)` since |
| 79 |
# it raises a SettingsError when only the RFC version is negotiated. |
| 80 |
if settings.get(H3DatagramSetting.RFC) == 1: |
| 81 |
self._datagram_setting = H3DatagramSetting.RFC |
| 82 |
elif settings.get(H3DatagramSetting.DRAFT04) == 1: |
| 83 |
self._datagram_setting = H3DatagramSetting.DRAFT04 |
| 84 |
|
| 85 |
if self._datagram_setting is None: |
| 86 |
raise SettingsError("HTTP Datagrams support required") |
| 87 |
|
| 88 |
def _get_local_settings(self) -> Dict[int, int]: |
| 89 |
settings = super()._get_local_settings() |
| 90 |
settings[H3DatagramSetting.RFC] = 1 |
| 91 |
settings[H3DatagramSetting.DRAFT04] = 1 |
| 92 |
settings[H3ConnectionWithDatagram.ENABLE_CONNECT_PROTOCOL] = 1 |
| 93 |
# This connection can handle only one WebTransport session. |
| 94 |
settings[WebTransportHttp3Setting.WEBTRANSPORT_MAX_SESSIONS_DRAFT07] = 1 |
| 95 |
return settings |
| 96 |
|
| 97 |
@property |
| 98 |
def datagram_setting(self) -> Optional[H3DatagramSetting]: |
| 99 |
return self._datagram_setting |
| 100 |
|
| 101 |
|
| 102 |
class WebTransportH3Protocol(QuicConnectionProtocol): |
| 103 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 104 |
super().__init__(*args, **kwargs) |
| 105 |
self._handler: Optional[Any] = None |
| 106 |
self._http: Optional[H3ConnectionWithDatagram] = None |
| 107 |
self._session_stream_id: Optional[int] = None |
| 108 |
self._close_info: Optional[Tuple[int, bytes]] = None |
| 109 |
self._capsule_decoder_for_session_stream: H3CapsuleDecoder =\ |
| 110 |
H3CapsuleDecoder() |
| 111 |
self._allow_calling_session_closed = True |
| 112 |
self._allow_datagrams = False |
| 113 |
|
| 114 |
def quic_event_received(self, event: QuicEvent) -> None: |
| 115 |
if isinstance(event, ProtocolNegotiated): |
| 116 |
self._http = H3ConnectionWithDatagram( |
| 117 |
self._quic, enable_webtransport=True) |
| 118 |
if self._http.datagram_setting != H3DatagramSetting.DRAFT04: |
| 119 |
self._allow_datagrams = True |
| 120 |
|
| 121 |
if self._http is not None: |
| 122 |
for http_event in self._http.handle_event(event): |
| 123 |
self._h3_event_received(http_event) |
| 124 |
|
| 125 |
if isinstance(event, ConnectionTerminated): |
| 126 |
self._call_session_closed(close_info=None, abruptly=True) |
| 127 |
if isinstance(event, StreamReset): |
| 128 |
if self._handler: |
| 129 |
self._handler.stream_reset(event.stream_id, event.error_code) |
| 130 |
|
| 131 |
def _h3_event_received(self, event: H3Event) -> None: |
| 132 |
if isinstance(event, HeadersReceived): |
| 133 |
# Convert from List[Tuple[bytes, bytes]] to Dict[bytes, bytes]. |
| 134 |
# Only the last header will be kept when there are duplicate |
| 135 |
# headers. |
| 136 |
headers = {} |
| 137 |
for header, value in event.headers: |
| 138 |
headers[header] = value |
| 139 |
|
| 140 |
method = headers.get(b":method") |
| 141 |
protocol = headers.get(b":protocol") |
| 142 |
origin = headers.get(b"origin") |
| 143 |
# Accept any Origin but the client must send it. |
| 144 |
if method == b"CONNECT" and protocol == b"webtransport" and origin: |
| 145 |
self._session_stream_id = event.stream_id |
| 146 |
self._handshake_webtransport(event, headers) |
| 147 |
else: |
| 148 |
status_code = 404 if origin else 403 |
| 149 |
self._send_error_response(event.stream_id, status_code) |
| 150 |
|
| 151 |
if isinstance(event, DataReceived) and\ |
| 152 |
self._session_stream_id == event.stream_id: |
| 153 |
if self._http and not self._http.datagram_setting and\ |
| 154 |
len(event.data) > 0: |
| 155 |
raise ProtocolError('Unexpected data on the session stream') |
| 156 |
self._receive_data_on_session_stream( |
| 157 |
event.data, event.stream_ended) |
| 158 |
elif self._handler is not None: |
| 159 |
if isinstance(event, WebTransportStreamDataReceived): |
| 160 |
self._handler.stream_data_received( |
| 161 |
stream_id=event.stream_id, |
| 162 |
data=event.data, |
| 163 |
stream_ended=event.stream_ended) |
| 164 |
elif isinstance(event, DatagramReceived): |
| 165 |
if self._allow_datagrams: |
| 166 |
self._handler.datagram_received(data=event.data) |
| 167 |
|
| 168 |
def _receive_data_on_session_stream(self, data: bytes, fin: bool) -> None: |
| 169 |
assert self._http is not None |
| 170 |
if len(data) > 0: |
| 171 |
self._capsule_decoder_for_session_stream.append(data) |
| 172 |
if fin: |
| 173 |
self._capsule_decoder_for_session_stream.final() |
| 174 |
for capsule in self._capsule_decoder_for_session_stream: |
| 175 |
if self._close_info is not None: |
| 176 |
raise ProtocolError(( |
| 177 |
"Receiving a capsule with type = {} after receiving " + |
| 178 |
"CLOSE_WEBTRANSPORT_SESSION").format(capsule.type)) |
| 179 |
assert self._http.datagram_setting is not None |
| 180 |
if self._http.datagram_setting == H3DatagramSetting.RFC: |
| 181 |
self._receive_h3_datagram_rfc_capsule_data( |
| 182 |
capsule=capsule, fin=fin) |
| 183 |
elif self._http.datagram_setting == H3DatagramSetting.DRAFT04: |
| 184 |
self._receive_h3_datagram_draft04_capsule_data( |
| 185 |
capsule=capsule, fin=fin) |
| 186 |
|
| 187 |
def _receive_h3_datagram_rfc_capsule_data(self, capsule: H3Capsule, fin: bool) -> None: |
| 188 |
if capsule.type == CapsuleType.DATAGRAM_RFC: |
| 189 |
raise ProtocolError( |
| 190 |
f"Unimplemented capsule type: {capsule.type}") |
| 191 |
elif capsule.type == CapsuleType.CLOSE_WEBTRANSPORT_SESSION: |
| 192 |
self._set_close_info_and_may_close_session( |
| 193 |
data=capsule.data, fin=fin) |
| 194 |
else: |
| 195 |
# Ignore unknown capsules. |
| 196 |
return |
| 197 |
|
| 198 |
def _receive_h3_datagram_draft04_capsule_data( |
| 199 |
self, capsule: H3Capsule, fin: bool) -> None: |
| 200 |
if capsule.type in {CapsuleType.DATAGRAM_DRAFT04, |
| 201 |
CapsuleType.REGISTER_DATAGRAM_CONTEXT_DRAFT04, |
| 202 |
CapsuleType.CLOSE_DATAGRAM_CONTEXT_DRAFT04}: |
| 203 |
raise ProtocolError( |
| 204 |
f"Unimplemented capsule type: {capsule.type}") |
| 205 |
if capsule.type in {CapsuleType.REGISTER_DATAGRAM_NO_CONTEXT_DRAFT04, |
| 206 |
CapsuleType.CLOSE_WEBTRANSPORT_SESSION}: |
| 207 |
# We'll handle this case below. |
| 208 |
pass |
| 209 |
else: |
| 210 |
# We should ignore unknown capsules. |
| 211 |
return |
| 212 |
|
| 213 |
if capsule.type == CapsuleType.REGISTER_DATAGRAM_NO_CONTEXT_DRAFT04: |
| 214 |
buffer = Buffer(data=capsule.data) |
| 215 |
format_type = buffer.pull_uint_var() |
| 216 |
# https://ietf-wg-webtrans.github.io/draft-ietf-webtrans-http3/draft-ietf-webtrans-http3.html#name-datagram-format-type |
| 217 |
WEBTRANPORT_FORMAT_TYPE = 0xff7c00 |
| 218 |
if format_type != WEBTRANPORT_FORMAT_TYPE: |
| 219 |
raise ProtocolError( |
| 220 |
"Unexpected datagram format type: {}".format( |
| 221 |
format_type)) |
| 222 |
self._allow_datagrams = True |
| 223 |
elif capsule.type == CapsuleType.CLOSE_WEBTRANSPORT_SESSION: |
| 224 |
self._set_close_info_and_may_close_session( |
| 225 |
data=capsule.data, fin=fin) |
| 226 |
|
| 227 |
def _set_close_info_and_may_close_session( |
| 228 |
self, data: bytes, fin: bool) -> None: |
| 229 |
buffer = Buffer(data=data) |
| 230 |
code = buffer.pull_uint32() |
| 231 |
# 4 bytes for the uint32. |
| 232 |
reason = buffer.pull_bytes(len(data) - 4) |
| 233 |
# TODO(bashi): Make sure `reason` is a UTF-8 text. |
| 234 |
self._close_info = (code, reason) |
| 235 |
if fin: |
| 236 |
self._call_session_closed(self._close_info, abruptly=False) |
| 237 |
|
| 238 |
def _send_error_response(self, stream_id: int, status_code: int) -> None: |
| 239 |
assert self._http is not None |
| 240 |
headers = [(b":status", str(status_code).encode()), |
| 241 |
(b"server", SERVER_NAME.encode())] |
| 242 |
self._http.send_headers(stream_id=stream_id, |
| 243 |
headers=headers, |
| 244 |
end_stream=True) |
| 245 |
|
| 246 |
def _handshake_webtransport(self, event: HeadersReceived, |
| 247 |
request_headers: Dict[bytes, bytes]) -> None: |
| 248 |
assert self._http is not None |
| 249 |
path = request_headers.get(b":path") |
| 250 |
if path is None: |
| 251 |
# `:path` must be provided. |
| 252 |
self._send_error_response(event.stream_id, 400) |
| 253 |
return |
| 254 |
|
| 255 |
# Create a handler using `:path`. |
| 256 |
try: |
| 257 |
self._handler = self._create_event_handler( |
| 258 |
session_id=event.stream_id, |
| 259 |
path=path, |
| 260 |
request_headers=event.headers) |
| 261 |
except OSError: |
| 262 |
self._send_error_response(event.stream_id, 404) |
| 263 |
return |
| 264 |
|
| 265 |
response_headers = [ |
| 266 |
(b"server", SERVER_NAME.encode()), |
| 267 |
(b"sec-webtransport-http3-draft", b"draft02"), |
| 268 |
] |
| 269 |
self._handler.connect_received(response_headers=response_headers) |
| 270 |
|
| 271 |
status_code = None |
| 272 |
for name, value in response_headers: |
| 273 |
if name == b":status": |
| 274 |
status_code = value |
| 275 |
response_headers.remove((b":status", status_code)) |
| 276 |
response_headers.insert(0, (b":status", status_code)) |
| 277 |
break |
| 278 |
if not status_code: |
| 279 |
response_headers.insert(0, (b":status", b"200")) |
| 280 |
self._http.send_headers(stream_id=event.stream_id, |
| 281 |
headers=response_headers) |
| 282 |
|
| 283 |
if status_code is None or status_code == b"200": |
| 284 |
self._handler.session_established() |
| 285 |
|
| 286 |
def _create_event_handler(self, session_id: int, path: bytes, |
| 287 |
request_headers: List[Tuple[bytes, bytes]]) -> Any: |
| 288 |
parsed = urlparse(path.decode()) |
| 289 |
file_path = os.path.join(_doc_root, parsed.path.lstrip("/")) |
| 290 |
callbacks = {"__file__": file_path} |
| 291 |
with open(file_path) as f: |
| 292 |
exec(compile(f.read(), path, "exec"), callbacks) |
| 293 |
session = WebTransportSession(self, session_id, request_headers) |
| 294 |
return WebTransportEventHandler(session, callbacks) |
| 295 |
|
| 296 |
def _call_session_closed( |
| 297 |
self, close_info: Optional[Tuple[int, bytes]], |
| 298 |
abruptly: bool) -> None: |
| 299 |
allow_calling_session_closed = self._allow_calling_session_closed |
| 300 |
self._allow_calling_session_closed = False |
| 301 |
if self._handler and allow_calling_session_closed: |
| 302 |
self._handler.session_closed(close_info, abruptly) |
| 303 |
|
| 304 |
|
| 305 |
class WebTransportSession: |
| 306 |
""" |
| 307 |
A WebTransport session. |
| 308 |
""" |
| 309 |
|
| 310 |
def __init__(self, protocol: WebTransportH3Protocol, session_id: int, |
| 311 |
request_headers: List[Tuple[bytes, bytes]]) -> None: |
| 312 |
self.session_id = session_id |
| 313 |
self.request_headers = request_headers |
| 314 |
|
| 315 |
self._protocol: WebTransportH3Protocol = protocol |
| 316 |
assert protocol._http is not None |
| 317 |
self._http: H3ConnectionWithDatagram = protocol._http |
| 318 |
|
| 319 |
# Use the a shared default path for all handlers so that different |
| 320 |
# WebTransport sessions can access the same store easily. |
| 321 |
self._stash_path = '/webtransport/handlers' |
| 322 |
self._stash: Optional[stash.Stash] = None |
| 323 |
self._dict_for_handlers: Dict[str, Any] = {} |
| 324 |
|
| 325 |
@property |
| 326 |
def stash(self) -> stash.Stash: |
| 327 |
"""A Stash object for storing cross-session state.""" |
| 328 |
if self._stash is None: |
| 329 |
address, authkey = stash.load_env_config() # type: ignore |
| 330 |
self._stash = stash.Stash(self._stash_path, address, authkey) # type: ignore |
| 331 |
return self._stash |
| 332 |
|
| 333 |
@property |
| 334 |
def dict_for_handlers(self) -> Dict[str, Any]: |
| 335 |
"""A dictionary that handlers can attach arbitrary data.""" |
| 336 |
return self._dict_for_handlers |
| 337 |
|
| 338 |
def stream_is_unidirectional(self, stream_id: int) -> bool: |
| 339 |
"""Return True if the stream is unidirectional.""" |
| 340 |
return stream_is_unidirectional(stream_id) |
| 341 |
|
| 342 |
def close(self, close_info: Optional[Tuple[int, bytes]]) -> None: |
| 343 |
""" |
| 344 |
Close the session. |
| 345 |
|
| 346 |
:param close_info The close information to send. |
| 347 |
""" |
| 348 |
self._protocol._allow_calling_session_closed = False |
| 349 |
assert self._protocol._session_stream_id is not None |
| 350 |
session_stream_id = self._protocol._session_stream_id |
| 351 |
if close_info is not None: |
| 352 |
code = close_info[0] |
| 353 |
reason = close_info[1] |
| 354 |
buffer = Buffer(capacity=len(reason) + 4) |
| 355 |
buffer.push_uint32(code) |
| 356 |
buffer.push_bytes(reason) |
| 357 |
capsule =\ |
| 358 |
H3Capsule(CapsuleType.CLOSE_WEBTRANSPORT_SESSION, buffer.data) |
| 359 |
self._http.send_data( |
| 360 |
session_stream_id, capsule.encode(), end_stream=False) |
| 361 |
|
| 362 |
self._http.send_data(session_stream_id, b'', end_stream=True) |
| 363 |
# TODO(yutakahirano): Reset all other streams. |
| 364 |
# TODO(yutakahirano): Reject future stream open requests |
| 365 |
# We need to wait for the stream data to arrive at the client, and then |
| 366 |
# we need to close the connection. At this moment we're relying on the |
| 367 |
# client's behavior. |
| 368 |
# TODO(yutakahirano): Implement the above. |
| 369 |
|
| 370 |
def create_unidirectional_stream(self) -> int: |
| 371 |
""" |
| 372 |
Create a unidirectional WebTransport stream and return the stream ID. |
| 373 |
""" |
| 374 |
return self._http.create_webtransport_stream( |
| 375 |
session_id=self.session_id, is_unidirectional=True) |
| 376 |
|
| 377 |
def create_bidirectional_stream(self) -> int: |
| 378 |
""" |
| 379 |
Create a bidirectional WebTransport stream and return the stream ID. |
| 380 |
""" |
| 381 |
stream_id = self._http.create_webtransport_stream( |
| 382 |
session_id=self.session_id, is_unidirectional=False) |
| 383 |
# TODO(bashi): Remove this workaround when aioquic supports receiving |
| 384 |
# data on server-initiated bidirectional streams. |
| 385 |
stream = self._http._get_or_create_stream(stream_id) |
| 386 |
assert stream.frame_type is None |
| 387 |
assert stream.session_id is None |
| 388 |
stream.frame_type = FrameType.WEBTRANSPORT_STREAM |
| 389 |
stream.session_id = self.session_id |
| 390 |
return stream_id |
| 391 |
|
| 392 |
def send_stream_data(self, |
| 393 |
stream_id: int, |
| 394 |
data: bytes, |
| 395 |
end_stream: bool = False) -> None: |
| 396 |
""" |
| 397 |
Send data on the specific stream. |
| 398 |
|
| 399 |
:param stream_id: The stream ID on which to send the data. |
| 400 |
:param data: The data to send. |
| 401 |
:param end_stream: If set to True, the stream will be closed. |
| 402 |
""" |
| 403 |
self._http._quic.send_stream_data(stream_id=stream_id, |
| 404 |
data=data, |
| 405 |
end_stream=end_stream) |
| 406 |
|
| 407 |
def send_datagram(self, data: bytes) -> None: |
| 408 |
""" |
| 409 |
Send data using a datagram frame. |
| 410 |
|
| 411 |
:param data: The data to send. |
| 412 |
""" |
| 413 |
if not self._protocol._allow_datagrams: |
| 414 |
_logger.warn( |
| 415 |
"Sending a datagram while that's not allowed - discarding it") |
| 416 |
return |
| 417 |
stream_id = self.session_id |
| 418 |
if self._http.datagram_setting is not None: |
| 419 |
# We must have a WebTransport Session ID at this point because |
| 420 |
# an extended CONNECT request is already received. |
| 421 |
assert self._protocol._session_stream_id is not None |
| 422 |
# TODO(yutakahirano): Make sure if this is the correct logic. |
| 423 |
# Chrome always use 0 for the initial stream and the initial flow |
| 424 |
# ID, we cannot check the correctness with it. |
| 425 |
stream_id = self._protocol._session_stream_id |
| 426 |
self._http.send_datagram(stream_id=stream_id, data=data) |
| 427 |
|
| 428 |
def stop_stream(self, stream_id: int, code: int) -> None: |
| 429 |
""" |
| 430 |
Send a STOP_SENDING frame to the given stream. |
| 431 |
:param code: the reason of the error. |
| 432 |
""" |
| 433 |
self._http._quic.stop_stream(stream_id, code) |
| 434 |
|
| 435 |
def reset_stream(self, stream_id: int, code: int) -> None: |
| 436 |
""" |
| 437 |
Send a RESET_STREAM frame to the given stream. |
| 438 |
:param code: the reason of the error. |
| 439 |
""" |
| 440 |
self._http._quic.reset_stream(stream_id, code) |
| 441 |
|
| 442 |
|
| 443 |
class WebTransportEventHandler: |
| 444 |
def __init__(self, session: WebTransportSession, |
| 445 |
callbacks: Dict[str, Any]) -> None: |
| 446 |
self._session = session |
| 447 |
self._callbacks = callbacks |
| 448 |
|
| 449 |
def _run_callback(self, callback_name: str, |
| 450 |
*args: Any, **kwargs: Any) -> None: |
| 451 |
if callback_name not in self._callbacks: |
| 452 |
return |
| 453 |
try: |
| 454 |
self._callbacks[callback_name](*args, **kwargs) |
| 455 |
except Exception as e: |
| 456 |
_logger.warn(str(e)) |
| 457 |
traceback.print_exc() |
| 458 |
|
| 459 |
def connect_received(self, response_headers: List[Tuple[bytes, |
| 460 |
bytes]]) -> None: |
| 461 |
self._run_callback("connect_received", self._session.request_headers, |
| 462 |
response_headers) |
| 463 |
|
| 464 |
def session_established(self) -> None: |
| 465 |
self._run_callback("session_established", self._session) |
| 466 |
|
| 467 |
def stream_data_received(self, stream_id: int, data: bytes, |
| 468 |
stream_ended: bool) -> None: |
| 469 |
self._run_callback("stream_data_received", self._session, stream_id, |
| 470 |
data, stream_ended) |
| 471 |
|
| 472 |
def datagram_received(self, data: bytes) -> None: |
| 473 |
self._run_callback("datagram_received", self._session, data) |
| 474 |
|
| 475 |
def session_closed( |
| 476 |
self, |
| 477 |
close_info: Optional[Tuple[int, bytes]], |
| 478 |
abruptly: bool) -> None: |
| 479 |
self._run_callback( |
| 480 |
"session_closed", self._session, close_info, abruptly=abruptly) |
| 481 |
|
| 482 |
def stream_reset(self, stream_id: int, error_code: int) -> None: |
| 483 |
self._run_callback( |
| 484 |
"stream_reset", self._session, stream_id, error_code) |
| 485 |
|
| 486 |
|
| 487 |
class SessionTicketStore: |
| 488 |
""" |
| 489 |
Simple in-memory store for session tickets. |
| 490 |
""" |
| 491 |
|
| 492 |
def __init__(self) -> None: |
| 493 |
self.tickets: Dict[bytes, SessionTicket] = {} |
| 494 |
|
| 495 |
def add(self, ticket: SessionTicket) -> None: |
| 496 |
self.tickets[ticket.ticket] = ticket |
| 497 |
|
| 498 |
def pop(self, label: bytes) -> Optional[SessionTicket]: |
| 499 |
return self.tickets.pop(label, None) |
| 500 |
|
| 501 |
|
| 502 |
class WebTransportH3Server: |
| 503 |
""" |
| 504 |
A WebTransport over HTTP/3 for testing. |
| 505 |
|
| 506 |
:param host: Host from which to serve. |
| 507 |
:param port: Port from which to serve. |
| 508 |
:param doc_root: Document root for serving handlers. |
| 509 |
:param cert_path: Path to certificate file to use. |
| 510 |
:param key_path: Path to key file to use. |
| 511 |
:param logger: a Logger object for this server. |
| 512 |
""" |
| 513 |
|
| 514 |
def __init__(self, host: str, port: int, doc_root: str, cert_path: str, |
| 515 |
key_path: str, logger: Optional[logging.Logger]) -> None: |
| 516 |
self.host = host |
| 517 |
self.port = port |
| 518 |
self.doc_root = doc_root |
| 519 |
self.cert_path = cert_path |
| 520 |
self.key_path = key_path |
| 521 |
self.started = False |
| 522 |
global _doc_root |
| 523 |
_doc_root = self.doc_root |
| 524 |
global _logger |
| 525 |
if logger is not None: |
| 526 |
_logger = logger |
| 527 |
|
| 528 |
def start(self) -> None: |
| 529 |
"""Start the server.""" |
| 530 |
self.server_thread = threading.Thread( |
| 531 |
target=self._start_on_server_thread, daemon=True) |
| 532 |
self.server_thread.start() |
| 533 |
self.started = True |
| 534 |
|
| 535 |
def _start_on_server_thread(self) -> None: |
| 536 |
secrets_log_file = None |
| 537 |
if "SSLKEYLOGFILE" in os.environ: |
| 538 |
try: |
| 539 |
secrets_log_file = open(os.environ["SSLKEYLOGFILE"], "a") |
| 540 |
except Exception as e: |
| 541 |
_logger.warn(str(e)) |
| 542 |
|
| 543 |
# Workaround https://github.com/aiortc/aioquic/issues/567 with if/else |
| 544 |
if secrets_log_file is not None: |
| 545 |
configuration = QuicConfiguration( |
| 546 |
alpn_protocols=H3_ALPN, |
| 547 |
is_client=False, |
| 548 |
max_datagram_frame_size=65536, |
| 549 |
secrets_log_file=secrets_log_file, |
| 550 |
) |
| 551 |
else: |
| 552 |
configuration = QuicConfiguration( |
| 553 |
alpn_protocols=H3_ALPN, |
| 554 |
is_client=False, |
| 555 |
max_datagram_frame_size=65536, |
| 556 |
) |
| 557 |
|
| 558 |
_logger.info("Starting WebTransport over HTTP/3 server on %s:%s", |
| 559 |
self.host, self.port) |
| 560 |
|
| 561 |
configuration.load_cert_chain(Path(self.cert_path), Path(self.key_path)) |
| 562 |
|
| 563 |
ticket_store = SessionTicketStore() |
| 564 |
|
| 565 |
# On Windows, the default event loop is ProactorEventLoop but it |
| 566 |
# doesn't seem to work when aioquic detects a connection loss. |
| 567 |
# Use SelectorEventLoop to work around the problem. |
| 568 |
if sys.platform == "win32": |
| 569 |
asyncio.set_event_loop_policy( |
| 570 |
asyncio.WindowsSelectorEventLoopPolicy()) |
| 571 |
self.loop = asyncio.new_event_loop() |
| 572 |
asyncio.set_event_loop(self.loop) |
| 573 |
|
| 574 |
self.loop.run_until_complete( |
| 575 |
serve( |
| 576 |
self.host, |
| 577 |
self.port, |
| 578 |
configuration=configuration, |
| 579 |
create_protocol=WebTransportH3Protocol, |
| 580 |
session_ticket_fetcher=ticket_store.pop, |
| 581 |
session_ticket_handler=ticket_store.add, |
| 582 |
)) |
| 583 |
self.loop.run_forever() |
| 584 |
|
| 585 |
def stop(self) -> None: |
| 586 |
"""Stop the server.""" |
| 587 |
if self.started: |
| 588 |
asyncio.run_coroutine_threadsafe(self._stop_on_server_thread(), |
| 589 |
self.loop) |
| 590 |
self.server_thread.join() |
| 591 |
_logger.info("Stopped WebTransport over HTTP/3 server on %s:%s", |
| 592 |
self.host, self.port) |
| 593 |
self.started = False |
| 594 |
|
| 595 |
async def _stop_on_server_thread(self) -> None: |
| 596 |
self.loop.stop() |
| 597 |
|
| 598 |
|
| 599 |
def server_is_running(host: str, port: int, timeout: float) -> bool: |
| 600 |
""" |
| 601 |
Check the WebTransport over HTTP/3 server is running at the given `host` and |
| 602 |
`port`. |
| 603 |
""" |
| 604 |
loop = asyncio.get_event_loop() |
| 605 |
return loop.run_until_complete(_connect_server_with_timeout(host, port, timeout)) |
| 606 |
|
| 607 |
|
| 608 |
async def _connect_server_with_timeout(host: str, port: int, timeout: float) -> bool: |
| 609 |
try: |
| 610 |
await asyncio.wait_for(_connect_to_server(host, port), timeout=timeout) |
| 611 |
except asyncio.TimeoutError: |
| 612 |
_logger.warning("Failed to connect WebTransport over HTTP/3 server") |
| 613 |
return False |
| 614 |
return True |
| 615 |
|
| 616 |
|
| 617 |
def _close_unusable_writer(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: |
| 618 |
# Starting in python3.11, `StreamWriter.__del__` implicitly `close()`s |
| 619 |
# itself [0], if it has not done so already. Because aioquic sometimes |
| 620 |
# models a unidirectional stream with a bidirectional transport [1], the |
| 621 |
# `writer` here for a server -> client stream may log a benign but |
| 622 |
# scary-looking exception when it's GC'ed and unsuccessfully writes EOF. |
| 623 |
# |
| 624 |
# For the purpose of checking connectivity, work around this for now by |
| 625 |
# preemptively closing such streams and suppressing the resulting |
| 626 |
# exceptions. |
| 627 |
# |
| 628 |
# [0]: https://github.com/python/cpython/blob/3.11/Lib/asyncio/streams.py#L413 |
| 629 |
# [1]: https://github.com/aiortc/aioquic/blob/1.2.0/src/aioquic/asyncio/protocol.py#L241 |
| 630 |
stream_id = cast(QuicStreamAdapter, writer.transport).stream_id |
| 631 |
if stream_is_unidirectional(stream_id) and not stream_is_client_initiated(stream_id): |
| 632 |
with contextlib.suppress(ValueError): |
| 633 |
writer.close() |
| 634 |
|
| 635 |
|
| 636 |
async def _connect_to_server(host: str, port: int) -> None: |
| 637 |
configuration = QuicConfiguration( |
| 638 |
alpn_protocols=H3_ALPN, |
| 639 |
is_client=True, |
| 640 |
verify_mode=ssl.CERT_NONE, |
| 641 |
) |
| 642 |
|
| 643 |
async with connect(host, port, configuration=configuration, |
| 644 |
stream_handler=_close_unusable_writer) as protocol: |
| 645 |
await protocol.ping() |