path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
tests.test_asyncio/HighLevelTest.test_server_receives_garbage
Modified
aiortc~aioquic
1c16a37df2078c8b819b3361da4317fb848d4cfe
[asyncio] create future for wait_connected on demand
<0>:<add> server = run(self.run_server(stateless_retry=False)) <del> server = run(run_server(stateless_retry=False))
# module: tests.test_asyncio class HighLevelTest(TestCase): def test_server_receives_garbage(self): <0> server = run(run_server(stateless_retry=False)) <1> server.datagram_received(binascii.unhexlify("c00000000080"), ("1.2.3.4", 1234)) <2> server.close() <3>
===========unchanged ref 0=========== at: tests.test_asyncio.HighLevelTest run_server(configuration=None) at: tests.test_asyncio.HighLevelTest.test_key_update run_client_key_update(host, port=4433) ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def run_server(self, configuration=None, **kwargs): + if configuration is None: + configuration = QuicConfiguration(is_client=False) + configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) + return await serve( + host="::", + port="4433", + configuration=configuration, + stream_handler=handle_stream, + **kwargs + ) + ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_timeout(self): with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", port=4400, configuration=QuicConfiguration(is_client=True, idle_timeout=5), ) ) ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_ping(self): async def run_client_ping(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: await client.ping() await client.ping() server, _ = run( asyncio.gather( + self.run_server(stateless_retry=False), run_client_ping("127.0.0.1") - run_server(stateless_retry=False), run_client_ping("127.0.0.1") ) ) server.close() ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_sni(self): + server, response = run( + asyncio.gather(self.run_server(), self.run_client("localhost")) - server, response = run(asyncio.gather(run_server(), run_client("localhost"))) + ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_key_update(self): async def run_client_key_update(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: await client.ping() client.request_key_update() await client.ping() server, _ = run( asyncio.gather( + self.run_server(stateless_retry=False), + run_client_key_update("127.0.0.1"), - run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_version_negotiation(self): server, response = run( asyncio.gather( + self.run_server(), - run_server(), + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration( is_client=True, quic_logger=QuicLogger(), supported_versions=[0x1A2A3A4A, QuicProtocolVersion.DRAFT_23], ), ), ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") def test_connect_and_serve_with_stateless_retry_bad(self, mock_validate): mock_validate.side_effect = ValueError("Decryption failed.") + server = run(self.run_server(stateless_retry=True)) - server = run(run_server(stateless_retry=True)) with self.assertRaises(ConnectionError): run( + self.run_client( - run_client( "127.0.0.1", configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), ) ) server.close() ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry(self): server, response = run( + asyncio.gather( + self.run_server(stateless_retry=True), self.run_client("127.0.0.1") - asyncio.gather(run_server(stateless_retry=True), run_client("127.0.0.1")) + ) ) self.assertEqual(response, b"gnip") server.close() ===========changed ref 8=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_change_connection_id(self): async def run_client_key_update(host, port=4433): configuration = QuicConfiguration(is_client=True) configuration.load_verify_locations(cafile=SERVER_CACERTFILE) async with connect(host, port, configuration=configuration) as client: await client.ping() client.change_connection_id() await client.ping() server, _ = run( asyncio.gather( + self.run_server(stateless_retry=False), + run_client_key_update("127.0.0.1"), - run_server(stateless_retry=False), run_client_key_update("127.0.0.1") ) ) server.close() ===========changed ref 9=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_with_stateless_retry_bad_original_connection_id(self): """ If the server's transport parameters do not have the correct original_connection_id the connection fail. """ def create_protocol(*args, **kwargs): protocol = QuicConnectionProtocol(*args, **kwargs) protocol._quic._original_connection_id = None return protocol + server = run( + self.run_server(create_protocol=create_protocol, stateless_retry=True) - server = run(run_server(create_protocol=create_protocol, stateless_retry=True)) + ) with self.assertRaises(ConnectionError): + run(self.run_client("127.0.0.1")) - run(run_client("127.0.0.1")) server.close() ===========changed ref 10=========== # module: tests.test_asyncio class HighLevelTest(TestCase): def test_connect_and_serve_without_client_configuration(self): async def run_client_without_config(host, port=4433): async with connect(host, port) as client: await client.ping() + server = run(self.run_server()) - server = run(run_server()) with self.assertRaises(ConnectionError): run(run_client_without_config("127.0.0.1")) server.close()
examples.demo/logs
Modified
aiortc~aioquic
57a1fa20dea79e18e4bf28f06c5d2875d483d55c
[examples] point qvis links to the sequence diagram view
<15>:<add> "qvis_url": QVIS_URL <add> + "?" <add> + urlencode({"file": file_url}) <del> "qvis_url": QVIS_URL + "?" + urlencode({"file": file_url}), <16>:<add> + "#/sequence",
# module: examples.demo @app.route("/logs/?") async def logs(request): <0> """ <1> Browsable list of QLOG files. <2> """ <3> logs = [] <4> for name in os.listdir(LOGS_PATH): <5> if name.endswith(".qlog"): <6> s = os.stat(os.path.join(LOGS_PATH, name)) <7> file_url = "https://" + request.headers["host"] + "/logs/" + name <8> logs.append( <9> { <10> "date": datetime.datetime.utcfromtimestamp(s.st_mtime).strftime( <11> "%Y-%m-%d %H:%M:%S" <12> ), <13> "file_url": file_url, <14> "name": name[:-5], <15> "qvis_url": QVIS_URL + "?" + urlencode({"file": file_url}), <16> "size": s.st_size, <17> } <18> ) <19> return templates.TemplateResponse( <20> "logs.html", <21> { <22> "logs": sorted(logs, key=lambda x: x["date"], reverse=True), <23> "request": request, <24> }, <25> ) <26>
===========unchanged ref 0=========== at: datetime datetime() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' strftime(fmt: _Text) -> str __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ utcfromtimestamp(t: float) -> _S __radd__ = __add__ at: examples.demo LOGS_PATH = os.path.join(ROOT, "htdocs", "logs") QVIS_URL = "https://qvis.edm.uhasselt.be/" templates = Jinja2Templates(directory=os.path.join(ROOT, "templates")) app = Starlette() at: os listdir(path: bytes) -> List[bytes] listdir(path: int) -> List[str] listdir(path: Optional[str]=...) -> List[str] listdir(path: _PathLike[str]) -> List[str] stat(path: _FdOrAnyPath, *, dir_fd: Optional[int]=..., follow_symlinks: bool=...) -> stat_result at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes at: os.stat_result st_mode: int # protection bits, st_ino: int # inode number, st_dev: int # device, st_nlink: int # number of hard links, st_uid: int # user id of owner, st_gid: int # group id of owner, st_size: int # size of file, in bytes, st_atime: float # time of most recent access, st_mtime: float # time of most recent content modification, ===========unchanged ref 1=========== st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) st_atime_ns: int # time of most recent access, in nanoseconds st_mtime_ns: int # time of most recent content modification in nanoseconds st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds st_reparse_tag: int st_file_attributes: int st_blocks: int # number of blocks allocated for file st_blksize: int # filesystem blocksize st_rdev: int # type of device if an inode device st_flags: int # user defined flags for file st_gen: int # file generation number st_birthtime: int # time of file creation st_rsize: int st_creator: int st_type: int at: urllib.parse urlencode(query: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]], Sequence[Tuple[Any, Any]], Sequence[Tuple[Any, Sequence[Any]]]], doseq: bool=..., safe: AnyStr=..., encoding: str=..., errors: str=..., quote_via: Callable[[str, AnyStr, str, str], str]=...) -> str
aioquic.asyncio.protocol/QuicConnectionProtocol.__init__
Modified
aiortc~aioquic
34a826ff81fc310dae259c0d2496d872ce5a2830
[asyncio] allow multiple calls to ping() in parallel
<6>:<add> self._ping_waiters: Dict[int, asyncio.Future[None]] = {} <del> self._ping_waiter: Optional[asyncio.Future[None]] = None
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): <0> loop = asyncio.get_event_loop() <1> <2> self._closed = asyncio.Event() <3> self._connected = False <4> self._connected_waiter: Optional[asyncio.Future[None]] = None <5> self._loop = loop <6> self._ping_waiter: Optional[asyncio.Future[None]] = None <7> self._quic = quic <8> self._stream_readers: Dict[int, asyncio.StreamReader] = {} <9> self._timer: Optional[asyncio.TimerHandle] = None <10> self._timer_at: Optional[float] = None <11> self._transmit_task: Optional[asyncio.Handle] = None <12> self._transport: Optional[asyncio.DatagramTransport] = None <13> <14> # callbacks <15> self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None <16> self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None <17> self._connection_terminated_handler: Callable[[], None] = lambda: None <18> if stream_handler is not None: <19> self._stream_handler = stream_handler <20> else: <21> self._stream_handler = lambda r, w: None <22>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.protocol QuicConnectionIdHandler = Callable[[bytes], None] QuicStreamHandler = Callable[[asyncio.StreamReader, asyncio.StreamWriter], None] at: aioquic.asyncio.protocol.QuicConnectionProtocol._handle_timer self._timer = None self._timer_at = None at: aioquic.asyncio.protocol.QuicConnectionProtocol._process_events self._connected_waiter = None self._connected = True at: aioquic.asyncio.protocol.QuicConnectionProtocol._transmit_soon self._transmit_task = self._loop.call_soon(self.transmit) at: aioquic.asyncio.protocol.QuicConnectionProtocol.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: aioquic.asyncio.protocol.QuicConnectionProtocol.transmit self._transmit_task = None self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected self._connected_waiter = self._loop.create_future() at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, logger_connection_id: Optional[bytes]=None, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: asyncio.events Handle(callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop ===========unchanged ref 1=========== at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.streams StreamReader(limit: int=..., loop: Optional[events.AbstractEventLoop]=...) at: asyncio.transports DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: typing Callable = _CallableType(collections.abc.Callable, 2) Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.asyncio.protocol/QuicConnectionProtocol.ping
Modified
aiortc~aioquic
34a826ff81fc310dae259c0d2496d872ce5a2830
[asyncio] allow multiple calls to ping() in parallel
<3>:<del> assert self._ping_waiter is None, "already awaiting ping" <4>:<add> waiter = self._loop.create_future() <del> self._ping_waiter = self._loop.create_future() <5>:<add> uid = id(waiter) <add> self._ping_waiters[uid] = waiter <add> self._quic.send_ping(uid) <del> self._quic.send_ping(id(self._ping_waiter)) <7>:<add> await asyncio.shield(waiter) <del> await asyncio.shield(self._ping_waiter)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: <0> """ <1> Ping the peer and wait for the response. <2> """ <3> assert self._ping_waiter is None, "already awaiting ping" <4> self._ping_waiter = self._loop.create_future() <5> self._quic.send_ping(id(self._ping_waiter)) <6> self.transmit() <7> await asyncio.shield(self._ping_waiter) <8>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol transmit() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._loop = loop self._ping_waiters: Dict[int, asyncio.Future[None]] = {} self._quic = quic at: aioquic.quic.connection.QuicConnection send_ping(uid: int) -> None at: asyncio.events.AbstractEventLoop create_future() -> Future[Any] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected = False self._connected_waiter: Optional[asyncio.Future[None]] = None self._loop = loop + self._ping_waiters: Dict[int, asyncio.Future[None]] = {} - self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.asyncio.protocol/QuicConnectionProtocol._process_events
Modified
aiortc~aioquic
34a826ff81fc310dae259c0d2496d872ce5a2830
[asyncio] allow multiple calls to ping() in parallel
<20>:<add> waiter = self._ping_waiters.pop(event.uid, None) <del> waiter = self._ping_waiter <21>:<add> if waiter is not None: <del> self._ping_waiter = None <22>:<add> waiter.set_result(None) <del> waiter.set_result(None)
# module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def _process_events(self) -> None: <0> event = self._quic.next_event() <1> while event is not None: <2> if isinstance(event, events.ConnectionIdIssued): <3> self._connection_id_issued_handler(event.connection_id) <4> elif isinstance(event, events.ConnectionIdRetired): <5> self._connection_id_retired_handler(event.connection_id) <6> elif isinstance(event, events.ConnectionTerminated): <7> self._connection_terminated_handler() <8> if self._connected_waiter is not None: <9> waiter = self._connected_waiter <10> self._connected_waiter = None <11> waiter.set_exception(ConnectionError) <12> self._closed.set() <13> elif isinstance(event, events.HandshakeCompleted): <14> if self._connected_waiter is not None: <15> waiter = self._connected_waiter <16> self._connected = True <17> self._connected_waiter = None <18> waiter.set_result(None) <19> elif isinstance(event, events.PingAcknowledged): <20> waiter = self._ping_waiter <21> self._ping_waiter = None <22> waiter.set_result(None) <23> self.quic_event_received(event) <24> event = self._quic.next_event() <25>
===========unchanged ref 0=========== at: _asyncio.Future set_exception(exception, /) set_result(result, /) at: aioquic.asyncio.protocol.QuicConnectionProtocol quic_event_received(event: events.QuicEvent) -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._closed = asyncio.Event() self._connected = False self._connected_waiter: Optional[asyncio.Future[None]] = None self._ping_waiters: Dict[int, asyncio.Future[None]] = {} self._quic = quic self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None at: aioquic.asyncio.protocol.QuicConnectionProtocol.wait_connected self._connected_waiter = self._loop.create_future() at: aioquic.quic.connection.QuicConnection next_event() -> Optional[events.QuicEvent] at: aioquic.quic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) PingAcknowledged(uid: int) at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) ===========unchanged ref 1=========== set_result(result: _T, /) -> None set_exception(exception: Union[type, BaseException], /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: asyncio.locks.Event set() -> None at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def ping(self) -> None: """ Ping the peer and wait for the response. """ - assert self._ping_waiter is None, "already awaiting ping" + waiter = self._loop.create_future() - self._ping_waiter = self._loop.create_future() + uid = id(waiter) + self._ping_waiters[uid] = waiter + self._quic.send_ping(uid) - self._quic.send_ping(id(self._ping_waiter)) self.transmit() + await asyncio.shield(waiter) - await asyncio.shield(self._ping_waiter) ===========changed ref 1=========== # module: aioquic.asyncio.protocol class QuicConnectionProtocol(asyncio.DatagramProtocol): def __init__( self, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler] = None ): loop = asyncio.get_event_loop() self._closed = asyncio.Event() self._connected = False self._connected_waiter: Optional[asyncio.Future[None]] = None self._loop = loop + self._ping_waiters: Dict[int, asyncio.Future[None]] = {} - self._ping_waiter: Optional[asyncio.Future[None]] = None self._quic = quic self._stream_readers: Dict[int, asyncio.StreamReader] = {} self._timer: Optional[asyncio.TimerHandle] = None self._timer_at: Optional[float] = None self._transmit_task: Optional[asyncio.Handle] = None self._transport: Optional[asyncio.DatagramTransport] = None # callbacks self._connection_id_issued_handler: QuicConnectionIdHandler = lambda c: None self._connection_id_retired_handler: QuicConnectionIdHandler = lambda c: None self._connection_terminated_handler: Callable[[], None] = lambda: None if stream_handler is not None: self._stream_handler = stream_handler else: self._stream_handler = lambda r, w: None
aioquic.h3.connection/H3Connection._encode_headers
Modified
aiortc~aioquic
5750e8b66fc9d0c309a56009892be2dead82f382
[http3] use pylsqpack 0.3.0
<3>:<add> encoder, frame_data = self._encoder.encode(stream_id, headers) <del> encoder, frame_data = self._encoder.encode(stream_id, 0, headers)
# module: aioquic.h3.connection class H3Connection: def _encode_headers(self, stream_id: int, headers: Headers) -> bytes: <0> """ <1> Encode a HEADERS block and send encoder updates on the encoder stream. <2> """ <3> encoder, frame_data = self._encoder.encode(stream_id, 0, headers) <4> self._encoder_bytes_sent += len(encoder) <5> self._quic.send_stream_data(self._local_encoder_stream_id, encoder) <6> return frame_data <7>
===========unchanged ref 0=========== at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._encoder = pylsqpack.Encoder() self._encoder_bytes_sent = 0 self._local_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None
tests.test_tls/ContextTest.create_client
Modified
aiortc~aioquic
4eaefff68ee7321785b32d849ab45da3799c51bf
[tls] test handshake with unknown CA but no verification
<1>:<add> alpn_protocols=alpn_protocols, <add> cadata=cadata, <add> cafile=cafile, <add> is_client=True, <add> **kwargs <del> alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True
# module: tests.test_tls class ContextTest(TestCase): + def create_client( + self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE, **kwargs - def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): + ): <0> client = Context( <1> alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True <2> ) <3> client.handshake_extensions = [ <4> ( <5> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <6> CLIENT_QUIC_TRANSPORT_PARAMETERS, <7> ) <8> ] <9> self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) <10> return client <11>
===========unchanged ref 0=========== at: aioquic.tls Context(is_client: bool, alpn_protocols: Optional[List[str]]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, server_name: Optional[str]=None, verify_mode: Optional[int]=None) at: aioquic.tls.Context.__init__ self.handshake_extensions: List[Extension] = [] at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") at: unittest.case TestCase(methodName: str=...)
tests.test_tls/ContextTest.test_handshake_with_alpn_fail
Modified
aiortc~aioquic
4eaefff68ee7321785b32d849ab45da3799c51bf
[tls] test handshake with unknown CA but no verification
<1>:<del> <4>:<del> # send client hello <5>:<del> client_buf = create_buffers() <6>:<del> client.handle_message(b"", client_buf) <7>:<del> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8>:<del> server_input = merge_buffers(client_buf) <9>:<del> self.assertGreaterEqual(len(server_input), 258) <10>:<del> self.assertLessEqual(len(server_input), 296) <11>:<del> reset_buffers(client_buf) <12>:<del> <13>:<del> # handle client hello <14>:<del> # send server hello, encrypted extensions, certificate, certificate verify, finished <15>:<del> server_buf = create_buffers() <17>:<add> self._handshake(client, server) <del> server.handle_message(server_input, server_buf)
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn_fail(self): <0> client = self.create_client(alpn_protocols=["hq-20"]) <1> <2> server = self.create_server(alpn_protocols=["h3-20"]) <3> <4> # send client hello <5> client_buf = create_buffers() <6> client.handle_message(b"", client_buf) <7> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <8> server_input = merge_buffers(client_buf) <9> self.assertGreaterEqual(len(server_input), 258) <10> self.assertLessEqual(len(server_input), 296) <11> reset_buffers(client_buf) <12> <13> # handle client hello <14> # send server hello, encrypted extensions, certificate, certificate verify, finished <15> server_buf = create_buffers() <16> with self.assertRaises(tls.AlertHandshakeFailure) as cm: <17> server.handle_message(server_input, server_buf) <18> self.assertEqual(str(cm.exception), "No common ALPN protocols") <19>
===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context.__init__ self._signature_algorithms: List[int] = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self.alpn_negotiated: Optional[str] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self._alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) at: tests.test_tls.ContextTest create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE, *, capath: Optional[str]=None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, server_name: Optional[str]=None) create_client(alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE, *, capath: Optional[str]=None, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None, max_early_data: Optional[int]=None, server_name: Optional[str]=None) create_server(alpn_protocols=None) _handshake(client, server) ===========unchanged ref 1=========== at: tests.test_tls.ContextTest.test_handshake_with_alpn client = self.create_client(alpn_protocols=["hq-20"]) server = self.create_server(alpn_protocols=["hq-20", "h3-20"]) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): + def create_client( + self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE, **kwargs - def create_client(self, alpn_protocols=None, cadata=None, cafile=SERVER_CACERTFILE): + ): client = Context( + alpn_protocols=alpn_protocols, + cadata=cadata, + cafile=cafile, + is_client=True, + **kwargs - alpn_protocols=alpn_protocols, cadata=cadata, cafile=cafile, is_client=True ) client.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ] self.assertEqual(client.state, State.CLIENT_HANDSHAKE_START) return client
aioquic.quic.logger/QuicLoggerTrace.encode_max_stream_data_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<2>:<del> "id": str(stream_id), <4>:<add> "stream_id": str(stream_id),
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: <0> return { <1> "frame_type": "max_stream_data", <2> "id": str(stream_id), <3> "maximum": str(maximum), <4> } <5>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.quic.logger/QuicLoggerTrace.encode_reset_stream_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<4>:<add> "stream_id": str(stream_id),
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: <0> return { <1> "error_code": error_code, <2> "final_size": str(final_size), <3> "frame_type": "reset_stream", <4> } <5>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), }
aioquic.quic.logger/QuicLoggerTrace.encode_stop_sending_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<2>:<del> "id": str(stream_id), <4>:<add> "stream_id": str(stream_id),
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: <0> return { <1> "frame_type": "stop_sending", <2> "id": str(stream_id), <3> "error_code": error_code, <4> } <5>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), }
aioquic.quic.logger/QuicLoggerTrace.encode_stream_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<3>:<del> "id": str(stream_id), <6>:<add> "stream_id": str(stream_id),
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: <0> return { <1> "fin": frame.fin, <2> "frame_type": "stream", <3> "id": str(stream_id), <4> "length": str(len(frame.data)), <5> "offset": str(frame.offset), <6> } <7>
===========unchanged ref 0=========== at: aioquic.quic.packet QuicStreamFrame(data: bytes=b"", fin: bool=False, offset: int=0) at: aioquic.quic.packet.QuicStreamFrame data: bytes = b"" fin: bool = False offset: int = 0 at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), }
aioquic.quic.logger/QuicLoggerTrace.encode_transport_parameters
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<0>:<add> data: Dict[str, Any] = {"owner": owner} <del> data = [] <3>:<add> data[param_name] = param_value <del> data.append({"name": param_name, "value": param_value}) <5>:<add> data[param_name] = param_value <del> data.append({"name": param_name, "value": hexdump(param_value)}) <7>:<add> data[param_name] = param_value <del> data.append({"name": param_name, "value": str(param_value)})
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( + self, owner: str, parameters: QuicTransportParameters - self, parameters: QuicTransportParameters + ) -> Dict[str, Any]: - ) -> List[Dict]: <0> data = [] <1> for param_name, param_value in parameters.__dict__.items(): <2> if isinstance(param_value, bool): <3> data.append({"name": param_name, "value": param_value}) <4> elif isinstance(param_value, bytes): <5> data.append({"name": param_name, "value": hexdump(param_value)}) <6> elif isinstance(param_value, int): <7> data.append({"name": param_name, "value": str(param_value)}) <8> return data <9>
===========unchanged ref 0=========== at: aioquic.quic.packet QuicTransportParameters(original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_active_migration: Optional[bool]=False, preferred_address: Optional[QuicPreferredAddress]=None, active_connection_id_limit: Optional[int]=None) at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), }
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: <0> """ <1> Update metrics as the result of an ACK being received. <2> """ <3> is_ack_eliciting = False <4> largest_acked = ack_rangeset.bounds().stop - 1 <5> largest_newly_acked = None <6> largest_sent_time = None <7> <8> if largest_acked > space.largest_acked_packet: <9> space.largest_acked_packet = largest_acked <10> <11> for packet_number in sorted(space.sent_packets.keys()): <12> if packet_number > largest_acked: <13> break <14> if packet_number in ack_rangeset: <15> # remove packet and update counters <16> packet = space.sent_packets.pop(packet_number) <17> if packet.is_ack_eliciting: <18> is_ack_eliciting = True <19> space.ack_eliciting_in_flight -= 1 <20> if packet.in_flight: <21> self.on_packet_acked(packet) <22> largest_newly_acked = packet_number <23> largest_sent_time = packet.sent_time <24> <25> # trigger callbacks <26> for handler, args in packet.delivery_handlers: <27> handler(QuicDeliveryState.ACKED, *args) <28> <29> # nothing to do if there are no newly acked packets <30> if largest_newly_acked is None: <31> return <32> <33> if largest_acked == largest_newly_acked and is_ack_eliciting: <34> latest_rtt = now - largest_sent_time <35> <36> # limit ACK delay to max_ack_delay <37> ack_delay = min(ack_delay, self.max_ack_delay) <38> </s>
===========below chunk 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", event="metric_update", data={ "latest_rtt": int(self._rtt_latest * 1000), "min_rtt": int(self._rtt_min * 1000), "smoothed_rtt": int(self._rtt_smoothed * 1000), "rtt_variance": int(self._rtt_variance * 1000), }, ) self.detect_loss(space, now=now) self._pto_count = 0 ===========unchanged ref 0=========== at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None at: aioquic.quic.packet_builder QuicDeliveryState() at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: aioquic.quic.rangeset RangeSet(ranges: Iterable[range]=[]) at: aioquic.quic.rangeset.RangeSet bounds() -> range at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery detect_loss(space: QuicPacketSpace, now: float) -> None on_packet_acked(packet: QuicSentPacket) -> None on_packet_acked(self, packet: QuicSentPacket) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 self._quic_logger = quic_logger self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.largest_acked_packet = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( + self, owner: str, parameters: QuicTransportParameters - self, parameters: QuicTransportParameters + ) -> Dict[str, Any]: - ) -> List[Dict]: + data: Dict[str, Any] = {"owner": owner} - data = [] for param_name, param_value in parameters.__dict__.items(): if isinstance(param_value, bool): + data[param_name] = param_value - data.append({"name": param_name, "value": param_value}) elif isinstance(param_value, bytes): + data[param_name] = param_value - data.append({"name": param_name, "value": hexdump(param_value)}) elif isinstance(param_value, int): + data[param_name] = param_value - data.append({"name": param_name, "value": str(param_value)}) return data
aioquic.quic.recovery/QuicPacketRecovery.on_packet_acked
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<16>:<add> self._log_metrics_updated() <del> self._log_metric_update()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: <0> self.bytes_in_flight -= packet.sent_bytes <1> <2> # don't increase window in congestion recovery <3> if packet.sent_time <= self._congestion_recovery_start_time: <4> return <5> <6> if self._ssthresh is None or self.congestion_window < self._ssthresh: <7> # slow start <8> self.congestion_window += packet.sent_bytes <9> else: <10> # congestion avoidance <11> self.congestion_window += ( <12> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window <13> ) <14> <15> if self._quic_logger is not None: <16> self._log_metric_update() <17>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.quic.recovery K_MAX_DATAGRAM_SIZE = 1280 at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated() -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now ===========unchanged ref 1=========== self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._</s> ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 <s> cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", + event="metrics_updated", - event="metric_update", data={ "latest_rtt": int(self._rtt_latest * 1000), "min_rtt": int(self._rtt_min * 1000), "smoothed_rtt": int(self._rtt_smoothed * 1000), "rtt_variance": int(self._rtt_variance * 1000), }, ) self.detect_loss(space, now=now) self._pto_count = 0 ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), }
aioquic.quic.recovery/QuicPacketRecovery.on_packet_expired
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<3>:<add> self._log_metrics_updated() <del> self._log_metric_update()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: <0> self.bytes_in_flight -= packet.sent_bytes <1> <2> if self._quic_logger is not None: <3> self._log_metric_update() <4>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket sent_bytes: int = 0 at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated() -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self.bytes_in_flight = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._</s> ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 <s> cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", + event="metrics_updated", - event="metric_update", data={ "latest_rtt": int(self._rtt_latest * 1000), "min_rtt": int(self._rtt_min * 1000), "smoothed_rtt": int(self._rtt_smoothed * 1000), "rtt_variance": int(self._rtt_variance * 1000), }, ) self.detect_loss(space, now=now) self._pto_count = 0 ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), }
aioquic.quic.recovery/QuicPacketRecovery.on_packet_lost
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<16>:<add> self._log_metrics_updated() <del> self._log_metric_update()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: <0> del space.sent_packets[packet.packet_number] <1> <2> if packet.is_ack_eliciting: <3> space.ack_eliciting_in_flight -= 1 <4> if packet.in_flight: <5> self.bytes_in_flight -= packet.sent_bytes <6> <7> if self._quic_logger is not None: <8> self._quic_logger.log_event( <9> category="recovery", <10> event="packet_lost", <11> data={ <12> "type": self._quic_logger.packet_type(packet.packet_type), <13> "packet_number": str(packet.packet_number), <14> }, <15> ) <16> self._log_metric_update() <17> <18> # trigger callbacks <19> for handler, args in packet.delivery_handlers: <20> handler(QuicDeliveryState.LOST, *args) <21>
===========unchanged ref 0=========== at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None packet_type(packet_type: int) -> str at: aioquic.quic.packet_builder QuicDeliveryState() QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket in_flight: bool is_ack_eliciting: bool packet_number: int packet_type: int sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated() -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self.bytes_in_flight = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._</s> ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 <s> cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", + event="metrics_updated", - event="metric_update", data={ "latest_rtt": int(self._rtt_latest * 1000), "min_rtt": int(self._rtt_min * 1000), "smoothed_rtt": int(self._rtt_smoothed * 1000), "rtt_variance": int(self._rtt_variance * 1000), }, ) self.detect_loss(space, now=now) self._pto_count = 0 ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), }
aioquic.quic.recovery/QuicPacketRecovery.on_packet_sent
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<12>:<add> self._log_metrics_updated() <del> self._log_metric_update()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: <0> space.sent_packets[packet.packet_number] = packet <1> <2> if packet.is_ack_eliciting: <3> space.ack_eliciting_in_flight += 1 <4> if packet.in_flight: <5> if packet.is_ack_eliciting: <6> self._time_of_last_sent_ack_eliciting_packet = packet.sent_time <7> <8> # add packet to bytes in flight <9> self.bytes_in_flight += packet.sent_bytes <10> <11> if self._quic_logger is not None: <12> self._log_metric_update() <13>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket in_flight: bool is_ack_eliciting: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated() -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self._time_of_last_sent_ack_eliciting_packet = 0.0 self.bytes_in_flight = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: del space.sent_packets[packet.packet_number] if packet.is_ack_eliciting: space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", event="packet_lost", data={ "type": self._quic_logger.packet_type(packet.packet_type), "packet_number": str(packet.packet_number), }, ) + self._log_metrics_updated() - self._log_metric_update() # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.LOST, *args) ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._</s>
aioquic.quic.recovery/QuicPacketRecovery.on_packets_lost
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<10>:<add> self._log_metrics_updated() <del> self._log_metric_update()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packets_lost(self, lost_largest_time: float, now: float) -> None: <0> # start a new congestion event if packet was sent after the <1> # start of the previous congestion recovery period. <2> if lost_largest_time > self._congestion_recovery_start_time: <3> self._congestion_recovery_start_time = now <4> self.congestion_window = max( <5> int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW <6> ) <7> self._ssthresh = self.congestion_window <8> <9> if self._quic_logger is not None: <10> self._log_metric_update() <11>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated() -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) self.congestion_window += packet.sent_bytes ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 if packet.in_flight: if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self.bytes_in_flight += packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: del space.sent_packets[packet.packet_number] if packet.is_ack_eliciting: space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", event="packet_lost", data={ "type": self._quic_logger.packet_type(packet.packet_type), "packet_number": str(packet.packet_number), }, ) + self._log_metrics_updated() - self._log_metric_update() # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.LOST, *args) ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 4=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._</s>
aioquic.quic.connection/QuicConnection.datagrams_to_send
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
# module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: <0> """ <1> Return a list of `(data, addr)` tuples of datagrams which need to be <2> sent, and the network address to which they need to be sent. <3> <4> :param now: The current time. <5> """ <6> network_path = self._network_paths[0] <7> <8> if self._state in END_STATES: <9> return [] <10> <11> # build datagrams <12> builder = QuicPacketBuilder( <13> host_cid=self.host_cid, <14> packet_number=self._packet_number, <15> pad_first_datagram=( <16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT <17> ), <18> peer_cid=self._peer_cid, <19> peer_token=self._peer_token, <20> quic_logger=self._quic_logger, <21> spin_bit=self._spin_bit, <22> version=self._version, <23> ) <24> if self._close_pending: <25> for epoch, packet_type in ( <26> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT), <27> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE), <28> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL), <29> ): <30> crypto = self._cryptos[epoch] <31> if crypto.send.is_valid(): <32> builder.start_packet(packet_type, crypto) <33> self._write_close_frame( <34> builder=builder, <35> error_code=self._close_event.error_code, <36> frame_type=self._close_event.frame_type, <37> reason_phrase=self._close_event.reason_phrase, <38> ) <39> builder.end_packet() <40> self._close_pending = False <41> break</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 1 else: # congestion control builder.max_flight_bytes = ( self._loss.congestion_window - self._loss.bytes_in_flight ) if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE: builder.max_flight_bytes = PACKET_MAX_SIZE # limit data on un-validated network paths if not network_path.is_validated: builder.max_total_bytes = ( network_path.bytes_received * 3 - network_path.bytes_sent ) try: if not self._handshake_confirmed: for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]: self._write_handshake(builder, epoch) self._write_application(builder, network_path, now) except QuicPacketBuilderStop: pass datagrams, packets = builder.flush() if datagrams: self._packet_number = builder.packet_number # register packets sent_handshake = False for packet in packets: packet.sent_time = now self._loss.on_packet_sent( packet=packet, space=self._spaces[packet.epoch] ) if packet.epoch == tls.Epoch.HANDSHAKE: sent_handshake = True # log packet if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="packet_sent", data={ "packet_type": self._quic_logger.packet_type( packet.packet_type ), "header": { "packet_number": str(packet.packet_number), "packet_size": packet.sent_bytes, "scid": dump_</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 2 <s>": str(packet.packet_number), "packet_size": packet.sent_bytes, "scid": dump_cid(self.host_cid) if is_long_header(packet.packet_type) else "", "dcid": dump_cid(self._peer_cid), }, "frames": packet.quic_logger_frames, }, ) # check if we can discard initial keys if sent_handshake and self._is_client: self._discard_epoch(tls.Epoch.INITIAL) # return datagrams to send and the destination network address ret = [] for datagram in datagrams: byte_length = len(datagram) network_path.bytes_sent += byte_length ret.append((datagram, network_path.addr)) if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="datagram_sent", data={"byte_length": byte_length, "count": 1}, ) return ret ===========unchanged ref 0=========== at: aioquic.quic.connection NetworkAddress = Any dump_cid(cid: bytes) -> str QuicConnectionState() END_STATES = frozenset( [ QuicConnectionState.CLOSING, QuicConnectionState.DRAINING, QuicConnectionState.TERMINATED, ] ) at: aioquic.quic.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._close_event: Optional[events.ConnectionTerminated] = None self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self.host_cid = self._host_cids[0].cid self._network_paths: List[QuicNetworkPath] = [] self._packet_number = 0 self._peer_cid = os.urandom(configuration.connection_id_length) self._peer_token = b"" self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._spin_bit = False self._state = QuicConnectionState.FIRSTFLIGHT self._version: Optional[int] = None self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._close_pending = False self._probe_pending = False ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase ) at: aioquic.quic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._packet_number = 0 at: aioquic.quic.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.quic.connection.QuicConnection._set_state self._state = state at: aioquic.quic.connection.QuicConnection._write_application self._probe_pending = False at: aioquic.quic.connection.QuicConnection._write_handshake self._probe_pending = False at: aioquic.quic.connection.QuicConnection.change_connection_id self._peer_cid = connection_id.cid at: aioquic.quic.connection.QuicConnection.close self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase, ) self._close_pending = True at: aioquic.quic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] self._version = self._configuration.supported_versions[0]
aioquic.quic.connection/QuicConnection._parse_transport_parameters
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<6>:<add> event="parameters_set", <del> event="transport_parameters_update", <7>:<del> data={ <8>:<del> "owner": "remote", <9>:<add> data=self._quic_logger.encode_transport_parameters( <del> "parameters": self._quic_logger.encode_transport_parameters( <10>:<add> owner="remote", parameters=quic_transport_parameters <del> quic_transport_parameters <11>:<del> ), <12>:<add> ), <del> },
# module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: <0> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) <1> <2> # log event <3> if self._quic_logger is not None and not from_session_ticket: <4> self._quic_logger.log_event( <5> category="transport", <6> event="transport_parameters_update", <7> data={ <8> "owner": "remote", <9> "parameters": self._quic_logger.encode_transport_parameters( <10> quic_transport_parameters <11> ), <12> }, <13> ) <14> <15> # validate remote parameters <16> if ( <17> self._is_client <18> and not from_session_ticket <19> and ( <20> quic_transport_parameters.original_connection_id <21> != self._original_connection_id <22> ) <23> ): <24> raise QuicConnectionError( <25> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, <26> frame_type=QuicFrameType.CRYPTO, <27> reason_phrase="original_connection_id does not match", <28> ) <29> <30> # store remote parameters <31> if quic_transport_parameters.ack_delay_exponent is not None: <32> self._remote_ack_delay_exponent = self._remote_ack_delay_exponent <33> if quic_transport_parameters.active_connection_id_limit is not None: <34> self._remote_active_connection_id_limit = ( <35> quic_transport_parameters.active_connection_id_limit <36> ) <37> if quic_transport_parameters.idle_timeout is not None: <38> self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0 <39> if quic_transport_parameters.max_ack_delay is not None: <40> self._loss.max_ack_delay = qu</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: # offset: 1 for param in [ "max_data", "max_stream_data_bidi_local", "max_stream_data_bidi_remote", "max_stream_data_uni", "max_streams_bidi", "max_streams_uni", ]: value = getattr(quic_transport_parameters, "initial_" + param) if value is not None: setattr(self, "_remote_" + param, value) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._original_connection_id = original_connection_id self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._remote_ack_delay_exponent = 3 self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid at: aioquic.quic.logger.QuicLoggerTrace encode_transport_parameters(owner: str, parameters: QuicTransportParameters) -> Dict[str, Any] log_event(*, category: str, event: str, data: Dict) -> None at: aioquic.quic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========unchanged ref 1=========== QuicTransportParameters(original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_active_migration: Optional[bool]=False, preferred_address: Optional[QuicPreferredAddress]=None, active_connection_id_limit: Optional[int]=None) pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.quic.packet.QuicTransportParameters original_connection_id: Optional[bytes] = None idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None ===========unchanged ref 2=========== max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( + self, owner: str, parameters: QuicTransportParameters - self, parameters: QuicTransportParameters + ) -> Dict[str, Any]: - ) -> List[Dict]: + data: Dict[str, Any] = {"owner": owner} - data = [] for param_name, param_value in parameters.__dict__.items(): if isinstance(param_value, bool): + data[param_name] = param_value - data.append({"name": param_name, "value": param_value}) elif isinstance(param_value, bytes): + data[param_name] = param_value - data.append({"name": param_name, "value": hexdump(param_value)}) elif isinstance(param_value, int): + data[param_name] = param_value - data.append({"name": param_name, "value": str(param_value)}) return data ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), }
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<21>:<add> event="parameters_set", <del> event="transport_parameters_update", <22>:<del> data={ <23>:<del> "owner": "local", <24>:<add> data=self._quic_logger.encode_transport_parameters( <del> "parameters": self._quic_logger.encode_transport_parameters( <25>:<add> owner="local", parameters=quic_transport_parameters <del> quic_transport_parameters <26>:<del> ), <27>:<add> ), <del> },
# module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: <0> quic_transport_parameters = QuicTransportParameters( <1> ack_delay_exponent=self._local_ack_delay_exponent, <2> active_connection_id_limit=self._local_active_connection_id_limit, <3> idle_timeout=int(self._configuration.idle_timeout * 1000), <4> initial_max_data=self._local_max_data, <5> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local, <6> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote, <7> initial_max_stream_data_uni=self._local_max_stream_data_uni, <8> initial_max_streams_bidi=self._local_max_streams_bidi, <9> initial_max_streams_uni=self._local_max_streams_uni, <10> max_ack_delay=25, <11> ) <12> if not self._is_client: <13> quic_transport_parameters.original_connection_id = ( <14> self._original_connection_id <15> ) <16> <17> # log event <18> if self._quic_logger is not None: <19> self._quic_logger.log_event( <20> category="transport", <21> event="transport_parameters_update", <22> data={ <23> "owner": "local", <24> "parameters": self._quic_logger.encode_transport_parameters( <25> quic_transport_parameters <26> ), <27> }, <28> ) <29> <30> buf = Buffer(capacity=512) <31> push_quic_transport_parameters(buf, quic_transport_parameters) <32> return buf.data <33>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.connection QuicConnectionState() at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._original_connection_id = original_connection_id ===========unchanged ref 1=========== self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._state = QuicConnectionState.FIRSTFLIGHT self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._serialize_transport_parameters quic_transport_parameters = QuicTransportParameters( ack_delay_exponent=self._local_ack_delay_exponent, active_connection_id_limit=self._local_active_connection_id_limit, idle_timeout=int(self._configuration.idle_timeout * 1000), initial_max_data=self._local_max_data, initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local, initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote, initial_max_stream_data_uni=self._local_max_stream_data_uni, initial_max_streams_bidi=self._local_max_streams_bidi, initial_max_streams_uni=self._local_max_streams_uni, max_ack_delay=25, ) at: aioquic.quic.connection.QuicConnection._write_connection_limits self._local_max_data *= 2 at: aioquic.quic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None ===========unchanged ref 2=========== at: aioquic.quic.packet push_quic_transport_parameters(buf: Buffer, params: QuicTransportParameters) -> None at: aioquic.quic.packet.QuicTransportParameters original_connection_id: Optional[bytes] = None ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) # log event if self._quic_logger is not None and not from_session_ticket: self._quic_logger.log_event( category="transport", + event="parameters_set", - event="transport_parameters_update", - data={ - "owner": "remote", + data=self._quic_logger.encode_transport_parameters( - "parameters": self._quic_logger.encode_transport_parameters( + owner="remote", parameters=quic_transport_parameters - quic_transport_parameters - ), + ), - }, ) # validate remote parameters if ( self._is_client and not from_session_ticket and ( quic_transport_parameters.original_connection_id != self._original_connection_id ) ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="original_connection_id does not match", ) # store remote parameters if quic_transport_parameters.ack_delay_exponent is not None: self._remote_ack_delay_exponent = self._remote_ack_delay_exponent if quic_transport_parameters.active_connection_id_limit is not None: self._remote_active_connection_id_limit = ( quic_transport_parameters.active_connection_id_limit ) if quic_transport_parameters.idle_timeout is not None: self._remote_idle_timeout = quic_transport_parameters.idle_timeout / 1000.0 if quic_transport_parameters.max_ack_delay is not None:</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: # offset: 1 <s>transport_parameters.idle_timeout / 1000.0 if quic_transport_parameters.max_ack_delay is not None: self._loss.max_ack_delay = quic_transport_parameters.max_ack_delay / 1000.0 for param in [ "max_data", "max_stream_data_bidi_local", "max_stream_data_bidi_remote", "max_stream_data_uni", "max_streams_bidi", "max_streams_uni", ]: value = getattr(quic_transport_parameters, "initial_" + param) if value is not None: setattr(self, "_remote_" + param, value) ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update()
aioquic.h3.connection/qlog_encode_headers_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<2>:<add> "frame": {"frame_type": "headers", "headers": qlog_encode_headers(headers)}, <del> "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)},
# module: aioquic.h3.connection def qlog_encode_headers_frame( byte_length: int, headers: Headers, stream_id: int ) -> Dict: <0> return { <1> "byte_length": str(byte_length), <2> "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)}, <3> "stream_id": str(stream_id), <4> } <5>
===========unchanged ref 0=========== at: aioquic.h3.connection qlog_encode_headers(headers: Headers) -> List[Dict] at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 6=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 7=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 if packet.in_flight: if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self.bytes_in_flight += packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 8=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packets_lost(self, lost_largest_time: float, now: float) -> None: # start a new congestion event if packet was sent after the # start of the previous congestion recovery period. if lost_largest_time > self._congestion_recovery_start_time: self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 9=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( + self, owner: str, parameters: QuicTransportParameters - self, parameters: QuicTransportParameters + ) -> Dict[str, Any]: - ) -> List[Dict]: + data: Dict[str, Any] = {"owner": owner} - data = [] for param_name, param_value in parameters.__dict__.items(): if isinstance(param_value, bool): + data[param_name] = param_value - data.append({"name": param_name, "value": param_value}) elif isinstance(param_value, bytes): + data[param_name] = param_value - data.append({"name": param_name, "value": hexdump(param_value)}) elif isinstance(param_value, int): + data[param_name] = param_value - data.append({"name": param_name, "value": str(param_value)}) return data ===========changed ref 10=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update()
aioquic.h3.connection/qlog_encode_push_promise_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<4>:<add> "headers": qlog_encode_headers(headers), <del> "field": qlog_encode_headers(headers), <5>:<add> "push_id": str(push_id), <del> "id": str(push_id),
# module: aioquic.h3.connection def qlog_encode_push_promise_frame( byte_length: int, headers: Headers, push_id: int, stream_id: int ) -> Dict: <0> return { <1> "byte_length": str(byte_length), <2> "frame": { <3> "frame_type": "push_promise", <4> "field": qlog_encode_headers(headers), <5> "id": str(push_id), <6> }, <7> "stream_id": str(stream_id), <8> } <9>
===========unchanged ref 0=========== at: aioquic.h3.connection qlog_encode_headers(headers: Headers) -> List[Dict] at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.h3.connection def qlog_encode_headers_frame( byte_length: int, headers: Headers, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), + "frame": {"frame_type": "headers", "headers": qlog_encode_headers(headers)}, - "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)}, "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 6=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 7=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 8=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 if packet.in_flight: if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self.bytes_in_flight += packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 9=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packets_lost(self, lost_largest_time: float, now: float) -> None: # start a new congestion event if packet was sent after the # start of the previous congestion recovery period. if lost_largest_time > self._congestion_recovery_start_time: self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 10=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( + self, owner: str, parameters: QuicTransportParameters - self, parameters: QuicTransportParameters + ) -> Dict[str, Any]: - ) -> List[Dict]: + data: Dict[str, Any] = {"owner": owner} - data = [] for param_name, param_value in parameters.__dict__.items(): if isinstance(param_value, bool): + data[param_name] = param_value - data.append({"name": param_name, "value": param_value}) elif isinstance(param_value, bytes): + data[param_name] = param_value - data.append({"name": param_name, "value": hexdump(param_value)}) elif isinstance(param_value, int): + data[param_name] = param_value - data.append({"name": param_name, "value": str(param_value)}) return data ===========changed ref 11=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update()
aioquic.h3.connection/H3Connection.send_data
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<19>:<add> category="http", <del> category="HTTP",
# module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: <0> """ <1> Send data on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> <7> :param stream_id: The stream ID on which to send the data. <8> :param data: The data to send. <9> :param end_stream: Whether to end the stream. <10> """ <11> # check DATA frame is allowed <12> stream = self._get_or_create_stream(stream_id) <13> if stream.headers_send_state != HeadersState.AFTER_HEADERS: <14> raise FrameUnexpected("DATA frame is not allowed in this state") <15> <16> # log frame <17> if self._quic_logger is not None: <18> self._quic_logger.log_event( <19> category="HTTP", <20> event="frame_created", <21> data=qlog_encode_data_frame(byte_length=len(data), stream_id=stream_id), <22> ) <23> <24> self._quic.send_stream_data( <25> stream_id, encode_frame(FrameType.DATA, data), end_stream <26> ) <27>
===========unchanged ref 0=========== at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HeadersState() FrameUnexpected(reason_phrase: str="") encode_frame(frame_type: int, frame_data: bytes) -> bytes qlog_encode_data_frame(byte_length: int, stream_id: int) -> Dict at: aioquic.h3.connection.H3Connection _get_or_create_stream(stream_id: int) -> H3Stream at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger at: aioquic.h3.connection.H3Stream.__init__ self.headers_send_state: HeadersState = HeadersState.INITIAL at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None ===========changed ref 0=========== # module: aioquic.h3.connection def qlog_encode_headers_frame( byte_length: int, headers: Headers, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), + "frame": {"frame_type": "headers", "headers": qlog_encode_headers(headers)}, - "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)}, "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.h3.connection def qlog_encode_push_promise_frame( byte_length: int, headers: Headers, push_id: int, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), "frame": { "frame_type": "push_promise", + "headers": qlog_encode_headers(headers), - "field": qlog_encode_headers(headers), + "push_id": str(push_id), - "id": str(push_id), }, "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 6=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 7=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 8=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 9=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_sent(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: space.sent_packets[packet.packet_number] = packet if packet.is_ack_eliciting: space.ack_eliciting_in_flight += 1 if packet.in_flight: if packet.is_ack_eliciting: self._time_of_last_sent_ack_eliciting_packet = packet.sent_time # add packet to bytes in flight self.bytes_in_flight += packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 10=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packets_lost(self, lost_largest_time: float, now: float) -> None: # start a new congestion event if packet was sent after the # start of the previous congestion recovery period. if lost_largest_time > self._congestion_recovery_start_time: self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update()
aioquic.h3.connection/H3Connection.send_headers
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<21>:<add> category="http", <del> category="HTTP",
# module: aioquic.h3.connection class H3Connection: def send_headers( self, stream_id: int, headers: Headers, end_stream: bool = False ) -> None: <0> """ <1> Send headers on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> <7> :param stream_id: The stream ID on which to send the headers. <8> :param headers: The HTTP headers to send. <9> :param end_stream: Whether to end the stream. <10> """ <11> # check HEADERS frame is allowed <12> stream = self._get_or_create_stream(stream_id) <13> if stream.headers_send_state == HeadersState.AFTER_TRAILERS: <14> raise FrameUnexpected("HEADERS frame is not allowed in this state") <15> <16> frame_data = self._encode_headers(stream_id, headers) <17> <18> # log frame <19> if self._quic_logger is not None: <20> self._quic_logger.log_event( <21> category="HTTP", <22> event="frame_created", <23> data=qlog_encode_headers_frame( <24> byte_length=len(frame_data), headers=headers, stream_id=stream_id <25> ), <26> ) <27> <28> # update state and send headers <29> if stream.headers_send_state == HeadersState.INITIAL: <30> stream.headers_send_state = HeadersState.AFTER_HEADERS <31> else: <32> stream.headers_send_state = HeadersState.AFTER_TRAILERS <33> self._quic.send_stream_data( <34> stream_id, encode_frame(FrameType.HEADERS, frame_data), end_stream <35> ) <36>
===========unchanged ref 0=========== at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HeadersState() FrameUnexpected(reason_phrase: str="") encode_frame(frame_type: int, frame_data: bytes) -> bytes qlog_encode_headers_frame(byte_length: int, headers: Headers, stream_id: int) -> Dict at: aioquic.h3.connection.H3Connection _encode_headers(stream_id: int, headers: Headers) -> bytes _get_or_create_stream(stream_id: int) -> H3Stream at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger at: aioquic.h3.connection.H3Stream.__init__ self.headers_send_state: HeadersState = HeadersState.INITIAL at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]] at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None ===========changed ref 0=========== # module: aioquic.h3.connection def qlog_encode_headers_frame( byte_length: int, headers: Headers, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), + "frame": {"frame_type": "headers", "headers": qlog_encode_headers(headers)}, - "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)}, "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.h3.connection def qlog_encode_push_promise_frame( byte_length: int, headers: Headers, push_id: int, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), "frame": { "frame_type": "push_promise", + "headers": qlog_encode_headers(headers), - "field": qlog_encode_headers(headers), + "push_id": str(push_id), - "id": str(push_id), }, "stream_id": str(stream_id), } ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def send_data(self, stream_id: int, data: bytes, end_stream: bool) -> None: """ Send data on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. :param stream_id: The stream ID on which to send the data. :param data: The data to send. :param end_stream: Whether to end the stream. """ # check DATA frame is allowed stream = self._get_or_create_stream(stream_id) if stream.headers_send_state != HeadersState.AFTER_HEADERS: raise FrameUnexpected("DATA frame is not allowed in this state") # log frame if self._quic_logger is not None: self._quic_logger.log_event( + category="http", - category="HTTP", event="frame_created", data=qlog_encode_data_frame(byte_length=len(data), stream_id=stream_id), ) self._quic.send_stream_data( stream_id, encode_frame(FrameType.DATA, data), end_stream ) ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_expired(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes if self._quic_logger is not None: + self._log_metrics_updated() - self._log_metric_update() ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_max_stream_data_frame(self, maximum: int, stream_id: int) -> Dict: return { "frame_type": "max_stream_data", - "id": str(stream_id), "maximum": str(maximum), + "stream_id": str(stream_id), } ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stop_sending_frame(self, error_code: int, stream_id: int) -> Dict: return { "frame_type": "stop_sending", - "id": str(stream_id), "error_code": error_code, + "stream_id": str(stream_id), } ===========changed ref 6=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_reset_stream_frame( self, error_code: int, final_size: int, stream_id: int ) -> Dict: return { "error_code": error_code, "final_size": str(final_size), "frame_type": "reset_stream", + "stream_id": str(stream_id), } ===========changed ref 7=========== # module: aioquic.quic.logger class QuicLoggerTrace: def encode_stream_frame(self, frame: QuicStreamFrame, stream_id: int) -> Dict: return { "fin": frame.fin, "frame_type": "stream", - "id": str(stream_id), "length": str(len(frame.data)), "offset": str(frame.offset), + "stream_id": str(stream_id), } ===========changed ref 8=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) - ===========changed ref 9=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - # TODO : collapse congestion window if persistent congestion - - def _log_metric_update(self) -> None: - data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} - if self._ssthresh is not None: - data["ssthresh"] = self._ssthresh - - self._quic_logger.log_event( - category="recovery", event="metric_update", data=data - ) -
aioquic.h3.connection/H3Connection._handle_request_or_push_frame
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
<30>:<add> category="http", <del> category="HTTP",
# module: aioquic.h3.connection class H3Connection: def _handle_request_or_push_frame( self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool, ) -> List[H3Event]: <0> """ <1> Handle a frame received on a request or push stream. <2> """ <3> http_events: List[H3Event] = [] <4> <5> if frame_type == FrameType.DATA: <6> # check DATA frame is allowed <7> if stream.headers_recv_state != HeadersState.AFTER_HEADERS: <8> raise FrameUnexpected("DATA frame is not allowed in this state") <9> <10> if stream_ended or frame_data: <11> http_events.append( <12> DataReceived( <13> data=frame_data, <14> push_id=stream.push_id, <15> stream_ended=stream_ended, <16> stream_id=stream.stream_id, <17> ) <18> ) <19> elif frame_type == FrameType.HEADERS: <20> # check HEADERS frame is allowed <21> if stream.headers_recv_state == HeadersState.AFTER_TRAILERS: <22> raise FrameUnexpected("HEADERS frame is not allowed in this state") <23> <24> # try to decode HEADERS, may raise pylsqpack.StreamBlocked <25> headers = self._decode_headers(stream.stream_id, frame_data) <26> <27> # log frame <28> if self._quic_logger is not None: <29> self._quic_logger.log_event( <30> category="HTTP", <31> event="frame_parsed", <32> data=qlog_encode_headers_frame( <33> byte_length=stream.blocked_frame_size <34> if frame_data is None <35> else len(frame_data), <36> headers=headers, <37> stream_id=stream.stream_id, <38> ), <39> ) <40> <41> # update state and emit headers <42> if stream.headers_recv_state ==</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _handle_request_or_push_frame( self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool, ) -> List[H3Event]: # offset: 1 stream.headers_recv_state = HeadersState.AFTER_HEADERS else: stream.headers_recv_state = HeadersState.AFTER_TRAILERS http_events.append( HeadersReceived( headers=headers, push_id=stream.push_id, stream_id=stream.stream_id, stream_ended=stream_ended, ) ) elif stream.frame_type == FrameType.PUSH_PROMISE and stream.push_id is None: if not self._is_client: raise FrameUnexpected("Clients must not send PUSH_PROMISE") frame_buf = Buffer(data=frame_data) push_id = frame_buf.pull_uint_var() headers = self._decode_headers( stream.stream_id, frame_data[frame_buf.tell() :] ) # log frame if self._quic_logger is not None: self._quic_logger.log_event( category="HTTP", event="frame_parsed", data=qlog_encode_push_promise_frame( byte_length=len(frame_data), headers=headers, push_id=push_id, stream_id=stream.stream_id, ), ) # emit event http_events.append( PushPromiseReceived( headers=headers, push_id=push_id, stream_id=stream.stream_id ) ) elif frame_type in ( FrameType.PRIORITY, FrameType.CANCEL_PUSH, FrameType.SETTINGS, FrameType.PUSH_PROMISE, FrameType.GOAWAY, FrameType.MAX</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _handle_request_or_push_frame( self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool, ) -> List[H3Event]: # offset: 2 <s>Type.SETTINGS, FrameType.PUSH_PROMISE, FrameType.GOAWAY, FrameType.MAX_PUSH_ID, FrameType.DUPLICATE_PUSH, ): raise FrameUnexpected( "Invalid frame type on request stream" if stream.push_id is None else "Invalid frame type on push stream" ) return http_events ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer tell() -> int pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HeadersState() FrameUnexpected(reason_phrase: str="") qlog_encode_headers_frame(byte_length: int, headers: Headers, stream_id: int) -> Dict qlog_encode_push_promise_frame(byte_length: int, headers: Headers, push_id: int, stream_id: int) -> Dict H3Stream(stream_id: int) at: aioquic.h3.connection.H3Connection _decode_headers(stream_id: int, frame_data: Optional[bytes]) -> Headers at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger at: aioquic.h3.connection.H3Stream.__init__ self.blocked_frame_size: Optional[int] = None self.frame_type: Optional[int] = None self.headers_recv_state: HeadersState = HeadersState.INITIAL self.push_id: Optional[int] = None self.stream_id = stream_id at: aioquic.h3.events H3Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) HeadersReceived(headers: Headers, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) ===========unchanged ref 1=========== PushPromiseReceived(headers: Headers, push_id: int, stream_id: int) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool push_id: Optional[int] = None at: aioquic.h3.events.HeadersReceived headers: Headers stream_id: int stream_ended: bool push_id: Optional[int] = None at: aioquic.h3.events.PushPromiseReceived headers: Headers push_id: int stream_id: int at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection def qlog_encode_headers_frame( byte_length: int, headers: Headers, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), + "frame": {"frame_type": "headers", "headers": qlog_encode_headers(headers)}, - "frame": {"frame_type": "headers", "fields": qlog_encode_headers(headers)}, "stream_id": str(stream_id), } ===========changed ref 1=========== # module: aioquic.h3.connection def qlog_encode_push_promise_frame( byte_length: int, headers: Headers, push_id: int, stream_id: int ) -> Dict: return { "byte_length": str(byte_length), "frame": { "frame_type": "push_promise", + "headers": qlog_encode_headers(headers), - "field": qlog_encode_headers(headers), + "push_id": str(push_id), - "id": str(push_id), }, "stream_id": str(stream_id), }
aioquic.h3.connection/H3Connection._receive_request_or_push_data
Modified
aiortc~aioquic
48092046ff28d4369b88eef5c9a28e86428a1b91
[qlog] update logging for draft-01
# module: aioquic.h3.connection class H3Connection: def _receive_request_or_push_data( self, stream: H3Stream, data: bytes, stream_ended: bool ) -> List[H3Event]: <0> """ <1> Handle data received on a request or push stream. <2> """ <3> http_events: List[H3Event] = [] <4> <5> stream.buffer += data <6> if stream_ended: <7> stream.ended = True <8> if stream.blocked: <9> return http_events <10> <11> # shortcut for DATA frame fragments <12> if ( <13> stream.frame_type == FrameType.DATA <14> and stream.frame_size is not None <15> and len(stream.buffer) < stream.frame_size <16> ): <17> http_events.append( <18> DataReceived( <19> data=stream.buffer, <20> push_id=stream.push_id, <21> stream_id=stream.stream_id, <22> stream_ended=False, <23> ) <24> ) <25> stream.frame_size -= len(stream.buffer) <26> stream.buffer = b"" <27> return http_events <28> <29> # handle lone FIN <30> if stream_ended and not stream.buffer: <31> http_events.append( <32> DataReceived( <33> data=b"", <34> push_id=stream.push_id, <35> stream_id=stream.stream_id, <36> stream_ended=True, <37> ) <38> ) <39> return http_events <40> <41> buf = Buffer(data=stream.buffer) <42> consumed = 0 <43> <44> while not buf.eof(): <45> # fetch next frame header <46> if stream.frame_size is None: <47> try: <48> stream.frame_type = buf.pull_uint_var() <49> stream.frame_size = buf.pull_uint_var() <50> except BufferReadError: <51> break <52> consumed = buf.tell() <53> <54> </s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_request_or_push_data( self, stream: H3Stream, data: bytes, stream_ended: bool ) -> List[H3Event]: # offset: 1 if ( self._quic_logger is not None and stream.frame_type == FrameType.DATA ): self._quic_logger.log_event( category="HTTP", event="frame_parsed", data=qlog_encode_data_frame( byte_length=stream.frame_size, stream_id=stream.stream_id ), ) # check how much data is available chunk_size = min(stream.frame_size, buf.capacity - consumed) if stream.frame_type != FrameType.DATA and chunk_size < stream.frame_size: break # read available data frame_data = buf.pull_bytes(chunk_size) consumed = buf.tell() # detect end of frame stream.frame_size -= chunk_size if not stream.frame_size: stream.frame_size = None try: http_events.extend( self._handle_request_or_push_frame( frame_type=stream.frame_type, frame_data=frame_data, stream=stream, stream_ended=stream.ended and buf.eof(), ) ) except pylsqpack.StreamBlocked: stream.blocked = True stream.blocked_frame_size = len(frame_data) break # remove processed data from buffer stream.buffer = stream.buffer[consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) qlog_encode_data_frame(byte_length: int, stream_id: int) -> Dict H3Stream(stream_id: int) at: aioquic.h3.connection.H3Connection _handle_request_or_push_frame(self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool) -> List[H3Event] _handle_request_or_push_frame(frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool) -> List[H3Event] at: aioquic.h3.connection.H3Connection.__init__ self._quic_logger: Optional[QuicLoggerTrace] = quic._quic_logger at: aioquic.h3.connection.H3Stream.__init__ self.blocked = False self.blocked_frame_size: Optional[int] = None self.buffer = b"" self.ended = False self.frame_size: Optional[int] = None self.frame_type: Optional[int] = None self.push_id: Optional[int] = None self.stream_id = stream_id at: aioquic.h3.events H3Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) ===========unchanged ref 1=========== at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def _handle_request_or_push_frame( self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool, ) -> List[H3Event]: """ Handle a frame received on a request or push stream. """ http_events: List[H3Event] = [] if frame_type == FrameType.DATA: # check DATA frame is allowed if stream.headers_recv_state != HeadersState.AFTER_HEADERS: raise FrameUnexpected("DATA frame is not allowed in this state") if stream_ended or frame_data: http_events.append( DataReceived( data=frame_data, push_id=stream.push_id, stream_ended=stream_ended, stream_id=stream.stream_id, ) ) elif frame_type == FrameType.HEADERS: # check HEADERS frame is allowed if stream.headers_recv_state == HeadersState.AFTER_TRAILERS: raise FrameUnexpected("HEADERS frame is not allowed in this state") # try to decode HEADERS, may raise pylsqpack.StreamBlocked headers = self._decode_headers(stream.stream_id, frame_data) # log frame if self._quic_logger is not None: self._quic_logger.log_event( + category="http", - category="HTTP", event="frame_parsed", data=qlog_encode_headers_frame( byte_length=stream.blocked_frame_size if frame_data is None else len(frame_data), headers=headers, stream_id=stream.stream_id, ), ) # update state and emit headers if stream.headers_recv_state == HeadersState.INITIAL: stream.headers_recv_state = HeadersState.AFTER_HEADERS else: stream.headers_recv_state =</s> ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def _handle_request_or_push_frame( self, frame_type: int, frame_data: Optional[bytes], stream: H3Stream, stream_ended: bool, ) -> List[H3Event]: # offset: 1 <s> stream.headers_recv_state = HeadersState.AFTER_HEADERS else: stream.headers_recv_state = HeadersState.AFTER_TRAILERS http_events.append( HeadersReceived( headers=headers, push_id=stream.push_id, stream_id=stream.stream_id, stream_ended=stream_ended, ) ) elif stream.frame_type == FrameType.PUSH_PROMISE and stream.push_id is None: if not self._is_client: raise FrameUnexpected("Clients must not send PUSH_PROMISE") frame_buf = Buffer(data=frame_data) push_id = frame_buf.pull_uint_var() headers = self._decode_headers( stream.stream_id, frame_data[frame_buf.tell() :] ) # log frame if self._quic_logger is not None: self._quic_logger.log_event( + category="http", - category="HTTP", event="frame_parsed", data=qlog_encode_push_promise_frame( byte_length=len(frame_data), headers=headers, push_id=push_id, stream_id=stream.stream_id, ), ) # emit event http_events.append( PushPromiseReceived( headers=headers, push_id=push_id, stream_id=stream.stream_id ) ) elif frame_type in ( FrameType.PRIORITY,</s>
examples.interop/test_spin_bit
Modified
aiortc~aioquic
b53dc6d7d9e3cc335fed740c308d39e1237a0a53
[interop] fix test for spin bit
<11>:<add> if category == "connectivity" and event == "spin_bit_updated": <del> if category == "connectivity" and event == "spin_bit_update":
# module: examples.interop def test_spin_bit(server: Server, configuration: QuicConfiguration): <0> async with connect( <1> server.host, server.port, configuration=configuration <2> ) as protocol: <3> for i in range(5): <4> await protocol.ping() <5> <6> # check log <7> spin_bits = set() <8> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <9> "traces" <10> ][0]["events"]: <11> if category == "connectivity" and event == "spin_bit_update": <12> spin_bits.add(data["state"]) <13> if len(spin_bits) == 2: <14> server.result |= Result.P <15>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None ===========unchanged ref 1=========== certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.logger.QuicLogger to_dict() -> Dict[str, Any] at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) verify_mode: Optional[int] = None
examples.interop/test_session_resumption
Modified
aiortc~aioquic
4415360845e16e679349f434dc057865b26243a2
[interop] msquic does session resumption on a different port
<0>:<add> port = server.session_resumption_port or server.port <9>:<add> port, <del> server.port, <18>:<del> async with connect( <19>:<del> server.host, server.port, configuration=configuration <20>:<del> ) as protocol: <21>:<add> async with connect(server.host, port, configuration=configuration) as protocol:
# module: examples.interop def test_session_resumption(server: Server, configuration: QuicConfiguration): <0> saved_ticket = None <1> <2> def session_ticket_handler(ticket): <3> nonlocal saved_ticket <4> saved_ticket = ticket <5> <6> # connect a first time, receive a ticket <7> async with connect( <8> server.host, <9> server.port, <10> configuration=configuration, <11> session_ticket_handler=session_ticket_handler, <12> ) as protocol: <13> await protocol.ping() <14> <15> # connect a second time, with the ticket <16> if saved_ticket is not None: <17> configuration.session_ticket = saved_ticket <18> async with connect( <19> server.host, server.port, configuration=configuration <20> ) as protocol: <21> await protocol.ping() <22> <23> # check session was resumed <24> if protocol._quic.tls.session_resumed: <25> server.result |= Result.R <26> <27> # check early data was accepted <28> if protocol._quic.tls.early_data_accepted: <29> server.result |= Result.Z <30>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._quic = quic at: aioquic.h3.connection.H3Connection.__init__ self._encoder_bytes_sent = 0 at: aioquic.h3.connection.H3Connection._encode_headers self._encoder_bytes_sent += len(encoder) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True ===========unchanged ref 1=========== quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.quic.connection.QuicConnection._initialize self.tls = tls.Context( alpn_protocols=self._configuration.alpn_protocols, cadata=self._configuration.cadata, cafile=self._configuration.cafile, capath=self._configuration.capath, is_client=self._is_client, logger=self._logger, max_early_data=None if self._is_client else MAX_EARLY_DATA, server_name=self._configuration.server_name, verify_mode=self._configuration.verify_mode, ) at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), session_resumption_port: Optional[int]=None, verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" ===========unchanged ref 2=========== result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None verify_mode: Optional[int] = None at: examples.interop.test_http_3 http = cast(H3Connection, protocol._http) ===========changed ref 0=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) + session_resumption_port: Optional[int] = None verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("aioquic", "quic.aiortc.org", port=443), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com"), Server( + "msquic", + "quic.westus.cloudapp.azure.com", + port=443, + session_resumption_port=4433, + verify_mode=ssl.CERT_NONE, - "msquic", "quic.westus.cloudapp.azure.com", port=443, verify_mode=ssl.CERT_NONE ), Server("mvfst", "fb.mvfst.net"), Server("ngtcp2", "nghttp2.org"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), Server("pandora", "pandora.cm.in.tum.de"), Server("picoquic", "test.privateoctopus.com"), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=4433), Server("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quicly", "kazuhooku.com"), Server("quinn", "ralith.com"), ]
examples.interop/test_throughput
Modified
aiortc~aioquic
b536f9ee3bc45310337dff40d1a58f0879eabefd
[interop] msquic uses a .txt suffix for throughput files
<4>:<add> path = "/%d%s" % (size, server.throughput_file_suffix) <del> path = "/%d" % size
# module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): <0> failures = 0 <1> <2> for size in [5000000, 10000000]: <3> print("Testing %d bytes download" % size) <4> path = "/%d" % size <5> <6> # perform HTTP request over TCP <7> start = time.time() <8> response = requests.get("https://" + server.host + path, verify=False) <9> tcp_octets = len(response.content) <10> tcp_elapsed = time.time() - start <11> assert tcp_octets == size, "HTTP/TCP response size mismatch" <12> <13> # perform HTTP request over QUIC <14> if server.http3: <15> configuration.alpn_protocols = H3_ALPN <16> else: <17> configuration.alpn_protocols = H0_ALPN <18> start = time.time() <19> async with connect( <20> server.host, <21> server.port, <22> configuration=configuration, <23> create_protocol=HttpClient, <24> ) as protocol: <25> protocol = cast(HttpClient, protocol) <26> <27> http_events = await protocol.get( <28> "https://{}:{}{}".format(server.host, server.port, path) <29> ) <30> quic_elapsed = time.time() - start <31> quic_octets = 0 <32> for http_event in http_events: <33> if isinstance(http_event, DataReceived): <34> quic_octets += len(http_event.data) <35> assert quic_octets == size, "HTTP/QUIC response size mismatch" <36> <37> print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) <38> print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) <39> <40> if quic_elapsed > 1.1 * tcp_elapsed: <41> failures += 1 <42> print(" => FAIL") <43> else: <44> print(" => PASS") <45> <46> if failures == 0: <47> server</s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 ===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.h0.connection H0_ALPN = ["hq-23", "hq-22"] at: aioquic.h3.connection H3_ALPN = ["h3-23", "h3-22"] at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool, push_id: Optional[int]=None) at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True ===========unchanged ref 1=========== quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: examples.interop Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), session_resumption_port: Optional[int]=None, throughput_file_suffix: str="", verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: http3_client HttpClient(quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None, /, *, quic: QuicConnection, stream_handler: Optional[QuicStreamHandler]=None) at: http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] ===========unchanged ref 2=========== at: requests.api get(url: Union[Text, bytes], params: Optional[ Union[ SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], Tuple[_ParamsMappingKeyType, _ParamsMappingValueType], Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], Union[Text, bytes], ] ]=..., **kwargs) -> Response at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] at: time time() -> float at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None + throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("aioquic", "quic.aiortc.org", port=443), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com"), Server( "msquic", "quic.westus.cloudapp.azure.com", port=443, session_resumption_port=4433, + throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server("mvfst", "fb.mvfst.net"), Server("ngtcp2", "nghttp2.org"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), Server("pandora", "pandora.cm.in.tum.de"), Server("picoquic", "test.privateoctopus.com"), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=4433), Server("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quicly", "kazuhooku.com"), Server("quinn", "ralith.com"), ]
aioquic.tls/verify_certificate
Modified
aiortc~aioquic
7a3377dc7b90a1aefe083c4ea19354a04e1b98f8
[tls] update cryptography typings
<15>:<add> if isinstance(ext.value, x509.SubjectAlternativeName): <del> if ext.oid == x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME:
# module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: <0> # verify dates <1> now = utcnow() <2> if now < certificate.not_valid_before: <3> raise AlertCertificateExpired("Certificate is not valid yet") <4> if now > certificate.not_valid_after: <5> raise AlertCertificateExpired("Certificate is no longer valid") <6> <7> # verify subject <8> if server_name is not None: <9> subject = [] <10> subjectAltName: List[Tuple[str, str]] = [] <11> for attr in certificate.subject: <12> if attr.oid == x509.NameOID.COMMON_NAME: <13> subject.append((("commonName", attr.value),)) <14> for ext in certificate.extensions: <15> if ext.oid == x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME: <16> for name in ext.value: <17> if isinstance(name, x509.DNSName): <18> subjectAltName.append(("DNS", name.value)) <19> <20> try: <21> ssl.match_hostname( <22> {"subject": tuple(subject), "subjectAltName": tuple(subjectAltName)}, <23> server_name, <24> ) <25> except ssl.CertificateError as exc: <26> raise AlertBadCertificate("\n".join(exc.args)) from exc <27> <28> # verify certificate chain <29> store = lib.X509_STORE_new() <30> openssl_assert(store != ffi.NULL) <31> store = ffi.gc(store, lib.X509_STORE_free) <32> <33> # load default CAs <34> openssl_assert(lib.X509_STORE_set_default_paths(store)) <35> paths = ssl.get_default_verify_paths() <36> openssl_assert( <37> </s>
===========below chunk 0=========== # module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: # offset: 1 store, openssl_encode_path(paths.cafile), openssl_encode_path(paths.capath) ) ) # load extra CAs if cadata is not None: for cert in load_pem_x509_certificates(cadata): openssl_assert(lib.X509_STORE_add_cert(store, cert._x509)) if cafile is not None or capath is not None: openssl_assert( lib.X509_STORE_load_locations( store, openssl_encode_path(cafile), openssl_encode_path(capath) ) ) chain_stack = lib.sk_X509_new_null() openssl_assert(chain_stack != ffi.NULL) chain_stack = ffi.gc(chain_stack, lib.sk_X509_free) for cert in chain: openssl_assert(lib.sk_X509_push(chain_stack, cert._x509)) store_ctx = lib.X509_STORE_CTX_new() openssl_assert(store_ctx != ffi.NULL) store_ctx = ffi.gc(store_ctx, lib.X509_STORE_CTX_free) openssl_assert( lib.X509_STORE_CTX_init(store_ctx, store, certificate._x509, chain_stack) ) res = lib.X509_verify_cert(store_ctx) if not res: err = lib.X509_STORE_CTX_get_error(store_ctx) err_str = openssl_decode_string(lib.X509_verify_cert_error_string(err)) raise Alert</s> ===========below chunk 1=========== # module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: # offset: 2 <s> err_str = openssl_decode_string(lib.X509_verify_cert_error_string(err)) raise AlertBadCertificate(err_str) ===========unchanged ref 0=========== at: aioquic.tls ffi = binding.ffi lib = binding.lib utcnow = datetime.datetime.utcnow AlertBadCertificate(*args: object) AlertCertificateExpired(*args: object) load_pem_x509_certificates(data: bytes) -> List[x509.Certificate] openssl_assert(ok: bool) -> None openssl_encode_path(s: Optional[str]) -> Any at: ssl CertificateError = SSLCertVerificationError match_hostname(cert: _PeerCertRetType, hostname: str) -> None get_default_verify_paths() -> DefaultVerifyPaths at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def cert_x509_ptr(certificate: x509.Certificate) -> Any: + """ + Accessor for private attribute. + """ + return getattr(certificate, "_x509") +
aioquic.quic.configuration/QuicConfiguration.load_cert_chain
Modified
aiortc~aioquic
7a3377dc7b90a1aefe083c4ea19354a04e1b98f8
[tls] update cryptography typings
<10>:<add> self.private_key = load_pem_private_key( <del> self.private_key = load_pem_private_key(fp.read(), password=password) <11>:<add> fp.read(), <add> password=password.encode("utf8") <add> if isinstance(password, str) <add> else password, <add> )
# module: aioquic.quic.configuration @dataclass class QuicConfiguration: def load_cert_chain( self, certfile: PathLike, keyfile: Optional[PathLike] = None, + password: Optional[Union[bytes, str]] = None, - password: Optional[str] = None, ) -> None: <0> """ <1> Load a private key and the corresponding certificate. <2> """ <3> with open(certfile, "rb") as fp: <4> certificates = load_pem_x509_certificates(fp.read()) <5> self.certificate = certificates[0] <6> self.certificate_chain = certificates[1:] <7> <8> if keyfile is not None: <9> with open(keyfile, "rb") as fp: <10> self.private_key = load_pem_private_key(fp.read(), password=password) <11>
===========unchanged ref 0=========== at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_23, QuicProtocolVersion.DRAFT_22, ] ) verify_mode: Optional[int] = None at: aioquic.tls load_pem_private_key(data: bytes, password: Optional[bytes]) -> Union[dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey, rsa.RSAPrivateKey] load_pem_x509_certificates(data: bytes) -> List[x509.Certificate] at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr ===========changed ref 0=========== # module: aioquic.tls + def cert_x509_ptr(certificate: x509.Certificate) -> Any: + """ + Accessor for private attribute. + """ + return getattr(certificate, "_x509") + ===========changed ref 1=========== # module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: # verify dates now = utcnow() if now < certificate.not_valid_before: raise AlertCertificateExpired("Certificate is not valid yet") if now > certificate.not_valid_after: raise AlertCertificateExpired("Certificate is no longer valid") # verify subject if server_name is not None: subject = [] subjectAltName: List[Tuple[str, str]] = [] for attr in certificate.subject: if attr.oid == x509.NameOID.COMMON_NAME: subject.append((("commonName", attr.value),)) for ext in certificate.extensions: + if isinstance(ext.value, x509.SubjectAlternativeName): - if ext.oid == x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME: for name in ext.value: if isinstance(name, x509.DNSName): subjectAltName.append(("DNS", name.value)) try: ssl.match_hostname( {"subject": tuple(subject), "subjectAltName": tuple(subjectAltName)}, server_name, ) except ssl.CertificateError as exc: raise AlertBadCertificate("\n".join(exc.args)) from exc # verify certificate chain store = lib.X509_STORE_new() openssl_assert(store != ffi.NULL) store = ffi.gc(store, lib.X509_STORE_free) # load default CAs openssl_assert(lib.X509_STORE_set_default_paths(store)) paths = ssl.get_default_verify_paths() openssl_assert( lib.X509_STORE_load_locations( store, openssl_encode_path</s> ===========changed ref 2=========== # module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: # offset: 1 <s>paths() openssl_assert( lib.X509_STORE_load_locations( store, openssl_encode_path(paths.cafile), openssl_encode_path(paths.capath) ) ) # load extra CAs if cadata is not None: for cert in load_pem_x509_certificates(cadata): + openssl_assert(lib.X509_STORE_add_cert(store, cert_x509_ptr(cert))) - openssl_assert(lib.X509_STORE_add_cert(store, cert._x509)) if cafile is not None or capath is not None: openssl_assert( lib.X509_STORE_load_locations( store, openssl_encode_path(cafile), openssl_encode_path(capath) ) ) chain_stack = lib.sk_X509_new_null() openssl_assert(chain_stack != ffi.NULL) chain_stack = ffi.gc(chain_stack, lib.sk_X509_free) for cert in chain: + openssl_assert(lib.sk_X509_push(chain_stack, cert_x509_ptr(cert))) - openssl_assert(lib.sk_X509_push(chain_stack, cert._x509)) store_ctx = lib.X509_STORE_CTX_new() openssl_assert(store_ctx != ffi.NULL) store_ctx = ffi.gc(store_ctx, lib.X509_STORE_CTX_free)</s> ===========changed ref 3=========== # module: aioquic.tls def verify_certificate( certificate: x509.Certificate, chain: List[x509.Certificate] = [], server_name: Optional[str] = None, cadata: Optional[bytes] = None, cafile: Optional[str] = None, capath: Optional[str] = None, ) -> None: # offset: 2 <s> openssl_assert( + lib.X509_STORE_CTX_init( + store_ctx, store, cert_x509_ptr(certificate), chain_stack + ) - lib.X509_STORE_CTX_init(store_ctx, store, certificate._x509, chain_stack) ) res = lib.X509_verify_cert(store_ctx) if not res: err = lib.X509_STORE_CTX_get_error(store_ctx) err_str = openssl_decode_string(lib.X509_verify_cert_error_string(err)) raise AlertBadCertificate(err_str)
aioquic.quic.crypto/CryptoPair.setup_initial
Modified
aiortc~aioquic
046d019c64c392469f879812df85c8db2caf2e2d
Drop support for draft-22
<5>:<del> if version < QuicProtocolVersion.DRAFT_23: <6>:<del> initial_salt = INITIAL_SALT_DRAFT_22 <7>:<del> else: <8>:<del> initial_salt = INITIAL_SALT_DRAFT_23 <9>:<del> <11>:<add> initial_secret = hkdf_extract(algorithm, INITIAL_SALT_DRAFT_23, cid) <del> initial_secret = hkdf_extract(algorithm, initial_salt, cid)
# module: aioquic.quic.crypto class CryptoPair: def setup_initial(self, cid: bytes, is_client: bool, version: int) -> None: <0> if is_client: <1> recv_label, send_label = b"server in", b"client in" <2> else: <3> recv_label, send_label = b"client in", b"server in" <4> <5> if version < QuicProtocolVersion.DRAFT_23: <6> initial_salt = INITIAL_SALT_DRAFT_22 <7> else: <8> initial_salt = INITIAL_SALT_DRAFT_23 <9> <10> algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) <11> initial_secret = hkdf_extract(algorithm, initial_salt, cid) <12> self.recv.setup( <13> INITIAL_CIPHER_SUITE, <14> hkdf_expand_label( <15> algorithm, initial_secret, recv_label, b"", algorithm.digest_size <16> ), <17> ) <18> self.send.setup( <19> INITIAL_CIPHER_SUITE, <20> hkdf_expand_label( <21> algorithm, initial_secret, send_label, b"", algorithm.digest_size <22> ), <23> ) <24>
===========unchanged ref 0=========== at: aioquic.quic.crypto INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 INITIAL_SALT_DRAFT_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") at: aioquic.quic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes) -> None teardown() -> None at: aioquic.quic.crypto.CryptoPair.__init__ self.recv = CryptoContext() self.send = CryptoContext() at: aioquic.tls hkdf_expand_label(algorithm: hashes.HashAlgorithm, secret: bytes, label: bytes, hash_value: bytes, length: int) -> bytes hkdf_extract(algorithm: hashes.HashAlgorithm, salt: bytes, key_material: bytes) -> bytes cipher_suite_hash(cipher_suite: CipherSuite) -> hashes.HashAlgorithm ===========changed ref 0=========== # module: aioquic.quic.crypto CIPHER_SUITES = { CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"), CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"), CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"), } INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 - INITIAL_SALT_DRAFT_22 = binascii.unhexlify("7fbcdb0e7c66bbe9193a96cd21519ebd7a02644a") INITIAL_SALT_DRAFT_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") SAMPLE_SIZE = 16
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
046d019c64c392469f879812df85c8db2caf2e2d
Drop support for draft-22
<0>:<del> configuration.supported_versions = [ <1>:<del> 0x1A2A3A4A, <2>:<del> QuicProtocolVersion.DRAFT_23, <3>:<del> QuicProtocolVersion.DRAFT_22, <4>:<del> ] <5>:<add> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_23]
# module: examples.interop def test_version_negotiation(server: Server, configuration: QuicConfiguration): <0> configuration.supported_versions = [ <1> 0x1A2A3A4A, <2> QuicProtocolVersion.DRAFT_23, <3> QuicProtocolVersion.DRAFT_22, <4> ] <5> <6> async with connect( <7> server.host, server.port, configuration=configuration <8> ) as protocol: <9> await protocol.ping() <10> <11> # check log <12> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <13> "traces" <14> ][0]["events"]: <15> if ( <16> category == "transport" <17> and event == "packet_received" <18> and data["packet_type"] == "version_negotiation" <19> ): <20> server.result |= Result.V <21>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(host: str, port: int, *, configuration: Optional[QuicConfiguration]=None, create_protocol: Optional[Callable]=QuicConnectionProtocol, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] connect(*args, **kwds) at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, connection_id_length: int=8, idle_timeout: float=60.0, is_client: bool=True, quic_logger: Optional[QuicLogger]=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, cadata: Optional[bytes]=None, cafile: Optional[str]=None, capath: Optional[str]=None, certificate: Any=None, certificate_chain: List[Any]=field(default_factory=list), private_key: Any=None, supported_versions: List[int]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_23] ), verify_mode: Optional[int]=None) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None connection_id_length: int = 8 idle_timeout: float = 60.0 is_client: bool = True quic_logger: Optional[QuicLogger] = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None ===========unchanged ref 1=========== certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_23] ) verify_mode: Optional[int] = None at: aioquic.quic.logger.QuicLogger to_dict() -> Dict[str, Any] at: aioquic.quic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), session_resumption_port: Optional[int]=None, throughput_file_suffix: str="", verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 0=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( - default_factory=lambda: [ - QuicProtocolVersion.DRAFT_23, - QuicProtocolVersion.DRAFT_22, - ] + default_factory=lambda: [QuicProtocolVersion.DRAFT_23] ) verify_mode: Optional[int] = None ===========changed ref 1=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-23"] - H0_ALPN = ["hq-23", "hq-22"] ===========changed ref 2=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-23"] - H3_ALPN = ["h3-23", "h3-22"] ===========changed ref 3=========== # module: aioquic.quic.crypto CIPHER_SUITES = { CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"), CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"), CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"), } INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 - INITIAL_SALT_DRAFT_22 = binascii.unhexlify("7fbcdb0e7c66bbe9193a96cd21519ebd7a02644a") INITIAL_SALT_DRAFT_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") SAMPLE_SIZE = 16
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
Modified
aiortc~aioquic
78ed75e0b3b05c4e06a0f83630256d2da8831b9e
[qlog] ensure metrics_updated is logged in congestion recovery
<35>:<add> log_rtt = True
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: <0> """ <1> Update metrics as the result of an ACK being received. <2> """ <3> is_ack_eliciting = False <4> largest_acked = ack_rangeset.bounds().stop - 1 <5> largest_newly_acked = None <6> largest_sent_time = None <7> <8> if largest_acked > space.largest_acked_packet: <9> space.largest_acked_packet = largest_acked <10> <11> for packet_number in sorted(space.sent_packets.keys()): <12> if packet_number > largest_acked: <13> break <14> if packet_number in ack_rangeset: <15> # remove packet and update counters <16> packet = space.sent_packets.pop(packet_number) <17> if packet.is_ack_eliciting: <18> is_ack_eliciting = True <19> space.ack_eliciting_in_flight -= 1 <20> if packet.in_flight: <21> self.on_packet_acked(packet) <22> largest_newly_acked = packet_number <23> largest_sent_time = packet.sent_time <24> <25> # trigger callbacks <26> for handler, args in packet.delivery_handlers: <27> handler(QuicDeliveryState.ACKED, *args) <28> <29> # nothing to do if there are no newly acked packets <30> if largest_newly_acked is None: <31> return <32> <33> if largest_acked == largest_newly_acked and is_ack_eliciting: <34> latest_rtt = now - largest_sent_time <35> <36> # limit ACK delay to max_ack_delay <37> ack_delay = min(ack_delay, self.max_ack_delay) <38> </s>
===========below chunk 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) if self._quic_logger is not None: self._quic_logger.log_event( category="recovery", event="metrics_updated", data={ "latest_rtt": int(self._rtt_latest * 1000), "min_rtt": int(self._rtt_min * 1000), "smoothed_rtt": int(self._rtt_smoothed * 1000), "rtt_variance": int(self._rtt_variance * 1000), }, ) self.detect_loss(space, now=now) self._pto_count = 0 ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryState() at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: aioquic.quic.rangeset RangeSet(ranges: Iterable[range]=[]) at: aioquic.quic.rangeset.RangeSet bounds() -> range at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery detect_loss(space: QuicPacketSpace, now: float) -> None get_earliest_loss_time() -> Optional[QuicPacketSpace] on_packet_acked(packet: QuicSentPacket) -> None _log_metrics_updated(log_rtt=False) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 self._quic_logger = quic_logger self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.largest_acked_packet = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]
aioquic.quic.recovery/QuicPacketRecovery.on_packet_acked
Modified
aiortc~aioquic
78ed75e0b3b05c4e06a0f83630256d2da8831b9e
[qlog] ensure metrics_updated is logged in congestion recovery
<15>:<del> if self._quic_logger is not None: <16>:<del> self._log_metrics_updated() <17>:<del>
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: <0> self.bytes_in_flight -= packet.sent_bytes <1> <2> # don't increase window in congestion recovery <3> if packet.sent_time <= self._congestion_recovery_start_time: <4> return <5> <6> if self._ssthresh is None or self.congestion_window < self._ssthresh: <7> # slow start <8> self.congestion_window += packet.sent_bytes <9> else: <10> # congestion avoidance <11> self.congestion_window += ( <12> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window <13> ) <14> <15> if self._quic_logger is not None: <16> self._log_metrics_updated() <17>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket packet_number: int sent_bytes: int = 0 at: aioquic.quic.recovery K_MAX_DATAGRAM_SIZE = 1280 QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery _log_metrics_updated(log_rtt=False) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time + log_rtt = True # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt,</s> ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 <s> # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) - - if self._quic_logger is not None: - self._quic_logger.log_event( - category="recovery", - event="metrics_updated", - data={ - "latest_rtt": int(self._rtt_latest * 1000), - "min_rtt": int(self._rtt_min * 1000), - "smoothed_rtt": int(self._rtt_smoothed * 1000), - "rtt_variance": int(self._rtt_variance * 1000), - }, - ) + else: + log_rtt = False self.detect_loss(space,</s> ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 2 <s>now) + if self._quic_logger is not None: + self._log_metrics_updated(log_rtt=log_rtt) + self._pto_count = 0
aioquic.quic.recovery/QuicPacketRecovery._log_metrics_updated
Modified
aiortc~aioquic
78ed75e0b3b05c4e06a0f83630256d2da8831b9e
[qlog] ensure metrics_updated is logged in congestion recovery
<3>:<add> <add> if log_rtt: <add> data.update( <add> { <add> "latest_rtt": int(self._rtt_latest * 1000), <add> "min_rtt": int(self._rtt_min * 1000), <add> "smoothed_rtt": int(self._rtt_smoothed * 1000), <add> "rtt_variance": int(self._rtt_variance * 1000), <add> } <add> )
# module: aioquic.quic.recovery class QuicPacketRecovery: # TODO : collapse congestion window if persistent congestion + def _log_metrics_updated(self, log_rtt=False) -> None: - def _log_metrics_updated(self) -> None: <0> data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} <1> if self._ssthresh is not None: <2> data["ssthresh"] = self._ssthresh <3> <4> self._quic_logger.log_event( <5> category="recovery", event="metrics_updated", data=data <6> ) <7>
===========unchanged ref 0=========== at: aioquic.quic.logger.QuicLoggerTrace log_event(*, category: str, event: str, data: Dict) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._quic_logger = quic_logger self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery._log_metrics_updated data = {"bytes_in_flight": self.bytes_in_flight, "cwnd": self.congestion_window} data["ssthresh"] = self._ssthresh at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_min = self._rtt_latest self._rtt_variance = latest_rtt / 2 self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return if self._ssthresh is None or self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) - if self._quic_logger is not None: - self._log_metrics_updated() - ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time + log_rtt = True # limit ACK delay to max_ack_delay ack_delay = min(ack_delay, self.max_ack_delay) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt,</s> ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 <s> # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) - - if self._quic_logger is not None: - self._quic_logger.log_event( - category="recovery", - event="metrics_updated", - data={ - "latest_rtt": int(self._rtt_latest * 1000), - "min_rtt": int(self._rtt_min * 1000), - "smoothed_rtt": int(self._rtt_smoothed * 1000), - "rtt_variance": int(self._rtt_variance * 1000), - }, - ) + else: + log_rtt = False self.detect_loss(space,</s> ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 2 <s>now) + if self._quic_logger is not None: + self._log_metrics_updated(log_rtt=log_rtt) + self._pto_count = 0
aioquic.quic.connection/QuicConnection._write_connection_limits
Modified
aiortc~aioquic
84bd35c5e955514cb872e99a6919db521a90e131
[quic] raise flow control limits more agressively
<1>:<add> if self._local_max_data_used * 2 > self._local_max_data: <del> if self._local_max_data_used > self._local_max_data * 0.75:
# module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: <0> # raise MAX_DATA if needed <1> if self._local_max_data_used > self._local_max_data * 0.75: <2> self._local_max_data *= 2 <3> self._logger.debug("Local max_data raised to %d", self._local_max_data) <4> if self._local_max_data_sent != self._local_max_data: <5> builder.start_frame(QuicFrameType.MAX_DATA, self._on_max_data_delivery) <6> builder.buffer.push_uint_var(self._local_max_data) <7> self._local_max_data_sent = self._local_max_data <8> <9> # log frame <10> if self._quic_logger is not None: <11> builder.quic_logger_frames.append( <12> self._quic_logger.encode_max_data_frame(self._local_max_data) <13> ) <14>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer push_uint_var(value: int) -> None at: aioquic.quic.connection.QuicConnection _on_max_data_delivery(delivery: QuicDeliveryState) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_stream_frame self._local_max_data_used += newly_received at: aioquic.quic.connection.QuicConnection._on_max_data_delivery self._local_max_data_sent = 0 at: aioquic.quic.logger.QuicLoggerTrace encode_max_data_frame(maximum: int) -> Dict at: aioquic.quic.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.quic.packet_builder QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", quic_logger: Optional[QuicLoggerTrace]=None, spin_bit: bool=False) ===========unchanged ref 1=========== at: aioquic.quic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.quic_logger_frames: Optional[List[Dict]] = None self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self.quic_logger_frames = self._packet.quic_logger_frames at: aioquic.quic.recovery QuicPacketSpace() at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
aioquic.quic.connection/QuicConnection._write_stream_limits
Modified
aiortc~aioquic
84bd35c5e955514cb872e99a6919db521a90e131
[quic] raise flow control limits more agressively
<1>:<add> if stream._recv_highest * 2 > stream.max_stream_data_local: <del> if stream._recv_highest > stream.max_stream_data_local * 0.75:
# module: aioquic.quic.connection class QuicConnection: def _write_stream_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream ) -> None: <0> # raise MAX_STREAM_DATA if needed <1> if stream._recv_highest > stream.max_stream_data_local * 0.75: <2> stream.max_stream_data_local *= 2 <3> self._logger.debug( <4> "Stream %d local max_stream_data raised to %d", <5> stream.stream_id, <6> stream.max_stream_data_local, <7> ) <8> if stream.max_stream_data_local_sent != stream.max_stream_data_local: <9> builder.start_frame( <10> QuicFrameType.MAX_STREAM_DATA, <11> self._on_max_stream_data_delivery, <12> (stream,), <13> ) <14> builder.buffer.push_uint_var(stream.stream_id) <15> builder.buffer.push_uint_var(stream.max_stream_data_local) <16> stream.max_stream_data_local_sent = stream.max_stream_data_local <17> <18> # log frame <19> if self._quic_logger is not None: <20> builder.quic_logger_frames.append( <21> self._quic_logger.encode_max_stream_data_frame( <22> maximum=stream.max_stream_data_local, stream_id=stream.stream_id <23> ) <24> ) <25>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer push_uint_var(value: int) -> None at: aioquic.quic.connection.QuicConnection _on_max_stream_data_delivery(delivery: QuicDeliveryState, stream: QuicStream) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.logger.QuicLoggerTrace encode_max_stream_data_frame(maximum: int, stream_id: int) -> Dict at: aioquic.quic.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.quic.packet_builder QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", quic_logger: Optional[QuicLoggerTrace]=None, spin_bit: bool=False) at: aioquic.quic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.quic_logger_frames: Optional[List[Dict]] = None ===========unchanged ref 1=========== self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self.quic_logger_frames = self._packet.quic_logger_frames at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.stream QuicStream(stream_id: Optional[int]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.quic.stream.QuicStream.__init__ self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self._recv_highest = 0 # the highest offset ever seen at: aioquic.quic.stream.QuicStream.add_frame self._recv_highest = frame_end at: logging.LoggerAdapter debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: # raise MAX_DATA if needed + if self._local_max_data_used * 2 > self._local_max_data: - if self._local_max_data_used > self._local_max_data * 0.75: self._local_max_data *= 2 self._logger.debug("Local max_data raised to %d", self._local_max_data) if self._local_max_data_sent != self._local_max_data: builder.start_frame(QuicFrameType.MAX_DATA, self._on_max_data_delivery) builder.buffer.push_uint_var(self._local_max_data) self._local_max_data_sent = self._local_max_data # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_max_data_frame(self._local_max_data) )
tests.test_connection/QuicConnectionTest.test_send_max_stream_data_retransmit
Modified
aiortc~aioquic
84bd35c5e955514cb872e99a6919db521a90e131
[quic] raise flow control limits more agressively
<9>:<add> server.send_stream_data(0, b"Z" * 524288) # 1048576 // 2 <del> server.send_stream_data(0, b"Z" * 786432) # 0.75 * 1048576
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_stream_data_retransmit(self): <0> with client_and_server() as (client, server): <1> # client creates bidirectional stream 0 <2> stream = client._create_stream(stream_id=0) <3> client.send_stream_data(0, b"hello") <4> self.assertEqual(stream.max_stream_data_local, 1048576) <5> self.assertEqual(stream.max_stream_data_local_sent, 1048576) <6> roundtrip(client, server) <7> <8> # server sends data, just before raising MAX_STREAM_DATA <9> server.send_stream_data(0, b"Z" * 786432) # 0.75 * 1048576 <10> for i in range(10): <11> roundtrip(server, client) <12> self.assertEqual(stream.max_stream_data_local, 1048576) <13> self.assertEqual(stream.max_stream_data_local_sent, 1048576) <14> <15> # server sends one more byte <16> server.send_stream_data(0, b"Z") <17> transfer(server, client) <18> <19> # MAX_STREAM_DATA is sent and lost <20> self.assertEqual(drop(client), 1) <21> self.assertEqual(stream.max_stream_data_local, 2097152) <22> self.assertEqual(stream.max_stream_data_local_sent, 2097152) <23> client._on_max_stream_data_delivery(QuicDeliveryState.LOST, stream) <24> self.assertEqual(stream.max_stream_data_local, 2097152) <25> self.assertEqual(stream.max_stream_data_local_sent, 0) <26> <27> # MAX_DATA is retransmitted and acked <28> self.assertEqual(roundtrip(client, server), (1, 1)) <29> self.assertEqual(stream.max_stream_data_local, 2097152) <30> self</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_stream_data_retransmit(self): # offset: 1 ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryState() at: tests.test_connection client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) drop(sender) roundtrip(sender, receiver) transfer(sender, receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: # raise MAX_DATA if needed + if self._local_max_data_used * 2 > self._local_max_data: - if self._local_max_data_used > self._local_max_data * 0.75: self._local_max_data *= 2 self._logger.debug("Local max_data raised to %d", self._local_max_data) if self._local_max_data_sent != self._local_max_data: builder.start_frame(QuicFrameType.MAX_DATA, self._on_max_data_delivery) builder.buffer.push_uint_var(self._local_max_data) self._local_max_data_sent = self._local_max_data # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_max_data_frame(self._local_max_data) ) ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _write_stream_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream ) -> None: # raise MAX_STREAM_DATA if needed + if stream._recv_highest * 2 > stream.max_stream_data_local: - if stream._recv_highest > stream.max_stream_data_local * 0.75: stream.max_stream_data_local *= 2 self._logger.debug( "Stream %d local max_stream_data raised to %d", stream.stream_id, stream.max_stream_data_local, ) if stream.max_stream_data_local_sent != stream.max_stream_data_local: builder.start_frame( QuicFrameType.MAX_STREAM_DATA, self._on_max_stream_data_delivery, (stream,), ) builder.buffer.push_uint_var(stream.stream_id) builder.buffer.push_uint_var(stream.max_stream_data_local) stream.max_stream_data_local_sent = stream.max_stream_data_local # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_max_stream_data_frame( maximum=stream.max_stream_data_local, stream_id=stream.stream_id ) )
aioquic.quic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
0f073560fef4c109a30c54b79260447176942a78
[recovery] allow cwnd to grow outside slow start
<21>:<add> self._congestion_stash = 0
# module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, is_client_without_1rtt: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: <0> self.is_client_without_1rtt = is_client_without_1rtt <1> self.max_ack_delay = 0.025 <2> self.spaces: List[QuicPacketSpace] = [] <3> <4> # callbacks <5> self._quic_logger = quic_logger <6> self._send_probe = send_probe <7> <8> # loss detection <9> self._pto_count = 0 <10> self._rtt_initialized = False <11> self._rtt_latest = 0.0 <12> self._rtt_min = math.inf <13> self._rtt_smoothed = 0.0 <14> self._rtt_variance = 0.0 <15> self._time_of_last_sent_ack_eliciting_packet = 0.0 <16> <17> # congestion control <18> self.bytes_in_flight = 0 <19> self.congestion_window = K_INITIAL_WINDOW <20> self._congestion_recovery_start_time = 0.0 <21> self._ssthresh: Optional[int] = None <22>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLoggerTrace(*, is_client: bool, odcid: bytes) at: aioquic.quic.recovery K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_min = self._rtt_latest self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes self.congestion_window += packet.sent_bytes self.congestion_window += count * K_MAX_DATAGRAM_SIZE self._congestion_stash -= count * self.congestion_window self._congestion_stash += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time self.bytes_in_flight += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) at: math inf: float at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.quic.recovery/QuicPacketRecovery.on_packet_acked
Modified
aiortc~aioquic
0f073560fef4c109a30c54b79260447176942a78
[recovery] allow cwnd to grow outside slow start
<11>:<add> self._congestion_stash += packet.sent_bytes <add> count = self._congestion_stash // self.congestion_window <add> if count: <add> self._congestion_stash -= count * self.congestion_window <add> self.congestion_window += count * K_MAX_DATAGRAM_SIZE <del> self.congestion_window += ( <12>:<del> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window <13>:<del> )
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: <0> self.bytes_in_flight -= packet.sent_bytes <1> <2> # don't increase window in congestion recovery <3> if packet.sent_time <= self._congestion_recovery_start_time: <4> return <5> <6> if self._ssthresh is None or self.congestion_window < self._ssthresh: <7> # slow start <8> self.congestion_window += packet.sent_bytes <9> else: <10> # congestion avoidance <11> self.congestion_window += ( <12> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window <13> ) <14>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._congestion_stash = 0 self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, is_client_without_1rtt: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 0.025 self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 + self._congestion_stash = 0 self._ssthresh: Optional[int] = None
aioquic.quic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
85e75cfcf079619dcce4d6c3e1de106d57f080ba
[recovery] use HyStart to exit slow start earlier
<22>:<add> self._rtt_monitor = QuicRttMonitor()
# module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, is_client_without_1rtt: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: <0> self.is_client_without_1rtt = is_client_without_1rtt <1> self.max_ack_delay = 0.025 <2> self.spaces: List[QuicPacketSpace] = [] <3> <4> # callbacks <5> self._quic_logger = quic_logger <6> self._send_probe = send_probe <7> <8> # loss detection <9> self._pto_count = 0 <10> self._rtt_initialized = False <11> self._rtt_latest = 0.0 <12> self._rtt_min = math.inf <13> self._rtt_smoothed = 0.0 <14> self._rtt_variance = 0.0 <15> self._time_of_last_sent_ack_eliciting_packet = 0.0 <16> <17> # congestion control <18> self.bytes_in_flight = 0 <19> self.congestion_window = K_INITIAL_WINDOW <20> self._congestion_recovery_start_time = 0.0 <21> self._congestion_stash = 0 <22> self._ssthresh: Optional[int] = None <23>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLoggerTrace(*, is_client: bool, odcid: bytes) at: aioquic.quic.recovery K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE QuicPacketSpace() QuicRttMonitor() at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_min = self._rtt_latest self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes self.congestion_window += packet.sent_bytes self.congestion_window += count * K_MAX_DATAGRAM_SIZE self._congestion_stash -= count * self.congestion_window self._congestion_stash += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time self.bytes_in_flight += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) at: math inf: float at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List')
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
Modified
aiortc~aioquic
85e75cfcf079619dcce4d6c3e1de106d57f080ba
[recovery] use HyStart to exit slow start earlier
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: <0> """ <1> Update metrics as the result of an ACK being received. <2> """ <3> is_ack_eliciting = False <4> largest_acked = ack_rangeset.bounds().stop - 1 <5> largest_newly_acked = None <6> largest_sent_time = None <7> <8> if largest_acked > space.largest_acked_packet: <9> space.largest_acked_packet = largest_acked <10> <11> for packet_number in sorted(space.sent_packets.keys()): <12> if packet_number > largest_acked: <13> break <14> if packet_number in ack_rangeset: <15> # remove packet and update counters <16> packet = space.sent_packets.pop(packet_number) <17> if packet.is_ack_eliciting: <18> is_ack_eliciting = True <19> space.ack_eliciting_in_flight -= 1 <20> if packet.in_flight: <21> self.on_packet_acked(packet) <22> largest_newly_acked = packet_number <23> largest_sent_time = packet.sent_time <24> <25> # trigger callbacks <26> for handler, args in packet.delivery_handlers: <27> handler(QuicDeliveryState.ACKED, *args) <28> <29> # nothing to do if there are no newly acked packets <30> if largest_newly_acked is None: <31> return <32> <33> if largest_acked == largest_newly_acked and is_ack_eliciting: <34> latest_rtt = now - largest_sent_time <35> log_rtt = True <36> <37> # limit ACK delay to max_ack_delay <38> ack_delay = min(ack_delay, self</s>
===========below chunk 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay: float, now: float, ) -> None: # offset: 1 # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) else: log_rtt = False self.detect_loss(space, now=now) if self._quic_logger is not None: self._log_metrics_updated(log_rtt=log_rtt) self._pto_count = 0 ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryState() at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: aioquic.quic.rangeset RangeSet(ranges: Iterable[range]=[]) at: aioquic.quic.rangeset.RangeSet bounds() -> range at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery on_packet_acked(packet: QuicSentPacket) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self.congestion_window = K_INITIAL_WINDOW self._rtt_monitor = QuicRttMonitor() self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_acked self.congestion_window += packet.sent_bytes self.congestion_window += count * K_MAX_DATAGRAM_SIZE ===========unchanged ref 1=========== at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.largest_acked_packet = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} at: aioquic.quic.recovery.QuicRttMonitor is_rtt_increasing(rtt: float, now: float) -> bool at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, is_client_without_1rtt: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 0.025 self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._congestion_stash = 0 + self._rtt_monitor = QuicRttMonitor() self._ssthresh: Optional[int] = None
aioquic.quic.packet_builder/QuicPacketBuilder.start_frame
Modified
aiortc~aioquic
ecaea8c917c53e7b84d8740e47e1ea6825ff3802
[recovery] CONNECTION_CLOSE frames are not ACK-eliciting
<5>:<del> # FIXME: in_flight != is_ack_eliciting <6>:<del> self._packet.in_flight = True <9>:<add> if frame_type not in NON_IN_FLIGHT_FRAME_TYPES: <add> self._packet.in_flight = True
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_frame( self, frame_type: int, handler: Optional[QuicDeliveryHandler] = None, args: Sequence[Any] = [], ) -> None: <0> """ <1> Starts a new frame. <2> """ <3> self.buffer.push_uint_var(frame_type) <4> if frame_type not in NON_ACK_ELICITING_FRAME_TYPES: <5> # FIXME: in_flight != is_ack_eliciting <6> self._packet.in_flight = True <7> self._packet.is_ack_eliciting = True <8> self._ack_eliciting = True <9> if frame_type == QuicFrameType.CRYPTO: <10> self._packet.is_crypto_packet = True <11> if handler is not None: <12> self._packet.delivery_handlers.append((handler, args)) <13>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryHandler = Callable[..., None] at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._ack_eliciting = False self._packet: Optional[QuicSentPacket] = None self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self._packet = None at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._ack_eliciting = False self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: typing Sequence = _alias(collections.abc.Sequence, 1) ===========changed ref 0=========== # module: aioquic.quic.packet NON_ACK_ELICITING_FRAME_TYPES = frozenset( + [ + QuicFrameType.ACK, + QuicFrameType.ACK_ECN, + QuicFrameType.PADDING, + QuicFrameType.TRANSPORT_CLOSE, + QuicFrameType.APPLICATION_CLOSE, + ] - [QuicFrameType.ACK, QuicFrameType.ACK_ECN, QuicFrameType.PADDING] ) + NON_IN_FLIGHT_FRAME_TYPES = frozenset( + [ + QuicFrameType.ACK, + QuicFrameType.ACK_ECN, + QuicFrameType.TRANSPORT_CLOSE, + QuicFrameType.APPLICATION_CLOSE, + ] + ) + PROBING_FRAME_TYPES = frozenset( [ QuicFrameType.PATH_CHALLENGE, QuicFrameType.PATH_RESPONSE, QuicFrameType.PADDING, QuicFrameType.NEW_CONNECTION_ID, ] )
aioquic.quic.connection/QuicConnection._handle_crypto_frame
Modified
aiortc~aioquic
beb593adb5cdc24cc936753ae3693dcf8b29bce8
[quic] check offset + length is allowed
<5>:<add> if offset + length > UINT_VAR_MAX: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <add> frame_type=frame_type, <add> reason_phrase="offset + length cannot exceed 2^62 - 1", <add> ) <23>:<add> frame_type=frame_type, <del> frame_type=QuicFrameType.CRYPTO,
# module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a CRYPTO frame. <2> """ <3> offset = buf.pull_uint_var() <4> length = buf.pull_uint_var() <5> frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length)) <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_crypto_frame(frame) <11> ) <12> <13> stream = self._crypto_streams[context.epoch] <14> event = stream.add_frame(frame) <15> if event is not None: <16> # pass data to TLS layer <17> try: <18> self.tls.handle_message(event.data, self._crypto_buffers) <19> self._push_crypto_data() <20> except tls.Alert as exc: <21> raise QuicConnectionError( <22> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description), <23> frame_type=QuicFrameType.CRYPTO, <24> reason_phrase=str(exc), <25> ) <26> <27> # parse transport parameters <28> if ( <29> not self._parameters_received <30> and self.tls.received_extensions is not None <31> ): <32> for ext_type, ext_data in self.tls.received_extensions: <33> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <34> self._parse_transport_parameters(ext_data) <35> self._parameters_received = True <36> break <37> assert ( <38> self._parameters_received <39> ), "No QUIC transport parameters received" <40> <41> # update current epoch <42> if not self._handshake_complete and self.tls.state in [ <43> tls.State.CLIENT_POST_HAND</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 tls.State.SERVER_POST_HANDSHAKE, ]: self._handshake_complete = True self._loss.is_client_without_1rtt = False self._replenish_connection_ids() self._events.append( events.HandshakeCompleted( alpn_protocol=self.tls.alpn_negotiated, early_data_accepted=self.tls.early_data_accepted, session_resumed=self.tls.session_resumed, ) ) self._unblock_streams(is_unidirectional=False) self._unblock_streams(is_unidirectional=True) self._logger.info( "ALPN negotiated protocol %s", self.tls.alpn_negotiated ) ===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _replenish_connection_ids() -> None _push_crypto_data() -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._events: Deque[events.QuicEvent] = deque() self._handshake_complete = False self._parameters_received = False self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnection._initialize self.tls = tls.Context( alpn_protocols=self._configuration.alpn_protocols, cadata=self._configuration.cadata, cafile=self._configuration.cafile, capath=self._configuration.capath, is_client=self._is_client, logger=self._logger, max_early_data=None if self._is_client else MAX_EARLY_DATA, server_name=self._configuration.server_name, verify_mode=self._configuration.verify_mode, ) self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float at: collections.deque append(x: _T) -> None ===========changed ref 0=========== # module: aioquic.buffer + UINT_VAR_MAX = 0x3FFFFFFFFFFFFFFF ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_crypto_frame_over_largest_offset(self): + with client_and_server() as (client, server): + # client receives offset + length > 2^62 - 1 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_crypto_frame( + client_receive_context(client), + QuicFrameType.CRYPTO, + Buffer(data=encode_uint_var(UINT_VAR_MAX) + encode_uint_var(1)), + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.CRYPTO) + self.assertEqual( + cm.exception.reason_phrase, "offset + length cannot exceed 2^62 - 1" + ) + ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_over_largest_offset(self): + with client_and_server() as (client, server): + # client receives offset + length > 2^62 - 1 + frame_type = QuicFrameType.STREAM_BASE | 6 + stream_id = 1 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(UINT_VAR_MAX) + + encode_uint_var(1) + ), + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR + ) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual( + cm.exception.reason_phrase, "offset + length cannot exceed 2^62 - 1" + ) +
aioquic.quic.connection/QuicConnection._handle_stream_frame
Modified
aiortc~aioquic
beb593adb5cdc24cc936753ae3693dcf8b29bce8
[quic] check offset + length is allowed
<12>:<add> if offset + length > UINT_VAR_MAX: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <add> frame_type=frame_type, <add> reason_phrase="offset + length cannot exceed 2^62 - 1", <add> )
# module: aioquic.quic.connection class QuicConnection: def _handle_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a STREAM frame. <2> """ <3> stream_id = buf.pull_uint_var() <4> if frame_type & 4: <5> offset = buf.pull_uint_var() <6> else: <7> offset = 0 <8> if frame_type & 2: <9> length = buf.pull_uint_var() <10> else: <11> length = buf.capacity - buf.tell() <12> frame = QuicStreamFrame( <13> offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1) <14> ) <15> <16> # log frame <17> if self._quic_logger is not None: <18> context.quic_logger_frames.append( <19> self._quic_logger.encode_stream_frame(frame, stream_id=stream_id) <20> ) <21> <22> # check stream direction <23> self._assert_stream_can_receive(frame_type, stream_id) <24> <25> # check flow-control limits <26> stream = self._get_or_create_stream(frame_type, stream_id) <27> if offset + length > stream.max_stream_data_local: <28> raise QuicConnectionError( <29> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <30> frame_type=frame_type, <31> reason_phrase="Over stream data limit", <32> ) <33> newly_received = max(0, offset + length - stream._recv_highest) <34> if self._local_max_data_used + newly_received > self._local_max_data: <35> raise QuicConnectionError( <36> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <37> frame_type=frame_type, <38> reason_phrase="Over connection data limit", <39> ) <40> <41> event = stream.add</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 if event is not None: self._events.append(event) self._local_max_data_used += newly_received ===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _assert_stream_can_receive(frame_type: int, stream_id: int) -> None _assert_stream_can_send(frame_type: int, stream_id: int) -> None _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream at: aioquic.quic.connection.QuicConnection.__init__ self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_stop_sending_frame stream_id = buf.pull_uint_var() at: aioquic.quic.connection.QuicReceiveContext quic_logger_frames: Optional[List[Any]] ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a CRYPTO frame. """ offset = buf.pull_uint_var() length = buf.pull_uint_var() + if offset + length > UINT_VAR_MAX: + raise QuicConnectionError( + error_code=QuicErrorCode.FRAME_ENCODING_ERROR, + frame_type=frame_type, + reason_phrase="offset + length cannot exceed 2^62 - 1", + ) frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length)) # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_crypto_frame(frame) ) stream = self._crypto_streams[context.epoch] event = stream.add_frame(frame) if event is not None: # pass data to TLS layer try: self.tls.handle_message(event.data, self._crypto_buffers) self._push_crypto_data() except tls.Alert as exc: raise QuicConnectionError( error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description), + frame_type=frame_type, - frame_type=QuicFrameType.CRYPTO, reason_phrase=str(exc), ) # parse transport parameters if ( not self._parameters_received and self.tls.received_extensions is not None ): for ext_type, ext_data in self.tls.received_extensions: if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: self._parse_transport_parameters(ext_data) self._parameters_received = True break assert ( self._parameters_received ), "No QUIC</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s> self._parameters_received = True break assert ( self._parameters_received ), "No QUIC transport parameters received" # update current epoch if not self._handshake_complete and self.tls.state in [ tls.State.CLIENT_POST_HANDSHAKE, tls.State.SERVER_POST_HANDSHAKE, ]: self._handshake_complete = True self._loss.is_client_without_1rtt = False self._replenish_connection_ids() self._events.append( events.HandshakeCompleted( alpn_protocol=self.tls.alpn_negotiated, early_data_accepted=self.tls.early_data_accepted, session_resumed=self.tls.session_resumed, ) ) self._unblock_streams(is_unidirectional=False) self._unblock_streams(is_unidirectional=True) self._logger.info( "ALPN negotiated protocol %s", self.tls.alpn_negotiated ) ===========changed ref 2=========== # module: aioquic.buffer + UINT_VAR_MAX = 0x3FFFFFFFFFFFFFFF ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_crypto_frame_over_largest_offset(self): + with client_and_server() as (client, server): + # client receives offset + length > 2^62 - 1 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_crypto_frame( + client_receive_context(client), + QuicFrameType.CRYPTO, + Buffer(data=encode_uint_var(UINT_VAR_MAX) + encode_uint_var(1)), + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.CRYPTO) + self.assertEqual( + cm.exception.reason_phrase, "offset + length cannot exceed 2^62 - 1" + ) + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_over_largest_offset(self): + with client_and_server() as (client, server): + # client receives offset + length > 2^62 - 1 + frame_type = QuicFrameType.STREAM_BASE | 6 + stream_id = 1 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(UINT_VAR_MAX) + + encode_uint_var(1) + ), + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR + ) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual( + cm.exception.reason_phrase, "offset + length cannot exceed 2^62 - 1" + ) +
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
1d7928f94e5458a95b0189b06ef1e16361152fe2
[recovery] clarify some code
<1>:<add> loss_space = self.get_earliest_loss_space() <del> loss_space = self.get_earliest_loss_time() <13>:<del> timeout = ( <14>:<del> self._rtt_smoothed <15>:<del> + max(4 * self._rtt_variance, K_GRANULARITY) <16>:<del> + self.max_ack_delay <17>:<del> ) * (2 ** self._pto_count) <18>:<add> timeout = self.get_probe_timeout() * (2 ** self._pto_count)
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_loss_detection_time(self) -> float: <0> # loss timer <1> loss_space = self.get_earliest_loss_time() <2> if loss_space is not None: <3> return loss_space.loss_time <4> <5> # packet timer <6> if ( <7> self.is_client_without_1rtt <8> or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0 <9> ): <10> if not self._rtt_initialized: <11> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) <12> else: <13> timeout = ( <14> self._rtt_smoothed <15> + max(4 * self._rtt_variance, K_GRANULARITY) <16> + self.max_ack_delay <17> ) * (2 ** self._pto_count) <18> return self._time_of_last_sent_ack_eliciting_packet + timeout <19> <20> return None <21>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_INITIAL_RTT = 0.5 # seconds at: aioquic.quic.recovery.QuicPacketRecovery get_earliest_loss_space() -> Optional[QuicPacketSpace] at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.is_client_without_1rtt = is_client_without_1rtt self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._rtt_smoothed = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.loss_time: Optional[float] = None ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - def get_earliest_loss_time(self) -> Optional[QuicPacketSpace]: - loss_space = None - for space in self.spaces: - if space.loss_time is not None and ( - loss_space is None or space.loss_time < loss_space.loss_time - ): - loss_space = space - return loss_space - ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - def get_earliest_loss_time(self) -> Optional[QuicPacketSpace]: - loss_space = None - for space in self.spaces: - if space.loss_time is not None and ( - loss_space is None or space.loss_time < loss_space.loss_time - ): - loss_space = space - return loss_space -
aioquic.quic.recovery/QuicPacketRecovery.on_loss_detection_timeout
Modified
aiortc~aioquic
1d7928f94e5458a95b0189b06ef1e16361152fe2
[recovery] clarify some code
<0>:<add> loss_space = self.get_earliest_loss_space() <del> loss_space = self.get_earliest_loss_time()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: <0> loss_space = self.get_earliest_loss_time() <1> if loss_space is not None: <2> self.detect_loss(loss_space, now=now) <3> else: <4> self._pto_count += 1 <5> <6> # reschedule some data <7> for space in self.spaces: <8> for packet_number, packet in list( <9> filter(lambda i: i[1].is_crypto_packet, space.sent_packets.items()) <10> ): <11> # remove packet and update counters <12> self.on_packet_lost(packet, space) <13> <14> self._send_probe() <15>
===========unchanged ref 0=========== at: aioquic.quic.recovery.QuicPacketRecovery on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] self._send_probe = send_probe self._pto_count = 0 self.bytes_in_flight = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - def get_earliest_loss_time(self) -> Optional[QuicPacketSpace]: - loss_space = None - for space in self.spaces: - if space.loss_time is not None and ( - loss_space is None or space.loss_time < loss_space.loss_time - ): - loss_space = space - return loss_space - ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: - def get_earliest_loss_time(self) -> Optional[QuicPacketSpace]: - loss_space = None - for space in self.spaces: - if space.loss_time is not None and ( - loss_space is None or space.loss_time < loss_space.loss_time - ): - loss_space = space - return loss_space - ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def get_loss_detection_time(self) -> float: # loss timer + loss_space = self.get_earliest_loss_space() - loss_space = self.get_earliest_loss_time() if loss_space is not None: return loss_space.loss_time # packet timer if ( self.is_client_without_1rtt or sum(space.ack_eliciting_in_flight for space in self.spaces) > 0 ): if not self._rtt_initialized: timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) else: - timeout = ( - self._rtt_smoothed - + max(4 * self._rtt_variance, K_GRANULARITY) - + self.max_ack_delay - ) * (2 ** self._pto_count) + timeout = self.get_probe_timeout() * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
aioquic.quic.crypto/CryptoContext.__init__
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<5>:<add> self.version: Optional[int] = None
# module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: <0> self.aead: Optional[AEAD] = None <1> self.cipher_suite: Optional[CipherSuite] = None <2> self.hp: Optional[HeaderProtection] = None <3> self.key_phase = key_phase <4> self.secret: Optional[bytes] = None <5>
===========unchanged ref 0=========== at: aioquic.quic.crypto.CryptoContext.setup key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.hp = HeaderProtection(hp_cipher_name, hp) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.secret = secret at: aioquic.quic.crypto.CryptoContext.teardown self.aead = None self.cipher_suite = None self.hp = None self.secret = None ===========changed ref 0=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018
aioquic.quic.crypto/CryptoContext.setup
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<7>:<add> self.version = version
# module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: <0> hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] <1> <2> key, iv, hp = derive_key_iv_hp(cipher_suite, secret) <3> self.aead = AEAD(aead_cipher_name, key, iv) <4> self.cipher_suite = cipher_suite <5> self.hp = HeaderProtection(hp_cipher_name, hp) <6> self.secret = secret <7>
===========unchanged ref 0=========== at: aioquic.quic.crypto CIPHER_SUITES = { CipherSuite.AES_128_GCM_SHA256: (b"aes-128-ecb", b"aes-128-gcm"), CipherSuite.AES_256_GCM_SHA384: (b"aes-256-ecb", b"aes-256-gcm"), CipherSuite.CHACHA20_POLY1305_SHA256: (b"chacha20", b"chacha20-poly1305"), } derive_key_iv_hp(cipher_suite: CipherSuite, secret: bytes) -> Tuple[bytes, bytes, bytes] at: aioquic.quic.crypto.CryptoContext.__init__ self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None at: aioquic.quic.crypto.CryptoContext.teardown self.aead = None self.cipher_suite = None self.hp = None ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 1=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018
aioquic.quic.crypto/next_key_phase
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<1>:<add> <add> if self.version < QuicProtocolVersion.DRAFT_24: <add> label = b"traffic upd" <add> else: <add> label = b"quic ku" <4>:<add> cipher_suite=self.cipher_suite, <del> self.cipher_suite, <5>:<add> secret=hkdf_expand_label( <del> hkdf_expand_label( <6>:<add> algorithm, self.secret, label, b"", algorithm.digest_size <del> algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size <8>:<add> version=self.version,
# module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: <0> algorithm = cipher_suite_hash(self.cipher_suite) <1> <2> crypto = CryptoContext(key_phase=int(not self.key_phase)) <3> crypto.setup( <4> self.cipher_suite, <5> hkdf_expand_label( <6> algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size <7> ), <8> ) <9> return crypto <10>
===========unchanged ref 0=========== at: aioquic.quic.crypto CryptoContext(key_phase: int=0) at: aioquic.quic.crypto.CryptoContext.__init__ self.cipher_suite: Optional[CipherSuite] = None self.key_phase = key_phase self.version: Optional[int] = None at: aioquic.quic.crypto.CryptoContext.setup self.cipher_suite = cipher_suite self.version = version at: aioquic.quic.crypto.CryptoContext.teardown self.cipher_suite = None ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 2=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018
aioquic.quic.crypto/CryptoPair.setup_initial
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<8>:<add> cipher_suite=INITIAL_CIPHER_SUITE, <del> INITIAL_CIPHER_SUITE, <9>:<add> secret=hkdf_expand_label( <del> hkdf_expand_label( <12>:<add> version=version, <14>:<add> cipher_suite=INITIAL_CIPHER_SUITE, <del> INITIAL_CIPHER_SUITE, <15>:<add> secret=hkdf_expand_label( <del> hkdf_expand_label( <18>:<add> version=version,
# module: aioquic.quic.crypto class CryptoPair: def setup_initial(self, cid: bytes, is_client: bool, version: int) -> None: <0> if is_client: <1> recv_label, send_label = b"server in", b"client in" <2> else: <3> recv_label, send_label = b"client in", b"server in" <4> <5> algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) <6> initial_secret = hkdf_extract(algorithm, INITIAL_SALT_DRAFT_23, cid) <7> self.recv.setup( <8> INITIAL_CIPHER_SUITE, <9> hkdf_expand_label( <10> algorithm, initial_secret, recv_label, b"", algorithm.digest_size <11> ), <12> ) <13> self.send.setup( <14> INITIAL_CIPHER_SUITE, <15> hkdf_expand_label( <16> algorithm, initial_secret, send_label, b"", algorithm.digest_size <17> ), <18> ) <19>
===========unchanged ref 0=========== at: aioquic.quic.crypto INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 INITIAL_SALT_DRAFT_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") at: aioquic.quic.crypto.CryptoContext encrypt_packet(plain_header: bytes, plain_payload: bytes, packet_number: int) -> bytes setup(cipher_suite: CipherSuite, secret: bytes, version: int) -> None setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None at: aioquic.quic.crypto.CryptoPair _update_key() -> None at: aioquic.quic.crypto.CryptoPair.__init__ self.recv = CryptoContext() self.send = CryptoContext() self._update_key_requested = False at: aioquic.quic.crypto.CryptoPair._update_key self._update_key_requested = False at: aioquic.quic.crypto.CryptoPair.update_key self._update_key_requested = True ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 2=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto ===========changed ref 3=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018
tests.test_connection/QuicConnectionTest.test_decryption_error
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<3>:<add> cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, <del> tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) <4>:<add> secret=bytes(48), <add> version=QuicProtocolVersion.DRAFT_23,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): <0> with client_and_server() as (client, server): <1> # mess with encryption key <2> server._cryptos[tls.Epoch.ONE_RTT].send.setup( <3> tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) <4> ) <5> <6> # server sends close <7> server.close(error_code=QuicErrorCode.NO_ERROR) <8> for data, addr in server.datagrams_to_send(now=time.time()): <9> client.receive_datagram(data, SERVER_ADDR, now=time.time()) <10>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) client_and_server(client_kwargs={}, client_options={}, client_patch=lambda x: None, handshake=True, server_kwargs={}, server_certfile=SERVER_CERTFILE, server_keyfile=SERVER_KEYFILE, server_options={}, server_patch=lambda x: None, transport_options={}) at: time time() -> float ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 1=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 3=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto ===========changed ref 4=========== # module: aioquic.quic.crypto class CryptoPair: def setup_initial(self, cid: bytes, is_client: bool, version: int) -> None: if is_client: recv_label, send_label = b"server in", b"client in" else: recv_label, send_label = b"client in", b"server in" algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) initial_secret = hkdf_extract(algorithm, INITIAL_SALT_DRAFT_23, cid) self.recv.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, recv_label, b"", algorithm.digest_size ), + version=version, ) self.send.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, send_label, b"", algorithm.digest_size ), + version=version, )
tests.test_crypto/CryptoTest.test_decrypt_chacha20
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<2>:<add> cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, <del> CipherSuite.CHACHA20_POLY1305_SHA256, <3>:<add> secret=binascii.unhexlify( <del> binascii.unhexlify( <6>:<add> version=QuicProtocolVersion.DRAFT_23,
# module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_decrypt_chacha20(self): <0> pair = CryptoPair() <1> pair.recv.setup( <2> CipherSuite.CHACHA20_POLY1305_SHA256, <3> binascii.unhexlify( <4> "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" <5> ), <6> ) <7> <8> plain_header, plain_payload, packet_number = pair.decrypt_packet( <9> CHACHA20_CLIENT_ENCRYPTED_PACKET, 25, 0 <10> ) <11> self.assertEqual(plain_header, CHACHA20_CLIENT_PLAIN_HEADER) <12> self.assertEqual(plain_payload, CHACHA20_CLIENT_PLAIN_PAYLOAD) <13> self.assertEqual(packet_number, CHACHA20_CLIENT_PACKET_NUMBER) <14>
===========unchanged ref 0=========== at: _collections_abc.Mapping __slots__ = () __abc_tpflags__ = 1 << 6 # Py_TPFLAGS_MAPPING get(key, default=None) __reversed__ = None at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: os environ = _createenviron() at: tests.test_crypto CHACHA20_CLIENT_PLAIN_HEADER = binascii.unhexlify( "e1ff0000160880b57c7b70d8524b0850fc2a28e240fd7640170002" ) CHACHA20_CLIENT_PLAIN_PAYLOAD = binascii.unhexlify("0201000000") CHACHA20_CLIENT_ENCRYPTED_PACKET = binascii.unhexlify( "e8ff0000160880b57c7b70d8524b0850fc2a28e240fd7640178313b04be98449" "eb10567e25ce930381f2a5b7da2db8db" ) at: unittest.case skipIf(condition: object, reason: str) -> Callable[[_FT], _FT] at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 1=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): with client_and_server() as (client, server): # mess with encryption key server._cryptos[tls.Epoch.ONE_RTT].send.setup( + cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, - tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) + secret=bytes(48), + version=QuicProtocolVersion.DRAFT_23, ) # server sends close server.close(error_code=QuicErrorCode.NO_ERROR) for data, addr in server.datagrams_to_send(now=time.time()): client.receive_datagram(data, SERVER_ADDR, now=time.time()) ===========changed ref 4=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto ===========changed ref 5=========== # module: aioquic.quic.crypto class CryptoPair: def setup_initial(self, cid: bytes, is_client: bool, version: int) -> None: if is_client: recv_label, send_label = b"server in", b"client in" else: recv_label, send_label = b"client in", b"server in" algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) initial_secret = hkdf_extract(algorithm, INITIAL_SALT_DRAFT_23, cid) self.recv.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, recv_label, b"", algorithm.digest_size ), + version=version, ) self.send.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, send_label, b"", algorithm.digest_size ), + version=version, )
tests.test_crypto/CryptoTest.test_decrypt_short_server
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<2>:<add> cipher_suite=INITIAL_CIPHER_SUITE, <del> INITIAL_CIPHER_SUITE, <3>:<add> secret=binascii.unhexlify( <del> binascii.unhexlify( <6>:<add> version=QuicProtocolVersion.DRAFT_23,
# module: tests.test_crypto class CryptoTest(TestCase): def test_decrypt_short_server(self): <0> pair = CryptoPair() <1> pair.recv.setup( <2> INITIAL_CIPHER_SUITE, <3> binascii.unhexlify( <4> "310281977cb8c1c1c1212d784b2d29e5a6489e23de848d370a5a2f9537f3a100" <5> ), <6> ) <7> <8> plain_header, plain_payload, packet_number = pair.decrypt_packet( <9> SHORT_SERVER_ENCRYPTED_PACKET, 9, 0 <10> ) <11> self.assertEqual(plain_header, SHORT_SERVER_PLAIN_HEADER) <12> self.assertEqual(plain_payload, SHORT_SERVER_PLAIN_PAYLOAD) <13> self.assertEqual(packet_number, SHORT_SERVER_PACKET_NUMBER) <14>
===========unchanged ref 0=========== at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_crypto SHORT_SERVER_PLAIN_HEADER = binascii.unhexlify("41b01fd24a586a9cf30003") SHORT_SERVER_ENCRYPTED_PACKET = binascii.unhexlify( "5db01fd24a586a9cf33dec094aaec6d6b4b7a5e15f5a3f05d06cf1ad0355c19d" "cce0807eecf7bf1c844a66e1ecd1f74b2a2d69bfd25d217833edd973246597bd" "5107ea15cb1e210045396afa602fe23432f4ab24ce251b" ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_decrypt_chacha20(self): pair = CryptoPair() pair.recv.setup( + cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, - CipherSuite.CHACHA20_POLY1305_SHA256, + secret=binascii.unhexlify( - binascii.unhexlify( "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" ), + version=QuicProtocolVersion.DRAFT_23, ) plain_header, plain_payload, packet_number = pair.decrypt_packet( CHACHA20_CLIENT_ENCRYPTED_PACKET, 25, 0 ) self.assertEqual(plain_header, CHACHA20_CLIENT_PLAIN_HEADER) self.assertEqual(plain_payload, CHACHA20_CLIENT_PLAIN_PAYLOAD) self.assertEqual(packet_number, CHACHA20_CLIENT_PACKET_NUMBER) ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 2=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 3=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): with client_and_server() as (client, server): # mess with encryption key server._cryptos[tls.Epoch.ONE_RTT].send.setup( + cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, - tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) + secret=bytes(48), + version=QuicProtocolVersion.DRAFT_23, ) # server sends close server.close(error_code=QuicErrorCode.NO_ERROR) for data, addr in server.datagrams_to_send(now=time.time()): client.receive_datagram(data, SERVER_ADDR, now=time.time()) ===========changed ref 5=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto ===========changed ref 6=========== # module: aioquic.quic.crypto class CryptoPair: def setup_initial(self, cid: bytes, is_client: bool, version: int) -> None: if is_client: recv_label, send_label = b"server in", b"client in" else: recv_label, send_label = b"client in", b"server in" algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) initial_secret = hkdf_extract(algorithm, INITIAL_SALT_DRAFT_23, cid) self.recv.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, recv_label, b"", algorithm.digest_size ), + version=version, ) self.send.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=hkdf_expand_label( - hkdf_expand_label( algorithm, initial_secret, send_label, b"", algorithm.digest_size ), + version=version, )
tests.test_crypto/CryptoTest.test_encrypt_chacha20
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<2>:<add> cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, <del> CipherSuite.CHACHA20_POLY1305_SHA256, <3>:<add> secret=binascii.unhexlify( <del> binascii.unhexlify( <6>:<add> version=QuicProtocolVersion.DRAFT_23,
# module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_encrypt_chacha20(self): <0> pair = CryptoPair() <1> pair.send.setup( <2> CipherSuite.CHACHA20_POLY1305_SHA256, <3> binascii.unhexlify( <4> "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" <5> ), <6> ) <7> <8> packet = pair.encrypt_packet( <9> CHACHA20_CLIENT_PLAIN_HEADER, <10> CHACHA20_CLIENT_PLAIN_PAYLOAD, <11> CHACHA20_CLIENT_PACKET_NUMBER, <12> ) <13> self.assertEqual(packet, CHACHA20_CLIENT_ENCRYPTED_PACKET) <14>
===========unchanged ref 0=========== at: _collections_abc.Mapping get(key, default=None) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: os environ = _createenviron() at: tests.test_crypto CHACHA20_CLIENT_PLAIN_HEADER = binascii.unhexlify( "e1ff0000160880b57c7b70d8524b0850fc2a28e240fd7640170002" ) CHACHA20_CLIENT_PLAIN_PAYLOAD = binascii.unhexlify("0201000000") SHORT_SERVER_PACKET_NUMBER = 3 at: tests.test_crypto.CryptoTest.test_decrypt_short_server plain_header, plain_payload, packet_number = pair.decrypt_packet( SHORT_SERVER_ENCRYPTED_PACKET, 9, 0 ) at: unittest.case skipIf(condition: object, reason: str) -> Callable[[_FT], _FT] at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_crypto class CryptoTest(TestCase): def test_decrypt_short_server(self): pair = CryptoPair() pair.recv.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=binascii.unhexlify( - binascii.unhexlify( "310281977cb8c1c1c1212d784b2d29e5a6489e23de848d370a5a2f9537f3a100" ), + version=QuicProtocolVersion.DRAFT_23, ) plain_header, plain_payload, packet_number = pair.decrypt_packet( SHORT_SERVER_ENCRYPTED_PACKET, 9, 0 ) self.assertEqual(plain_header, SHORT_SERVER_PLAIN_HEADER) self.assertEqual(plain_payload, SHORT_SERVER_PLAIN_PAYLOAD) self.assertEqual(packet_number, SHORT_SERVER_PACKET_NUMBER) ===========changed ref 1=========== # module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_decrypt_chacha20(self): pair = CryptoPair() pair.recv.setup( + cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, - CipherSuite.CHACHA20_POLY1305_SHA256, + secret=binascii.unhexlify( - binascii.unhexlify( "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" ), + version=QuicProtocolVersion.DRAFT_23, ) plain_header, plain_payload, packet_number = pair.decrypt_packet( CHACHA20_CLIENT_ENCRYPTED_PACKET, 25, 0 ) self.assertEqual(plain_header, CHACHA20_CLIENT_PLAIN_HEADER) self.assertEqual(plain_payload, CHACHA20_CLIENT_PLAIN_PAYLOAD) self.assertEqual(packet_number, CHACHA20_CLIENT_PACKET_NUMBER) ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 3=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 4=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): with client_and_server() as (client, server): # mess with encryption key server._cryptos[tls.Epoch.ONE_RTT].send.setup( + cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, - tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) + secret=bytes(48), + version=QuicProtocolVersion.DRAFT_23, ) # server sends close server.close(error_code=QuicErrorCode.NO_ERROR) for data, addr in server.datagrams_to_send(now=time.time()): client.receive_datagram(data, SERVER_ADDR, now=time.time()) ===========changed ref 6=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto
tests.test_crypto/CryptoTest.test_encrypt_short_server
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<2>:<add> cipher_suite=INITIAL_CIPHER_SUITE, <del> INITIAL_CIPHER_SUITE, <3>:<add> secret=binascii.unhexlify( <del> binascii.unhexlify( <6>:<add> version=QuicProtocolVersion.DRAFT_23,
# module: tests.test_crypto class CryptoTest(TestCase): def test_encrypt_short_server(self): <0> pair = CryptoPair() <1> pair.send.setup( <2> INITIAL_CIPHER_SUITE, <3> binascii.unhexlify( <4> "310281977cb8c1c1c1212d784b2d29e5a6489e23de848d370a5a2f9537f3a100" <5> ), <6> ) <7> <8> packet = pair.encrypt_packet( <9> SHORT_SERVER_PLAIN_HEADER, <10> SHORT_SERVER_PLAIN_PAYLOAD, <11> SHORT_SERVER_PACKET_NUMBER, <12> ) <13> self.assertEqual(packet, SHORT_SERVER_ENCRYPTED_PACKET) <14>
===========unchanged ref 0=========== at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_crypto LONG_SERVER_ENCRYPTED_PACKET = binascii.unhexlify( "c9ff0000170008f067a5502a4262b5004074168bf22b7002596f99ae67abf65a" "5852f54f58c37c808682e2e40492d8a3899fb04fc0afe9aabc8767b18a0aa493" "537426373b48d502214dd856d63b78cee37bc664b3fe86d487ac7a77c53038a3" "cd32f0b5004d9f5754c4f7f2d1f35cf3f7116351c92b9cf9bb6d091ddfc8b32d" "432348a2c413" ) SHORT_SERVER_PLAIN_HEADER = binascii.unhexlify("41b01fd24a586a9cf30003") at: tests.test_crypto.CryptoTest.test_encrypt_long_server packet = pair.encrypt_packet( LONG_SERVER_PLAIN_HEADER, LONG_SERVER_PLAIN_PAYLOAD, LONG_SERVER_PACKET_NUMBER, ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_encrypt_chacha20(self): pair = CryptoPair() pair.send.setup( + cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, - CipherSuite.CHACHA20_POLY1305_SHA256, + secret=binascii.unhexlify( - binascii.unhexlify( "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" ), + version=QuicProtocolVersion.DRAFT_23, ) packet = pair.encrypt_packet( CHACHA20_CLIENT_PLAIN_HEADER, CHACHA20_CLIENT_PLAIN_PAYLOAD, CHACHA20_CLIENT_PACKET_NUMBER, ) self.assertEqual(packet, CHACHA20_CLIENT_ENCRYPTED_PACKET) ===========changed ref 1=========== # module: tests.test_crypto class CryptoTest(TestCase): def test_decrypt_short_server(self): pair = CryptoPair() pair.recv.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=binascii.unhexlify( - binascii.unhexlify( "310281977cb8c1c1c1212d784b2d29e5a6489e23de848d370a5a2f9537f3a100" ), + version=QuicProtocolVersion.DRAFT_23, ) plain_header, plain_payload, packet_number = pair.decrypt_packet( SHORT_SERVER_ENCRYPTED_PACKET, 9, 0 ) self.assertEqual(plain_header, SHORT_SERVER_PLAIN_HEADER) self.assertEqual(plain_payload, SHORT_SERVER_PLAIN_PAYLOAD) self.assertEqual(packet_number, SHORT_SERVER_PACKET_NUMBER) ===========changed ref 2=========== # module: tests.test_crypto class CryptoTest(TestCase): @skipIf(os.environ.get("TRAVIS") == "true", "travis lacks a modern OpenSSL") def test_decrypt_chacha20(self): pair = CryptoPair() pair.recv.setup( + cipher_suite=CipherSuite.CHACHA20_POLY1305_SHA256, - CipherSuite.CHACHA20_POLY1305_SHA256, + secret=binascii.unhexlify( - binascii.unhexlify( "b42772df33c9719a32820d302aa664d080d7f5ea7a71a330f87864cb289ae8c0" ), + version=QuicProtocolVersion.DRAFT_23, ) plain_header, plain_payload, packet_number = pair.decrypt_packet( CHACHA20_CLIENT_ENCRYPTED_PACKET, 25, 0 ) self.assertEqual(plain_header, CHACHA20_CLIENT_PLAIN_HEADER) self.assertEqual(plain_payload, CHACHA20_CLIENT_PLAIN_PAYLOAD) self.assertEqual(packet_number, CHACHA20_CLIENT_PACKET_NUMBER) ===========changed ref 3=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 4=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 5=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): with client_and_server() as (client, server): # mess with encryption key server._cryptos[tls.Epoch.ONE_RTT].send.setup( + cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, - tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) + secret=bytes(48), + version=QuicProtocolVersion.DRAFT_23, ) # server sends close server.close(error_code=QuicErrorCode.NO_ERROR) for data, addr in server.datagrams_to_send(now=time.time()): client.receive_datagram(data, SERVER_ADDR, now=time.time())
aioquic.quic.connection/QuicConnection._update_traffic_key
Modified
aiortc~aioquic
019af37c80fde306a09b8d0dec2e3559fd94d757
[crypto] add support for DRAFT_24 key update
<15>:<add> crypto.send.setup( <add> cipher_suite=cipher_suite, secret=secret, version=self._version <add> ) <del> crypto.send.setup(cipher_suite, secret) <17>:<add> crypto.recv.setup( <add> cipher_suite=cipher_suite, secret=secret, version=self._version <add> ) <del> crypto.recv.setup(cipher_suite, secret)
# module: aioquic.quic.connection class QuicConnection: def _update_traffic_key( self, direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes, ) -> None: <0> """ <1> Callback which is invoked by the TLS engine when new traffic keys are <2> available. <3> """ <4> secrets_log_file = self._configuration.secrets_log_file <5> if secrets_log_file is not None: <6> label_row = self._is_client == (direction == tls.Direction.DECRYPT) <7> label = SECRETS_LABELS[label_row][epoch.value] <8> secrets_log_file.write( <9> "%s %s %s\n" % (label, self.tls.client_random.hex(), secret.hex()) <10> ) <11> secrets_log_file.flush() <12> <13> crypto = self._cryptos[epoch] <14> if direction == tls.Direction.ENCRYPT: <15> crypto.send.setup(cipher_suite, secret) <16> else: <17> crypto.recv.setup(cipher_suite, secret) <18>
===========unchanged ref 0=========== at: aioquic.quic.connection SECRETS_LABELS = [ [ None, "QUIC_CLIENT_EARLY_TRAFFIC_SECRET", "QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET", "QUIC_CLIENT_TRAFFIC_SECRET_0", ], [ None, None, "QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET", "QUIC_SERVER_TRAFFIC_SECRET_0", ], ] at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._version: Optional[int] = None at: aioquic.quic.connection.QuicConnection._initialize self.tls = tls.Context( alpn_protocols=self._configuration.alpn_protocols, cadata=self._configuration.cadata, cafile=self._configuration.cafile, capath=self._configuration.capath, is_client=self._is_client, logger=self._logger, max_early_data=None if self._is_client else MAX_EARLY_DATA, server_name=self._configuration.server_name, verify_mode=self._configuration.verify_mode, ) self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) ===========changed ref 0=========== # module: tests.test_crypto class CryptoTest(TestCase): + def test_key_update_draft_24(self): + self._test_key_update(version=QuicProtocolVersion.DRAFT_24) + ===========changed ref 1=========== # module: tests.test_crypto class CryptoTest(TestCase): + def test_key_update_draft_23(self): + self._test_key_update(version=QuicProtocolVersion.DRAFT_23) + ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoContext: def __init__(self, key_phase: int = 0) -> None: self.aead: Optional[AEAD] = None self.cipher_suite: Optional[CipherSuite] = None self.hp: Optional[HeaderProtection] = None self.key_phase = key_phase self.secret: Optional[bytes] = None + self.version: Optional[int] = None ===========changed ref 3=========== # module: aioquic.quic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 DRAFT_21 = 0xFF000015 DRAFT_22 = 0xFF000016 DRAFT_23 = 0xFF000017 + DRAFT_24 = 0xFF000018 ===========changed ref 4=========== # module: aioquic.quic.crypto class CryptoContext: + def setup(self, cipher_suite: CipherSuite, secret: bytes, version: int) -> None: - def setup(self, cipher_suite: CipherSuite, secret: bytes) -> None: hp_cipher_name, aead_cipher_name = CIPHER_SUITES[cipher_suite] key, iv, hp = derive_key_iv_hp(cipher_suite, secret) self.aead = AEAD(aead_cipher_name, key, iv) self.cipher_suite = cipher_suite self.hp = HeaderProtection(hp_cipher_name, hp) self.secret = secret + self.version = version ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_decryption_error(self): with client_and_server() as (client, server): # mess with encryption key server._cryptos[tls.Epoch.ONE_RTT].send.setup( + cipher_suite=tls.CipherSuite.AES_128_GCM_SHA256, - tls.CipherSuite.AES_128_GCM_SHA256, bytes(48) + secret=bytes(48), + version=QuicProtocolVersion.DRAFT_23, ) # server sends close server.close(error_code=QuicErrorCode.NO_ERROR) for data, addr in server.datagrams_to_send(now=time.time()): client.receive_datagram(data, SERVER_ADDR, now=time.time()) ===========changed ref 6=========== # module: aioquic.quic.crypto def next_key_phase(self: CryptoContext) -> CryptoContext: algorithm = cipher_suite_hash(self.cipher_suite) + + if self.version < QuicProtocolVersion.DRAFT_24: + label = b"traffic upd" + else: + label = b"quic ku" crypto = CryptoContext(key_phase=int(not self.key_phase)) crypto.setup( + cipher_suite=self.cipher_suite, - self.cipher_suite, + secret=hkdf_expand_label( - hkdf_expand_label( + algorithm, self.secret, label, b"", algorithm.digest_size - algorithm, self.secret, b"traffic upd", b"", algorithm.digest_size ), + version=self.version, ) return crypto ===========changed ref 7=========== # module: tests.test_crypto class CryptoTest(TestCase): def test_encrypt_short_server(self): pair = CryptoPair() pair.send.setup( + cipher_suite=INITIAL_CIPHER_SUITE, - INITIAL_CIPHER_SUITE, + secret=binascii.unhexlify( - binascii.unhexlify( "310281977cb8c1c1c1212d784b2d29e5a6489e23de848d370a5a2f9537f3a100" ), + version=QuicProtocolVersion.DRAFT_23, ) packet = pair.encrypt_packet( SHORT_SERVER_PLAIN_HEADER, SHORT_SERVER_PLAIN_PAYLOAD, SHORT_SERVER_PACKET_NUMBER, ) self.assertEqual(packet, SHORT_SERVER_ENCRYPTED_PACKET)
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
113dbbf4463ce3a1b18b055498aa09d8e2f785c1
[quic] add support for draft-24
<0>:<add> # force version negotiation <add> configuration.supported_versions.insert(0, 0x1A2A3A4A) <del> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_23]
# module: examples.interop def test_version_negotiation(server: Server, configuration: QuicConfiguration): <0> configuration.supported_versions = [0x1A2A3A4A, QuicProtocolVersion.DRAFT_23] <1> <2> async with connect( <3> server.host, server.port, configuration=configuration <4> ) as protocol: <5> await protocol.ping() <6> <7> # check log <8> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <9> "traces" <10> ][0]["events"]: <11> if ( <12> category == "transport" <13> and event == "packet_received" <14> and data["packet_type"] == "version_negotiation" <15> ): <16> server.result |= Result.V <17>
===========unchanged ref 0=========== at: examples.interop Result() at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 0=========== # module: aioquic.h0.connection + H0_ALPN = ["hq-24", "hq-23"] - H0_ALPN = ["hq-23"] ===========changed ref 1=========== # module: aioquic.h3.connection logger = logging.getLogger("http3") + H3_ALPN = ["h3-24", "h3-23"] - H3_ALPN = ["h3-23"] ===========changed ref 2=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: """ A QUIC configuration. """ alpn_protocols: Optional[List[str]] = None """ A list of supported ALPN protocols. """ connection_id_length: int = 8 """ The length in bytes of local connection IDs. """ idle_timeout: float = 60.0 """ The idle timeout in seconds. The connection is terminated if nothing is received for the given duration. """ is_client: bool = True """ Whether this is the client side of the QUIC connection. """ quic_logger: Optional[QuicLogger] = None """ The :class:`~aioquic.quic.logger.QuicLogger` instance to log events to. """ secrets_log_file: TextIO = None """ A file-like object in which to log traffic secrets. This is useful to analyze traffic captures with Wireshark. """ server_name: Optional[str] = None """ The server name to send during the TLS handshake the Server Name Indication. .. note:: This is only used by clients. """ session_ticket: Optional[SessionTicket] = None """ The TLS session ticket which should be used for session resumption. """ cadata: Optional[bytes] = None cafile: Optional[str] = None capath: Optional[str] = None certificate: Any = None certificate_chain: List[Any] = field(default_factory=list) private_key: Any = None supported_versions: List[int] = field( + default_factory=lambda: [ + QuicProtocolVersion.DRAFT_24, + QuicProtocolVersion.DRAFT_23, + ] - default_factory=lambda: [QuicProtocolVersion.DRAFT_23] ) verify_mode: Optional[int] = None
aioquic.quic.packet/pull_quic_transport_parameters
Modified
aiortc~aioquic
e33434efb2349c79e0c086d00095bf1289d7f715
[interop] add explicit test for quantum readiness
<8>:<add> if param_id in PARAMS: <del> if param_id < len(PARAMS):
# module: aioquic.quic.packet def pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters: <0> params = QuicTransportParameters() <1> <2> with pull_block(buf, 2) as length: <3> end = buf.tell() + length <4> while buf.tell() < end: <5> param_id = buf.pull_uint16() <6> param_len = buf.pull_uint16() <7> param_start = buf.tell() <8> if param_id < len(PARAMS): <9> # parse known parameter <10> param_name, param_type = PARAMS[param_id] <11> if param_type == int: <12> setattr(params, param_name, buf.pull_uint_var()) <13> elif param_type == bytes: <14> setattr(params, param_name, buf.pull_bytes(param_len)) <15> elif param_type == QuicPreferredAddress: <16> setattr(params, param_name, pull_quic_preferred_address(buf)) <17> else: <18> setattr(params, param_name, True) <19> else: <20> # skip unknown parameter <21> buf.pull_bytes(param_len) <22> assert buf.tell() == param_start + param_len <23> <24> return params <25>
===========unchanged ref 0=========== at: aioquic.quic.packet QuicPreferredAddress(ipv4_address: Optional[Tuple[str, int]], ipv6_address: Optional[Tuple[str, int]], connection_id: bytes, stateless_reset_token: bytes) QuicTransportParameters(original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_active_migration: Optional[bool]=False, preferred_address: Optional[QuicPreferredAddress]=None, active_connection_id_limit: Optional[int]=None, quantum_readiness: Optional[bytes]=None) ===========unchanged ref 1=========== PARAMS = { 0: ("original_connection_id", bytes), 1: ("idle_timeout", int), 2: ("stateless_reset_token", bytes), 3: ("max_packet_size", int), 4: ("initial_max_data", int), 5: ("initial_max_stream_data_bidi_local", int), 6: ("initial_max_stream_data_bidi_remote", int), 7: ("initial_max_stream_data_uni", int), 8: ("initial_max_streams_bidi", int), 9: ("initial_max_streams_uni", int), 10: ("ack_delay_exponent", int), 11: ("max_ack_delay", int), 12: ("disable_active_migration", bool), 13: ("preferred_address", QuicPreferredAddress), 14: ("active_connection_id_limit", int), 3127: ("quantum_readiness", bytes), } pull_quic_preferred_address(buf: Buffer) -> QuicPreferredAddress ===========changed ref 0=========== # module: aioquic.quic.packet @dataclass class QuicTransportParameters: original_connection_id: Optional[bytes] = None idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None + quantum_readiness: Optional[bytes] = None ===========changed ref 1=========== # module: aioquic.quic.packet + PARAMS = { - PARAMS = [ + 0: ("original_connection_id", bytes), - ("original_connection_id", bytes), + 1: ("idle_timeout", int), - ("idle_timeout", int), + 2: ("stateless_reset_token", bytes), - ("stateless_reset_token", bytes), + 3: ("max_packet_size", int), - ("max_packet_size", int), + 4: ("initial_max_data", int), - ("initial_max_data", int), + 5: ("initial_max_stream_data_bidi_local", int), - ("initial_max_stream_data_bidi_local", int), + 6: ("initial_max_stream_data_bidi_remote", int), - ("initial_max_stream_data_bidi_remote", int), + 7: ("initial_max_stream_data_uni", int), - ("initial_max_stream_data_uni", int), + 8: ("initial_max_streams_bidi", int), - ("initial_max_streams_bidi", int), + 9: ("initial_max_streams_uni", int), - ("initial_max_streams_uni", int), + 10: ("ack_delay_exponent", int), - ("ack_delay_exponent", int), + 11: ("max_ack_delay", int), - ("max_ack_delay", int), + 12: ("disable_active_migration", bool), - ("disable_active_migration", bool), + 13: ("preferred_address", QuicPreferredAddress), - ("preferred_address", QuicPreferredAddress), + 14: ("active_connection_id_limit", int), - ("active_connection_id_limit", int), + 3127: ("quantum_readiness", bytes), + } - ]
aioquic.quic.packet/push_quic_transport_parameters
Modified
aiortc~aioquic
e33434efb2349c79e0c086d00095bf1289d7f715
[interop] add explicit test for quantum readiness
<1>:<add> for param_id, (param_name, param_type) in PARAMS.items(): <del> for param_id, (param_name, param_type) in enumerate(PARAMS):
# module: aioquic.quic.packet def push_quic_transport_parameters( buf: Buffer, params: QuicTransportParameters ) -> None: <0> with push_block(buf, 2): <1> for param_id, (param_name, param_type) in enumerate(PARAMS): <2> param_value = getattr(params, param_name) <3> if param_value is not None and param_value is not False: <4> buf.push_uint16(param_id) <5> with push_block(buf, 2): <6> if param_type == int: <7> buf.push_uint_var(param_value) <8> elif param_type == bytes: <9> buf.push_bytes(param_value) <10> elif param_type == QuicPreferredAddress: <11> push_quic_preferred_address(buf, param_value) <12>
===========unchanged ref 0=========== at: aioquic.quic.packet QuicTransportParameters(original_connection_id: Optional[bytes]=None, idle_timeout: Optional[int]=None, stateless_reset_token: Optional[bytes]=None, max_packet_size: Optional[int]=None, initial_max_data: Optional[int]=None, initial_max_stream_data_bidi_local: Optional[int]=None, initial_max_stream_data_bidi_remote: Optional[int]=None, initial_max_stream_data_uni: Optional[int]=None, initial_max_streams_bidi: Optional[int]=None, initial_max_streams_uni: Optional[int]=None, ack_delay_exponent: Optional[int]=None, max_ack_delay: Optional[int]=None, disable_active_migration: Optional[bool]=False, preferred_address: Optional[QuicPreferredAddress]=None, active_connection_id_limit: Optional[int]=None, quantum_readiness: Optional[bytes]=None) PARAMS = { 0: ("original_connection_id", bytes), 1: ("idle_timeout", int), 2: ("stateless_reset_token", bytes), 3: ("max_packet_size", int), 4: ("initial_max_data", int), 5: ("initial_max_stream_data_bidi_local", int), 6: ("initial_max_stream_data_bidi_remote", int), 7: ("initial_max_stream_data_uni", int), 8: ("initial_max_streams_bidi", int), 9: ("initial_max_streams_uni", int), 10: ("ack_delay_exponent", int), 11: ("max_ack_delay", int), 12: ("disable_active_migration", bool), 13: ("preferred_address", QuicPreferredAddress), 14: ("active_connection_id_limit", int), 3127: ("quantum_readiness", bytes), } ===========changed ref 0=========== # module: aioquic.quic.packet @dataclass class QuicTransportParameters: original_connection_id: Optional[bytes] = None idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None + quantum_readiness: Optional[bytes] = None ===========changed ref 1=========== # module: aioquic.quic.packet def pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters: params = QuicTransportParameters() with pull_block(buf, 2) as length: end = buf.tell() + length while buf.tell() < end: param_id = buf.pull_uint16() param_len = buf.pull_uint16() param_start = buf.tell() + if param_id in PARAMS: - if param_id < len(PARAMS): # parse known parameter param_name, param_type = PARAMS[param_id] if param_type == int: setattr(params, param_name, buf.pull_uint_var()) elif param_type == bytes: setattr(params, param_name, buf.pull_bytes(param_len)) elif param_type == QuicPreferredAddress: setattr(params, param_name, pull_quic_preferred_address(buf)) else: setattr(params, param_name, True) else: # skip unknown parameter buf.pull_bytes(param_len) assert buf.tell() == param_start + param_len return params ===========changed ref 2=========== # module: aioquic.quic.packet + PARAMS = { - PARAMS = [ + 0: ("original_connection_id", bytes), - ("original_connection_id", bytes), + 1: ("idle_timeout", int), - ("idle_timeout", int), + 2: ("stateless_reset_token", bytes), - ("stateless_reset_token", bytes), + 3: ("max_packet_size", int), - ("max_packet_size", int), + 4: ("initial_max_data", int), - ("initial_max_data", int), + 5: ("initial_max_stream_data_bidi_local", int), - ("initial_max_stream_data_bidi_local", int), + 6: ("initial_max_stream_data_bidi_remote", int), - ("initial_max_stream_data_bidi_remote", int), + 7: ("initial_max_stream_data_uni", int), - ("initial_max_stream_data_uni", int), + 8: ("initial_max_streams_bidi", int), - ("initial_max_streams_bidi", int), + 9: ("initial_max_streams_uni", int), - ("initial_max_streams_uni", int), + 10: ("ack_delay_exponent", int), - ("ack_delay_exponent", int), + 11: ("max_ack_delay", int), - ("max_ack_delay", int), + 12: ("disable_active_migration", bool), - ("disable_active_migration", bool), + 13: ("preferred_address", QuicPreferredAddress), - ("preferred_address", QuicPreferredAddress), + 14: ("active_connection_id_limit", int), - ("active_connection_id_limit", int), + 3127: ("quantum_readiness", bytes), + } - ]
examples.interop/print_result
Modified
aiortc~aioquic
e33434efb2349c79e0c086d00095bf1289d7f715
[interop] add explicit test for quantum readiness
<1>:<add> result = result[0:8] + " " + result[8:16] + " " + result[16:] <del> result = result[0:7] + " " + result[7:13] + " " + result[13:]
# module: examples.interop def print_result(server: Server) -> None: <0> result = str(server.result).replace("three", "3") <1> result = result[0:7] + " " + result[7:13] + " " + result[13:] <2> print("%s%s%s" % (server.name, " " * (20 - len(server.name)), result)) <3>
===========unchanged ref 0=========== at: examples.interop.test_throughput tcp_elapsed = time.time() - start quic_elapsed = time.time() - start ===========changed ref 0=========== # module: examples.interop + def test_quantum_readiness(server: Server, configuration: QuicConfiguration): + configuration.quantum_readiness_test = True + async with connect( + server.host, server.port, configuration=configuration + ) as protocol: + await protocol.ping() + server.result |= Result.Q + ===========changed ref 1=========== # module: examples.interop class Result(Flag): + V = 0x000001 - V = 0x0001 + H = 0x000002 - H = 0x0002 + D = 0x000004 - D = 0x0004 + C = 0x000008 - C = 0x0008 + R = 0x000010 - R = 0x0010 + Z = 0x000020 - Z = 0x0020 + S = 0x000040 - S = 0x0040 + Q = 0x000080 - M = 0x0080 - B = 0x0100 - U = 0x0200 - P = 0x0400 - E = 0x0800 - T = 0x1000 - three = 0x2000 - d = 0x4000 - p = 0x8000 ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_quantum_readiness(self): + with client_and_server(client_options={"quantum_readiness_test": True},) as ( + client, + server, + ): + stream_id = client.get_next_available_stream_id() + client.send_stream_data(stream_id, b"hello") + + roundtrip(client, server) + + received = None + while True: + event = server.next_event() + if isinstance(event, events.StreamDataReceived): + received = event.data + elif event is None: + break + + self.assertEqual(received, b"hello") + ===========changed ref 3=========== # module: aioquic.quic.packet def push_quic_transport_parameters( buf: Buffer, params: QuicTransportParameters ) -> None: with push_block(buf, 2): + for param_id, (param_name, param_type) in PARAMS.items(): - for param_id, (param_name, param_type) in enumerate(PARAMS): param_value = getattr(params, param_name) if param_value is not None and param_value is not False: buf.push_uint16(param_id) with push_block(buf, 2): if param_type == int: buf.push_uint_var(param_value) elif param_type == bytes: buf.push_bytes(param_value) elif param_type == QuicPreferredAddress: push_quic_preferred_address(buf, param_value) ===========changed ref 4=========== # module: aioquic.quic.packet @dataclass class QuicTransportParameters: original_connection_id: Optional[bytes] = None idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None + quantum_readiness: Optional[bytes] = None ===========changed ref 5=========== # module: aioquic.quic.packet def pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters: params = QuicTransportParameters() with pull_block(buf, 2) as length: end = buf.tell() + length while buf.tell() < end: param_id = buf.pull_uint16() param_len = buf.pull_uint16() param_start = buf.tell() + if param_id in PARAMS: - if param_id < len(PARAMS): # parse known parameter param_name, param_type = PARAMS[param_id] if param_type == int: setattr(params, param_name, buf.pull_uint_var()) elif param_type == bytes: setattr(params, param_name, buf.pull_bytes(param_len)) elif param_type == QuicPreferredAddress: setattr(params, param_name, pull_quic_preferred_address(buf)) else: setattr(params, param_name, True) else: # skip unknown parameter buf.pull_bytes(param_len) assert buf.tell() == param_start + param_len return params ===========changed ref 6=========== # module: aioquic.quic.packet + PARAMS = { - PARAMS = [ + 0: ("original_connection_id", bytes), - ("original_connection_id", bytes), + 1: ("idle_timeout", int), - ("idle_timeout", int), + 2: ("stateless_reset_token", bytes), - ("stateless_reset_token", bytes), + 3: ("max_packet_size", int), - ("max_packet_size", int), + 4: ("initial_max_data", int), - ("initial_max_data", int), + 5: ("initial_max_stream_data_bidi_local", int), - ("initial_max_stream_data_bidi_local", int), + 6: ("initial_max_stream_data_bidi_remote", int), - ("initial_max_stream_data_bidi_remote", int), + 7: ("initial_max_stream_data_uni", int), - ("initial_max_stream_data_uni", int), + 8: ("initial_max_streams_bidi", int), - ("initial_max_streams_bidi", int), + 9: ("initial_max_streams_uni", int), - ("initial_max_streams_uni", int), + 10: ("ack_delay_exponent", int), - ("ack_delay_exponent", int), + 11: ("max_ack_delay", int), - ("max_ack_delay", int), + 12: ("disable_active_migration", bool), - ("disable_active_migration", bool), + 13: ("preferred_address", QuicPreferredAddress), - ("preferred_address", QuicPreferredAddress), + 14: ("active_connection_id_limit", int), - ("active_connection_id_limit", int), + 3127: ("quantum_readiness", bytes), + } - ]
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
e33434efb2349c79e0c086d00095bf1289d7f715
[interop] add explicit test for quantum readiness
<11>:<add> quantum_readiness=b"Q" * 1200 <add> if self._configuration.quantum_readiness_test <add> else None, <27>:<add> buf = Buffer(capacity=3 * PACKET_MAX_SIZE) <del> buf = Buffer(capacity=512)
# module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: <0> quic_transport_parameters = QuicTransportParameters( <1> ack_delay_exponent=self._local_ack_delay_exponent, <2> active_connection_id_limit=self._local_active_connection_id_limit, <3> idle_timeout=int(self._configuration.idle_timeout * 1000), <4> initial_max_data=self._local_max_data, <5> initial_max_stream_data_bidi_local=self._local_max_stream_data_bidi_local, <6> initial_max_stream_data_bidi_remote=self._local_max_stream_data_bidi_remote, <7> initial_max_stream_data_uni=self._local_max_stream_data_uni, <8> initial_max_streams_bidi=self._local_max_streams_bidi, <9> initial_max_streams_uni=self._local_max_streams_uni, <10> max_ack_delay=25, <11> ) <12> if not self._is_client: <13> quic_transport_parameters.original_connection_id = ( <14> self._original_connection_id <15> ) <16> <17> # log event <18> if self._quic_logger is not None: <19> self._quic_logger.log_event( <20> category="transport", <21> event="parameters_set", <22> data=self._quic_logger.encode_transport_parameters( <23> owner="local", parameters=quic_transport_parameters <24> ), <25> ) <26> <27> buf = Buffer(capacity=512) <28> push_quic_transport_parameters(buf, quic_transport_parameters) <29> return buf.data <30>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._local_ack_delay_exponent = 3 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._original_connection_id = original_connection_id self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._write_connection_limits self._local_max_data *= 2 at: aioquic.quic.connection.QuicConnection.receive_datagram self._original_connection_id = self._peer_cid ===========changed ref 0=========== # module: examples.interop + def test_quantum_readiness(server: Server, configuration: QuicConfiguration): + configuration.quantum_readiness_test = True + async with connect( + server.host, server.port, configuration=configuration + ) as protocol: + await protocol.ping() + server.result |= Result.Q + ===========changed ref 1=========== # module: examples.interop def print_result(server: Server) -> None: result = str(server.result).replace("three", "3") + result = result[0:8] + " " + result[8:16] + " " + result[16:] - result = result[0:7] + " " + result[7:13] + " " + result[13:] print("%s%s%s" % (server.name, " " * (20 - len(server.name)), result)) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect_with_quantum_readiness(self): + with client_and_server(client_options={"quantum_readiness_test": True},) as ( + client, + server, + ): + stream_id = client.get_next_available_stream_id() + client.send_stream_data(stream_id, b"hello") + + roundtrip(client, server) + + received = None + while True: + event = server.next_event() + if isinstance(event, events.StreamDataReceived): + received = event.data + elif event is None: + break + + self.assertEqual(received, b"hello") + ===========changed ref 3=========== # module: aioquic.quic.packet def push_quic_transport_parameters( buf: Buffer, params: QuicTransportParameters ) -> None: with push_block(buf, 2): + for param_id, (param_name, param_type) in PARAMS.items(): - for param_id, (param_name, param_type) in enumerate(PARAMS): param_value = getattr(params, param_name) if param_value is not None and param_value is not False: buf.push_uint16(param_id) with push_block(buf, 2): if param_type == int: buf.push_uint_var(param_value) elif param_type == bytes: buf.push_bytes(param_value) elif param_type == QuicPreferredAddress: push_quic_preferred_address(buf, param_value) ===========changed ref 4=========== # module: examples.interop class Result(Flag): + V = 0x000001 - V = 0x0001 + H = 0x000002 - H = 0x0002 + D = 0x000004 - D = 0x0004 + C = 0x000008 - C = 0x0008 + R = 0x000010 - R = 0x0010 + Z = 0x000020 - Z = 0x0020 + S = 0x000040 - S = 0x0040 + Q = 0x000080 - M = 0x0080 - B = 0x0100 - U = 0x0200 - P = 0x0400 - E = 0x0800 - T = 0x1000 - three = 0x2000 - d = 0x4000 - p = 0x8000 ===========changed ref 5=========== # module: aioquic.quic.packet @dataclass class QuicTransportParameters: original_connection_id: Optional[bytes] = None idle_timeout: Optional[int] = None stateless_reset_token: Optional[bytes] = None max_packet_size: Optional[int] = None initial_max_data: Optional[int] = None initial_max_stream_data_bidi_local: Optional[int] = None initial_max_stream_data_bidi_remote: Optional[int] = None initial_max_stream_data_uni: Optional[int] = None initial_max_streams_bidi: Optional[int] = None initial_max_streams_uni: Optional[int] = None ack_delay_exponent: Optional[int] = None max_ack_delay: Optional[int] = None disable_active_migration: Optional[bool] = False preferred_address: Optional[QuicPreferredAddress] = None active_connection_id_limit: Optional[int] = None + quantum_readiness: Optional[bytes] = None ===========changed ref 6=========== # module: aioquic.quic.packet def pull_quic_transport_parameters(buf: Buffer) -> QuicTransportParameters: params = QuicTransportParameters() with pull_block(buf, 2) as length: end = buf.tell() + length while buf.tell() < end: param_id = buf.pull_uint16() param_len = buf.pull_uint16() param_start = buf.tell() + if param_id in PARAMS: - if param_id < len(PARAMS): # parse known parameter param_name, param_type = PARAMS[param_id] if param_type == int: setattr(params, param_name, buf.pull_uint_var()) elif param_type == bytes: setattr(params, param_name, buf.pull_bytes(param_len)) elif param_type == QuicPreferredAddress: setattr(params, param_name, pull_quic_preferred_address(buf)) else: setattr(params, param_name, True) else: # skip unknown parameter buf.pull_bytes(param_len) assert buf.tell() == param_start + param_len return params
examples.interop/test_http_3
Modified
aiortc~aioquic
2a914d62f21ae164250e609a21166a13e6d0fa18
[interop] perform additional HTTP/3 requests to trigger "d" check
<20>:<add> # perform more HTTP requests to use QPACK dynamic tables <del> # perform another HTTP request to use QPACK dynamic tables <21>:<add> for i in range(2): <add> events = await protocol.get( <del> events = await protocol.get( <22>:<add> "https://{}:{}{}".format(server.host, server.port, server.path) <del> "https://{}:{}{}".format(server.host, server.port, server.path) <23>:<add> ) <del> )
# module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): <0> if server.path is None: <1> return <2> <3> configuration.alpn_protocols = H3_ALPN <4> async with connect( <5> server.host, <6> server.port, <7> configuration=configuration, <8> create_protocol=HttpClient, <9> ) as protocol: <10> protocol = cast(HttpClient, protocol) <11> <12> # perform HTTP request <13> events = await protocol.get( <14> "https://{}:{}{}".format(server.host, server.port, server.path) <15> ) <16> if events and isinstance(events[0], HeadersReceived): <17> server.result |= Result.D <18> server.result |= Result.three <19> <20> # perform another HTTP request to use QPACK dynamic tables <21> events = await protocol.get( <22> "https://{}:{}{}".format(server.host, server.port, server.path) <23> ) <24> if events and isinstance(events[0], HeadersReceived): <25> http = cast(H3Connection, protocol._http) <26> protocol._quic._logger.info( <27> "QPACK decoder bytes RX %d TX %d", <28> http._decoder_bytes_received, <29> http._decoder_bytes_sent, <30> ) <31> protocol._quic._logger.info( <32> "QPACK encoder bytes RX %d TX %d", <33> http._encoder_bytes_received, <34> http._encoder_bytes_sent, <35> ) <36> if ( <37> http._decoder_bytes_received <38> and http._decoder_bytes_sent <39> and http._encoder_bytes_received <40> and http._encoder_bytes_sent <41> ): <42> server.result |= Result.d <43>
===========unchanged ref 0=========== at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", result: Result=field(default_factory=lambda: Result(0)), session_resumption_port: Optional[int]=None, throughput_file_suffix: str="", verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: http3_client HttpClient(*args, **kwargs) at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any
examples.interop/run
Modified
aiortc~aioquic
8d0065b4cbc6f6f394fcbb35a72c8f58cd2e8293
[interop] make a note of servers supporting structured logging
<1>:<add> if server.structured_logging: <add> server.result |= Result.L
# module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: <0> for server in servers: <1> for test_name, test_func in tests: <2> print("\n=== %s %s ===\n" % (server.name, test_name)) <3> configuration = QuicConfiguration( <4> alpn_protocols=H3_ALPN + H0_ALPN, <5> is_client=True, <6> quic_logger=QuicLogger(), <7> secrets_log_file=secrets_log_file, <8> verify_mode=server.verify_mode, <9> ) <10> if test_name == "test_throughput": <11> timeout = 60 <12> else: <13> timeout = 5 <14> try: <15> await asyncio.wait_for( <16> test_func(server, configuration), timeout=timeout <17> ) <18> except Exception as exc: <19> print(exc) <20> <21> if quic_log: <22> with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: <23> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) <24> <25> print("") <26> print_result(server) <27> <28> # print summary <29> if len(servers) > 1: <30> print("SUMMARY") <31> for server in servers: <32> print_result(server) <33>
===========unchanged ref 0=========== at: asyncio.tasks wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.interop Result() print_result(server: Server) -> None at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None structured_logging: bool = False throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: json dump(obj: Any, fp: IO[str], *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> None ===========changed ref 0=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None + structured_logging: bool = False throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ + Server("aioquic", "quic.aiortc.org", port=443, structured_logging=True), - Server("aioquic", "quic.aiortc.org", port=443), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com"), Server( "msquic", "quic.westus.cloudapp.azure.com", port=443, session_resumption_port=4433, + structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), + Server("mvfst", "fb.mvfst.net", structured_logging=True), - Server("mvfst", "fb.mvfst.net"), Server("ngtcp2", "nghttp2.org"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), Server("pandora", "pandora.cm.in.tum.de", verify_mode=ssl.CERT_NONE), + Server("picoquic", "test.privateoctopus.com", structured_logging=True), - Server("picoquic", "test.privateoctopus.com"), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=4433), Server("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quic</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s>("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quicly", "kazuhooku.com", verify_mode=ssl.CERT_NONE), Server("quinn", "ralith.com"), ]
examples.http3_client/HttpClient.__init__
Modified
aiortc~aioquic
e6250d1d2d87deeb18a6d6814ad4915bd7626482
[interop] check HTTP/3 pushes
<2>:<add> self.pushes: Dict[int, Deque[H3Event]] = {}
# module: examples.http3_client class HttpClient(QuicConnectionProtocol): def __init__(self, *args, **kwargs): <0> super().__init__(*args, **kwargs) <1> <2> self._http: Optional[HttpConnection] = None <3> self._request_events: Dict[int, Deque[H3Event]] = {} <4> self._request_waiter: Dict[int, asyncio.Future[Deque[H3Event]]] = {} <5> self._websockets: Dict[int, WebSocket] = {} <6> <7> if self._quic.configuration.alpn_protocols[0].startswith("hq-"): <8> self._http = H0Connection(self._quic) <9> else: <10> self._http = H3Connection(self._quic) <11>
===========unchanged ref 0=========== at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: examples.http3_client HttpConnection = Union[H0Connection, H3Connection] WebSocket(http: HttpConnection, stream_id: int, transmit: Callable[[], None]) at: typing Deque = _alias(collections.deque, 1, name='Deque') Dict = _alias(dict, 2, inst=False, name='Dict')
examples.http3_client/HttpClient.http_event_received
Modified
aiortc~aioquic
e6250d1d2d87deeb18a6d6814ad4915bd7626482
[interop] check HTTP/3 pushes
<14>:<add> elif event.push_id is not None: <del> else: <16>:<add> if event.push_id not in self.pushes: <add> self.pushes[event.push_id] = deque() <add> self.pushes[event.push_id].append(event) <del> print(event)
# module: examples.http3_client class HttpClient(QuicConnectionProtocol): def http_event_received(self, event: H3Event): <0> if isinstance(event, (HeadersReceived, DataReceived)): <1> stream_id = event.stream_id <2> if stream_id in self._request_events: <3> # http <4> self._request_events[event.stream_id].append(event) <5> if event.stream_ended: <6> request_waiter = self._request_waiter.pop(stream_id) <7> request_waiter.set_result(self._request_events.pop(stream_id)) <8> <9> elif stream_id in self._websockets: <10> # websocket <11> websocket = self._websockets[stream_id] <12> websocket.http_event_received(event) <13> <14> else: <15> # push <16> print(event) <17>
===========unchanged ref 0=========== at: _asyncio.Future set_result(result, /) at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_result(result: _T, /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: collections.deque append(x: _T) -> None at: examples.http3_client.HttpClient.__init__ self._request_events: Dict[int, Deque[H3Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[H3Event]]] = {} self._websockets: Dict[int, WebSocket] = {} at: examples.http3_client.WebSocket http_event_received(event: H3Event) at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: examples.http3_client class HttpClient(QuicConnectionProtocol): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) + self.pushes: Dict[int, Deque[H3Event]] = {} self._http: Optional[HttpConnection] = None self._request_events: Dict[int, Deque[H3Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[H3Event]]] = {} self._websockets: Dict[int, WebSocket] = {} if self._quic.configuration.alpn_protocols[0].startswith("hq-"): self._http = H0Connection(self._quic) else: self._http = H3Connection(self._quic)
aioquic.quic.connection/QuicConnection._write_stream_limits
Modified
aiortc~aioquic
2ee46bea21df5f7c38c2942875cee7c1e72a4953
[connection] avoid spurious logging raising MAX_STREAM_DATA
<0>:<add> """ <add> Raise MAX_STREAM_DATA if needed. <del> # raise MAX_STREAM_DATA if needed <1>:<add> <add> The only case where `stream.max_stream_data_local` is zero is for <add> locally created unidirectional streams. We skip such streams to avoid <add> spurious logging. <add> """ <add> if ( <add> stream.max_stream_data_local <add> and stream._recv_highest * 2 > stream.max_stream_data_local <del> if stream._recv_highest * 2 > stream.max_stream_data_local: <2>:<add> ):
# module: aioquic.quic.connection class QuicConnection: def _write_stream_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream ) -> None: <0> # raise MAX_STREAM_DATA if needed <1> if stream._recv_highest * 2 > stream.max_stream_data_local: <2> stream.max_stream_data_local *= 2 <3> self._logger.debug( <4> "Stream %d local max_stream_data raised to %d", <5> stream.stream_id, <6> stream.max_stream_data_local, <7> ) <8> if stream.max_stream_data_local_sent != stream.max_stream_data_local: <9> builder.start_frame( <10> QuicFrameType.MAX_STREAM_DATA, <11> self._on_max_stream_data_delivery, <12> (stream,), <13> ) <14> builder.buffer.push_uint_var(stream.stream_id) <15> builder.buffer.push_uint_var(stream.max_stream_data_local) <16> stream.max_stream_data_local_sent = stream.max_stream_data_local <17> <18> # log frame <19> if self._quic_logger is not None: <20> builder.quic_logger_frames.append( <21> self._quic_logger.encode_max_stream_data_frame( <22> maximum=stream.max_stream_data_local, stream_id=stream.stream_id <23> ) <24> ) <25>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection _on_max_stream_data_delivery(delivery: QuicDeliveryState, stream: QuicStream) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
examples.http3_client/HttpClient.http_event_received
Modified
aiortc~aioquic
0e7ad4c02b79a63b865cf3d27842e2ed2c2a16fc
[interop] rework HTTP/3 push test
<14>:<add> elif event.push_id in self.pushes: <del> elif event.push_id is not None: <16>:<del> if event.push_id not in self.pushes: <17>:<del> self.pushes[event.push_id] = deque()
# module: examples.http3_client class HttpClient(QuicConnectionProtocol): def http_event_received(self, event: H3Event): <0> if isinstance(event, (HeadersReceived, DataReceived)): <1> stream_id = event.stream_id <2> if stream_id in self._request_events: <3> # http <4> self._request_events[event.stream_id].append(event) <5> if event.stream_ended: <6> request_waiter = self._request_waiter.pop(stream_id) <7> request_waiter.set_result(self._request_events.pop(stream_id)) <8> <9> elif stream_id in self._websockets: <10> # websocket <11> websocket = self._websockets[stream_id] <12> websocket.http_event_received(event) <13> <14> elif event.push_id is not None: <15> # push <16> if event.push_id not in self.pushes: <17> self.pushes[event.push_id] = deque() <18> self.pushes[event.push_id].append(event) <19>
===========unchanged ref 0=========== at: _asyncio.Future set_result(result, /) at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_result(result: _T, /) -> None __iter__ = __await__ # make compatible with 'yield from'. at: collections.deque append(x: _T) -> None at: examples.http3_client.HttpClient.__init__ self._request_events: Dict[int, Deque[H3Event]] = {} self._request_waiter: Dict[int, asyncio.Future[Deque[H3Event]]] = {} self._websockets: Dict[int, WebSocket] = {} at: examples.http3_client.HttpClient.websocket websocket = WebSocket( http=self._http, stream_id=stream_id, transmit=self.transmit ) at: examples.http3_client.WebSocket http_event_received(event: H3Event) at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]
examples.interop/test_http_3
Modified
aiortc~aioquic
0e7ad4c02b79a63b865cf3d27842e2ed2c2a16fc
[interop] rework HTTP/3 push test
<45>:<add> # check push support <del> # check push support <46>:<add> if server.push_path is not None: <add> protocol.pushes.clear() <del> if protocol.pushes: <47>:<add> await protocol.get( <add> "https://{}:{}{}".format(server.host, server.port, server.push_path) <add> ) <add> await asyncio.sleep(0.5) <add> for push_id, events in protocol.pushes.items(): <add> if ( <add> len(events) >= 3 <add> and isinstance(events[0], PushPromiseReceived) <add> and isinstance(events[1], HeadersReceived) <add> and isinstance(events[2], DataReceived) <add> ): <add> protocol._quic._logger.info( <add> "Push promise %d for %s received (status %s)", <add> push_id, <add> dict(events[0].headers)[b":path
# module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): <0> if server.path is None: <1> return <2> <3> configuration.alpn_protocols = H3_ALPN <4> async with connect( <5> server.host, <6> server.port, <7> configuration=configuration, <8> create_protocol=HttpClient, <9> ) as protocol: <10> protocol = cast(HttpClient, protocol) <11> <12> # perform HTTP request <13> events = await protocol.get( <14> "https://{}:{}{}".format(server.host, server.port, server.path) <15> ) <16> if events and isinstance(events[0], HeadersReceived): <17> server.result |= Result.D <18> server.result |= Result.three <19> <20> # perform more HTTP requests to use QPACK dynamic tables <21> for i in range(2): <22> events = await protocol.get( <23> "https://{}:{}{}".format(server.host, server.port, server.path) <24> ) <25> if events and isinstance(events[0], HeadersReceived): <26> http = cast(H3Connection, protocol._http) <27> protocol._quic._logger.info( <28> "QPACK decoder bytes RX %d TX %d", <29> http._decoder_bytes_received, <30> http._decoder_bytes_sent, <31> ) <32> protocol._quic._logger.info( <33> "QPACK encoder bytes RX %d TX %d", <34> http._encoder_bytes_received, <35> http._encoder_bytes_sent, <36> ) <37> if ( <38> http._decoder_bytes_received <39> and http._decoder_bytes_sent <40> and http._encoder_bytes_received <41> and http._encoder_bytes_sent <42> ): <43> server.result |= Result.d <44> <45> # check push support <46> if protocol.pushes: <47> server.result |= Result.p <48>
===========unchanged ref 0=========== at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, retry_port: Optional[int]=4434, path: str="/", push_path: Optional[str]=None, result: Result=field(default_factory=lambda: Result(0)), session_resumption_port: Optional[int]=None, structured_logging: bool=False, throughput_file_suffix: str="", verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" push_path: Optional[str] = None result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None structured_logging: bool = False throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: http3_client HttpClient(*args, **kwargs) at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any ===========changed ref 0=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True retry_port: Optional[int] = 4434 path: str = "/" + push_path: Optional[str] = None result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None structured_logging: bool = False throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ + Server( + "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True - Server("aioquic", "quic.aiortc.org", port=443, structured_logging=True), + ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433), Server("gquic", "quic.rocks", retry_port=None), + Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), - Server("lsquic", "http3-test.litespeedtech.com"), Server( "msquic", "quic.westus.cloudapp.azure.com", port=443, session_resumption_port=4433, structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), + Server("mvfst", "fb.mvfst.net", push_path="/push", structured_logging=True), - Server("mvfst", "fb.mvfst.net", path="/push", structured_logging=True), + Server("ngtcp2", "nghttp2.org", push_path="/?push=/100"), - Server("ngtcp2", "nghttp2.org", path="/?push=/100"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=443), Server("pandora", "pandora.cm.in.tum.de", verify_mode=ssl.CERT_NONE), Server("picoquic", "test.privateoctopus.com", structured_logging=True), Server("quant", "quant.eggert.org", http3=False), Server("</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s> structured_logging=True), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=4433), Server("quicker", "quicker.edm.uhasselt.be", retry_port=None), Server("quicly", "kazuhooku.com", verify_mode=ssl.CERT_NONE), Server("quinn", "ralith.com"), ] ===========changed ref 3=========== # module: examples.http3_client class HttpClient(QuicConnectionProtocol): def http_event_received(self, event: H3Event): if isinstance(event, (HeadersReceived, DataReceived)): stream_id = event.stream_id if stream_id in self._request_events: # http self._request_events[event.stream_id].append(event) if event.stream_ended: request_waiter = self._request_waiter.pop(stream_id) request_waiter.set_result(self._request_events.pop(stream_id)) elif stream_id in self._websockets: # websocket websocket = self._websockets[stream_id] websocket.http_event_received(event) + elif event.push_id in self.pushes: - elif event.push_id is not None: # push - if event.push_id not in self.pushes: - self.pushes[event.push_id] = deque() self.pushes[event.push_id].append(event)
examples.http3_client/run
Modified
aiortc~aioquic
57c92cc9a14ec3a8f72c3e394e686fca09a71442
[http3_client] make it possible to perform N parallel requests
<37>:<del> start = time.time() <38>:<del> if data is not None: <39>:<del> http_events = await client.post( <40>:<del> url, <41>:<del> data=data.encode("utf8"), <42>:<del> headers={"content-type": "application/x-www-form-urlencoded"}, <43>:<add> coros = [ <add> perform_http_request( <add> client=client, url=url, data=data, print_response=print_response <44>:<add> for i in range(parallel) <add> ] <del> else: <45>:<del> http_events = await client.get(url) <46>:<del> elapsed = time.time() - start <47>:<add> await asyncio.gather(*coros) <48>:<del> # print
# module: examples.http3_client + def run( + configuration: QuicConfiguration, + url: str, + data: str, + parallel: int, + print_response: bool, + ) -> None: - def run(configuration: QuicConfiguration, url: str, data: str) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme in ( <3> "https", <4> "wss", <5> ), "Only https:// or wss:// URLs are supported." <6> if ":" in parsed.netloc: <7> host, port_str = parsed.netloc.split(":") <8> port = int(port_str) <9> else: <10> host = parsed.netloc <11> port = 443 <12> <13> async with connect( <14> host, <15> port, <16> configuration=configuration, <17> create_protocol=HttpClient, <18> session_ticket_handler=save_session_ticket, <19> ) as client: <20> client = cast(HttpClient, client) <21> <22> if parsed.scheme == "wss": <23> ws = await client.websocket(url, subprotocols=["chat", "superchat"]) <24> <25> # send some messages and receive reply <26> for i in range(2): <27> message = "Hello {}, WebSocket!".format(i) <28> print("> " + message) <29> await ws.send(message) <30> <31> message = await ws.recv() <32> print("< " + message) <33> <34> await ws.close() <35> else: <36> # perform request <37> start = time.time() <38> if data is not None: <39> http_events = await client.post( <40> url, <41> data=data.encode("utf8"), <42> headers={"content-type": "application/x-www-form-urlencoded"}, <43> ) <44> else: <45> http_events = await client.get(url) <46> elapsed = time.time() - start <47> <48> # print</s>
===========below chunk 0=========== # module: examples.http3_client + def run( + configuration: QuicConfiguration, + url: str, + data: str, + parallel: int, + print_response: bool, + ) -> None: - def run(configuration: QuicConfiguration, url: str, data: str) -> None: # offset: 1 octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): octets += len(http_event.data) logger.info( "Received %d bytes in %.1f s (%.3f Mbps)" % (octets, elapsed, octets * 8 / elapsed / 1000000) ) # print response for http_event in http_events: if isinstance(http_event, HeadersReceived): headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() elif isinstance(http_event, DataReceived): sys.stdout.buffer.write(http_event.data) sys.stdout.buffer.flush() ===========unchanged ref 0=========== at: _pickle dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) at: examples.http3_client logger = logging.getLogger("client") HttpClient(*args, **kwargs) args = parser.parse_args() at: examples.http3_client.HttpClient get(url: str, headers: Dict={}) -> Deque[H3Event] at: examples.http3_client.perform_http_request start = time.time() at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: pickle dump, dumps, load, loads = _dump, _dumps, _load, _loads at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: examples.http3_client + def perform_http_request( + client: HttpClient, url: str, data: str, print_response: bool + ) -> None: + # perform request + start = time.time() + if data is not None: + http_events = await client.post( + url, + data=data.encode("utf8"), + headers={"content-type": "application/x-www-form-urlencoded"}, + ) + else: + http_events = await client.get(url) + elapsed = time.time() - start + + # print speed + octets = 0 + for http_event in http_events: + if isinstance(http_event, DataReceived): + octets += len(http_event.data) + logger.info( + "Received %d bytes in %.1f s (%.3f Mbps)" + % (octets, elapsed, octets * 8 / elapsed / 1000000) + ) + + # print response + if print_response: + for http_event in http_events: + if isinstance(http_event, HeadersReceived): + headers = b"" + for k, v in http_event.headers: + headers += k + b": " + v + b"\r\n" + if headers: + sys.stderr.buffer.write(headers + b"\r\n") + sys.stderr.buffer.flush() + elif isinstance(http_event, DataReceived): + sys.stdout.buffer.write(http_event.data) + sys.stdout.buffer.flush() +
aioquic.quic.logger/QuicLoggerTrace.encode_transport_parameters
Modified
aiortc~aioquic
d1a5ed93b60922d1068430b1f59ae2d1723d97b8
[qlog] fix dumping `bytes` transport parameters
<5>:<add> data[param_name] = hexdump(param_value) <del> data[param_name] = param_value
# module: aioquic.quic.logger class QuicLoggerTrace: def encode_transport_parameters( self, owner: str, parameters: QuicTransportParameters ) -> Dict[str, Any]: <0> data: Dict[str, Any] = {"owner": owner} <1> for param_name, param_value in parameters.__dict__.items(): <2> if isinstance(param_value, bool): <3> data[param_name] = param_value <4> elif isinstance(param_value, bytes): <5> data[param_name] = param_value <6> elif isinstance(param_value, int): <7> data[param_name] = param_value <8> return data <9>
===========unchanged ref 0=========== at: aioquic.quic.logger hexdump(data: bytes) -> str at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.quic.packet_builder/QuicPacketBuilder.__init__
Modified
aiortc~aioquic
274fd9ddebdfd51b49da6de7e4d11d0b8167ca8f
[packet builder] clarify flight bytes accounting
<13>:<del> self._ack_eliciting = False <15>:<add> self._datagram_flight_bytes = 0
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): <0> self.max_flight_bytes: Optional[int] = None <1> self.max_total_bytes: Optional[int] = None <2> self.quic_logger_frames: Optional[List[Dict]] = None <3> <4> self._host_cid = host_cid <5> self._pad_first_datagram = pad_first_datagram <6> self._peer_cid = peer_cid <7> self._peer_token = peer_token <8> self._quic_logger = quic_logger <9> self._spin_bit = spin_bit <10> self._version = version <11> <12> # assembled datagrams and packets <13> self._ack_eliciting = False <14> self._datagrams: List[bytes] = [] <15> self._datagram_init = True <16> self._packets: List[QuicSentPacket] = [] <17> self._flight_bytes = 0 <18> self._total_bytes = 0 <19> <20> # current packet <21> self._header_size = 0 <22> self._packet: Optional[QuicSentPacket] = None <23> self._packet_crypto: Optional[CryptoPair] = None <24> self._packet_long_header = False <25> self._packet_number = packet_number <26> self._packet_start = 0 <27> self._packet_type = 0 <28> <29> self.buffer = Buffer(PACKET_MAX_SIZE) <30> self._buffer_capacity = PACKET_MAX_SIZE <31>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder PACKET_MAX_SIZE = 1280 QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram self._flight_bytes += self._datagram_flight_bytes self._total_bytes += datagram_bytes self._datagram_init = True at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self._pad_first_datagram = False self._datagram_flight_bytes += self._packet.sent_bytes self._packet_number += 1 self._packet = None self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicPacketBuilder.flush self._datagrams = [] self._packets = [] at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._buffer_capacity = remaining_flight_bytes self._buffer_capacity = remaining_total_bytes self._datagram_flight_bytes = 0 self._datagram_init = False self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto ===========unchanged ref 1=========== self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.quic.packet_builder/QuicPacketBuilder.start_frame
Modified
aiortc~aioquic
274fd9ddebdfd51b49da6de7e4d11d0b8167ca8f
[packet builder] clarify flight bytes accounting
<6>:<del> self._ack_eliciting = True
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_frame( self, frame_type: int, handler: Optional[QuicDeliveryHandler] = None, args: Sequence[Any] = [], ) -> None: <0> """ <1> Starts a new frame. <2> """ <3> self.buffer.push_uint_var(frame_type) <4> if frame_type not in NON_ACK_ELICITING_FRAME_TYPES: <5> self._packet.is_ack_eliciting = True <6> self._ack_eliciting = True <7> if frame_type not in NON_IN_FLIGHT_FRAME_TYPES: <8> self._packet.in_flight = True <9> if frame_type == QuicFrameType.CRYPTO: <10> self._packet.is_crypto_packet = True <11> if handler is not None: <12> self._packet.delivery_handlers.append((handler, args)) <13>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryHandler = Callable[..., None] at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._packet: Optional[QuicSentPacket] = None self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self._packet = None at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) at: typing Sequence = _alias(collections.abc.Sequence, 1) ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets - self._ack_eliciting = False self._datagrams: List[bytes] = [] + self._datagram_flight_bytes = 0 self._datagram_init = True self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE
aioquic.quic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
274fd9ddebdfd51b49da6de7e4d11d0b8167ca8f
[packet builder] clarify flight bytes accounting
<4>:<del> self._ack_eliciting = False <23>:<add> self._datagram_flight_bytes = 0
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> self._ack_eliciting = False <5> <6> # if there is too little space remaining, start a new datagram <7> # FIXME: the limit is arbitrary! <8> packet_start = buf.tell() <9> if self._buffer_capacity - packet_start < 128: <10> self._flush_current_datagram() <11> packet_start = 0 <12> <13> # initialize datagram if needed <14> if self._datagram_init: <15> if self.max_flight_bytes is not None: <16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <17> if remaining_flight_bytes < self._buffer_capacity: <18> self._buffer_capacity = remaining_flight_bytes <19> if self.max_total_bytes is not None: <20> remaining_total_bytes = self.max_total_bytes - self._total_bytes <21> if remaining_total_bytes < self._buffer_capacity: <22> self._buffer_capacity = remaining_total_bytes <23> self._datagram_init = False <24> <25> # calculate header size <26> packet_long_header = is_long_header(packet_type) <27> if packet_long_header: <28> header_size = 11 + len(self._peer_cid) + len(self._host_cid) <29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <30> token_length = len(self._peer_token) <31> header_size += size_uint_var(token_length) + token_length <32> else: <33> header_size = 3 + len(self._peer_cid) <34> <35> # check we have enough space <36> if packet_start + header_size >= self._buffer_capacity: <37> raise QuicPacketBuilderStop <38> </s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) QuicPacketBuilderStop(*args: object) at: aioquic.quic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None _flush_current_datagram(self) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._datagram_flight_bytes = 0 self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram self._flight_bytes += self._datagram_flight_bytes ===========unchanged ref 1=========== self._total_bytes += datagram_bytes self._datagram_init = True at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self._datagram_flight_bytes += self._packet.sent_bytes self._packet_number += 1 self._packet = None self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicSentPacket quic_logger_frames: List[Dict] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_frame( self, frame_type: int, handler: Optional[QuicDeliveryHandler] = None, args: Sequence[Any] = [], ) -> None: """ Starts a new frame. """ self.buffer.push_uint_var(frame_type) if frame_type not in NON_ACK_ELICITING_FRAME_TYPES: self._packet.is_ack_eliciting = True - self._ack_eliciting = True if frame_type not in NON_IN_FLIGHT_FRAME_TYPES: self._packet.in_flight = True if frame_type == QuicFrameType.CRYPTO: self._packet.is_crypto_packet = True if handler is not None: self._packet.delivery_handlers.append((handler, args)) ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets - self._ack_eliciting = False self._datagrams: List[bytes] = [] + self._datagram_flight_bytes = 0 self._datagram_init = True self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE
aioquic.quic.packet_builder/QuicPacketBuilder.end_packet
Modified
aiortc~aioquic
274fd9ddebdfd51b49da6de7e4d11d0b8167ca8f
[packet builder] clarify flight bytes accounting
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def end_packet(self) -> bool: <0> """ <1> Ends the current packet. <2> <3> Returns `True` if the packet contains data, `False` otherwise. <4> """ <5> buf = self.buffer <6> empty = True <7> packet_size = buf.tell() - self._packet_start <8> if packet_size > self._header_size: <9> empty = False <10> <11> # pad initial datagram <12> if self._pad_first_datagram: <13> if self.remaining_space: <14> buf.push_bytes(bytes(self.remaining_space)) <15> packet_size = buf.tell() - self._packet_start <16> <17> # log frame <18> if self._quic_logger is not None: <19> self._packet.quic_logger_frames.append( <20> self._quic_logger.encode_padding_frame() <21> ) <22> self._pad_first_datagram = False <23> <24> # write header <25> if self._packet_long_header: <26> length = ( <27> packet_size <28> - self._header_size <29> + PACKET_NUMBER_SEND_SIZE <30> + self._packet_crypto.aead_tag_size <31> ) <32> <33> buf.seek(self._packet_start) <34> buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) <35> buf.push_uint32(self._version) <36> buf.push_uint8(len(self._peer_cid)) <37> buf.push_bytes(self._peer_cid) <38> buf.push_uint8(len(self._host_cid)) <39> buf.push_bytes(self._host_cid) <40> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <41> buf.push_uint_var(len(self._peer_token)) <42> buf.push_bytes(self</s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def end_packet(self) -> bool: # offset: 1 buf.push_uint16(length | 0x4000) buf.push_uint16(self._packet_number & 0xFFFF) else: buf.seek(self._packet_start) buf.push_uint8( self._packet_type | (self._spin_bit << 5) | (self._packet_crypto.key_phase << 2) | (PACKET_NUMBER_SEND_SIZE - 1) ) buf.push_bytes(self._peer_cid) buf.push_uint16(self._packet_number & 0xFFFF) # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + self._header_size - packet_size ) if padding_size > 0: buf.seek(self._packet_start + packet_size) buf.push_bytes(bytes(padding_size)) packet_size += padding_size # encrypt in place plain = buf.data_slice(self._packet_start, self._packet_start + packet_size) buf.seek(self._packet_start) buf.push_bytes( self._packet_crypto.encrypt_packet( plain[0 : self._header_size], plain[self._header_size : packet_size], self._packet_number, ) ) self._packet.sent_bytes = buf.tell() - self._packet_start self._packets.append(self._packet) # short header packets cannot be coallesced, we need a new datagram if not self._packet_long_header: self._flush_current_datagram() self._packet_number += 1 else: # "cancel" the packet buf.seek(self._packet_start) self._packet = None self.qu</s> ===========below chunk 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def end_packet(self) -> bool: # offset: 2 <s> "cancel" the packet buf.seek(self._packet_start) self._packet = None self.quic_logger_frames = None return not empty ===========unchanged ref 0=========== at: aioquic.quic.packet_builder PACKET_NUMBER_SEND_SIZE = 2 at: aioquic.quic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None _flush_current_datagram(self) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version self._datagram_flight_bytes = 0 self._packets: List[QuicSentPacket] = [] self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.flush self._packets = [] at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._datagram_flight_bytes = 0 self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header ===========unchanged ref 1=========== self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames at: aioquic.quic.packet_builder.QuicSentPacket in_flight: bool sent_bytes: int = 0 quic_logger_frames: List[Dict] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_frame( self, frame_type: int, handler: Optional[QuicDeliveryHandler] = None, args: Sequence[Any] = [], ) -> None: """ Starts a new frame. """ self.buffer.push_uint_var(frame_type) if frame_type not in NON_ACK_ELICITING_FRAME_TYPES: self._packet.is_ack_eliciting = True - self._ack_eliciting = True if frame_type not in NON_IN_FLIGHT_FRAME_TYPES: self._packet.in_flight = True if frame_type == QuicFrameType.CRYPTO: self._packet.is_crypto_packet = True if handler is not None: self._packet.delivery_handlers.append((handler, args)) ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets - self._ack_eliciting = False self._datagrams: List[bytes] = [] + self._datagram_flight_bytes = 0 self._datagram_init = True self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE
aioquic.quic.packet_builder/QuicPacketBuilder._flush_current_datagram
Modified
aiortc~aioquic
274fd9ddebdfd51b49da6de7e4d11d0b8167ca8f
[packet builder] clarify flight bytes accounting
<3>:<add> self._flight_bytes += self._datagram_flight_bytes <add> self._total_bytes += datagram_bytes <4>:<del> if self._ack_eliciting: <5>:<del> self._flight_bytes += datagram_bytes <6>:<del> self._total_bytes += datagram_bytes
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def _flush_current_datagram(self) -> None: <0> datagram_bytes = self.buffer.tell() <1> if datagram_bytes: <2> self._datagrams.append(self.buffer.data) <3> self._datagram_init = True <4> if self._ack_eliciting: <5> self._flight_bytes += datagram_bytes <6> self._total_bytes += datagram_bytes <7> self.buffer.seek(0) <8>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._datagrams: List[bytes] = [] self._datagram_flight_bytes = 0 self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder.end_packet self._datagram_flight_bytes += self._packet.sent_bytes at: aioquic.quic.packet_builder.QuicPacketBuilder.flush self._datagrams = [] at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._datagram_flight_bytes = 0 self._datagram_init = False ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_frame( self, frame_type: int, handler: Optional[QuicDeliveryHandler] = None, args: Sequence[Any] = [], ) -> None: """ Starts a new frame. """ self.buffer.push_uint_var(frame_type) if frame_type not in NON_ACK_ELICITING_FRAME_TYPES: self._packet.is_ack_eliciting = True - self._ack_eliciting = True if frame_type not in NON_IN_FLIGHT_FRAME_TYPES: self._packet.in_flight = True if frame_type == QuicFrameType.CRYPTO: self._packet.is_crypto_packet = True if handler is not None: self._packet.delivery_handlers.append((handler, args)) ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets - self._ack_eliciting = False self._datagrams: List[bytes] = [] + self._datagram_flight_bytes = 0 self._datagram_init = True self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer - self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes + self._datagram_flight_bytes = 0 self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = E</s> ===========changed ref 3=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s>icPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size)
aioquic.quic.packet_builder/QuicPacketBuilder.flush
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<3>:<add> if self._packet is not None: <add> self._end_packet() <4>:<add>
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: <0> """ <1> Returns the assembled datagrams. <2> """ <3> self._flush_current_datagram() <4> datagrams = self._datagrams <5> packets = self._packets <6> self._datagrams = [] <7> self._packets = [] <8> return datagrams, packets <9>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._packet_crypto: Optional[CryptoPair] = None self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._buffer_capacity = remaining_flight_bytes self._buffer_capacity = remaining_total_bytes self._packet_crypto = crypto at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size +
aioquic.quic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<4>:<add> <add> # finish previous datagram <add> if self._packet is not None: <add> self._end_packet()
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> <5> # if there is too little space remaining, start a new datagram <6> # FIXME: the limit is arbitrary! <7> packet_start = buf.tell() <8> if self._buffer_capacity - packet_start < 128: <9> self._flush_current_datagram() <10> packet_start = 0 <11> <12> # initialize datagram if needed <13> if self._datagram_init: <14> if self.max_flight_bytes is not None: <15> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <16> if remaining_flight_bytes < self._buffer_capacity: <17> self._buffer_capacity = remaining_flight_bytes <18> if self.max_total_bytes is not None: <19> remaining_total_bytes = self.max_total_bytes - self._total_bytes <20> if remaining_total_bytes < self._buffer_capacity: <21> self._buffer_capacity = remaining_total_bytes <22> self._datagram_flight_bytes = 0 <23> self._datagram_init = False <24> <25> # calculate header size <26> packet_long_header = is_long_header(packet_type) <27> if packet_long_header: <28> header_size = 11 + len(self._peer_cid) + len(self._host_cid) <29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <30> token_length = len(self._peer_token) <31> header_size += size_uint_var(token_length) + token_length <32> else: <33> header_size = 3 + len(self._peer_cid) <34> <35> # check we have enough space <36> if packet_start + header_size >= self._buffer_capacity: <37> raise QuicPacketBuilderStop <38> </s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicPacketBuilderStop(*args: object) at: aioquic.quic.packet_builder.QuicPacketBuilder _end_packet() -> bool _flush_current_datagram() -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._datagram_flight_bytes = 0 self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 self._packet: Optional[QuicSentPacket] = None self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.quic.packet_builder.QuicPacketBuilder._end_packet self._datagram_flight_bytes += self._packet.sent_bytes self._packet = None at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram self._flight_bytes += self._datagram_flight_bytes self._total_bytes += datagram_bytes self._datagram_init = True at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool ===========unchanged ref 1=========== is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets
tests.test_connection/QuicConnectionTest.test_receive_datagram_wrong_version
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<11>:<del> builder.end_packet()
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_wrong_version(self): <0> client = create_standalone_client(self) <1> <2> builder = QuicPacketBuilder( <3> host_cid=client._peer_cid, <4> peer_cid=client.host_cid, <5> version=0xFF000011, # DRAFT_16 <6> ) <7> crypto = CryptoPair() <8> crypto.setup_initial(client.host_cid, is_client=False, version=client._version) <9> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <10> builder.buffer.push_bytes(bytes(1200)) <11> builder.end_packet() <12> <13> for datagram in builder.flush()[0]: <14> client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) <15> self.assertEqual(drop(client), 0) <16>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self) drop(sender) at: time time() -> float at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer + + # finish previous datagram + if self._packet is not None: + self._end_packet() # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_flight_bytes = 0 self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if</s> ===========changed ref 3=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s>start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size) ===========changed ref 4=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + def _end_packet(self) -> bool: + """ + Ends the current packet. + + Returns `True` if the packet contains data, `False` otherwise. + """ + buf = self.buffer + empty = True + packet_size = buf.tell() - self._packet_start + if packet_size > self._header_size: + empty = False + + # pad initial datagram + if self._pad_first_datagram: + if self.remaining_space: + buf.push_bytes(bytes(self.remaining_space)) + packet_size = buf.tell() - self._packet_start + + # log frame + if self._quic_logger is not None: + self._packet.quic_logger_frames.append( + self._quic_logger.encode_padding_frame() + ) + self._pad_first_datagram = False + + # write header + if self._packet_long_header: + length = ( + packet_size + - self._header_size + + PACKET_NUMBER_SEND_SIZE + + self._packet_crypto.aead_tag_size + ) + + buf.seek(self._packet_start) + buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) + buf.push_uint32(self._version) + buf.push_uint8(len(self._peer_cid)) + buf.push_bytes(self._peer_cid) + buf.push_uint8(len(self._host_cid)) + buf.push_bytes(self._host_cid) + if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: + buf.push_uint_var(len(self._peer_token)) + buf.push_bytes</s>
aioquic.quic.connection/QuicConnection.datagrams_to_send
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<39>:<del> builder.end_packet()
# module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: <0> """ <1> Return a list of `(data, addr)` tuples of datagrams which need to be <2> sent, and the network address to which they need to be sent. <3> <4> :param now: The current time. <5> """ <6> network_path = self._network_paths[0] <7> <8> if self._state in END_STATES: <9> return [] <10> <11> # build datagrams <12> builder = QuicPacketBuilder( <13> host_cid=self.host_cid, <14> packet_number=self._packet_number, <15> pad_first_datagram=( <16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT <17> ), <18> peer_cid=self._peer_cid, <19> peer_token=self._peer_token, <20> quic_logger=self._quic_logger, <21> spin_bit=self._spin_bit, <22> version=self._version, <23> ) <24> if self._close_pending: <25> for epoch, packet_type in ( <26> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT), <27> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE), <28> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL), <29> ): <30> crypto = self._cryptos[epoch] <31> if crypto.send.is_valid(): <32> builder.start_packet(packet_type, crypto) <33> self._write_close_frame( <34> builder=builder, <35> error_code=self._close_event.error_code, <36> frame_type=self._close_event.frame_type, <37> reason_phrase=self._close_event.reason_phrase, <38> ) <39> builder.end_packet() <40> self._close_pending = False <41> break</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 1 else: # congestion control builder.max_flight_bytes = ( self._loss.congestion_window - self._loss.bytes_in_flight ) if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE: builder.max_flight_bytes = PACKET_MAX_SIZE # limit data on un-validated network paths if not network_path.is_validated: builder.max_total_bytes = ( network_path.bytes_received * 3 - network_path.bytes_sent ) try: if not self._handshake_confirmed: for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]: self._write_handshake(builder, epoch) self._write_application(builder, network_path, now) except QuicPacketBuilderStop: pass datagrams, packets = builder.flush() if datagrams: self._packet_number = builder.packet_number # register packets sent_handshake = False for packet in packets: packet.sent_time = now self._loss.on_packet_sent( packet=packet, space=self._spaces[packet.epoch] ) if packet.epoch == tls.Epoch.HANDSHAKE: sent_handshake = True # log packet if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="packet_sent", data={ "packet_type": self._quic_logger.packet_type( packet.packet_type ), "header": { "packet_number": str(packet.packet_number), "packet_size": packet.sent_bytes, "scid": dump_</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 2 <s>": str(packet.packet_number), "packet_size": packet.sent_bytes, "scid": dump_cid(self.host_cid) if is_long_header(packet.packet_type) else "", "dcid": dump_cid(self._peer_cid), }, "frames": packet.quic_logger_frames, }, ) # check if we can discard initial keys if sent_handshake and self._is_client: self._discard_epoch(tls.Epoch.INITIAL) # return datagrams to send and the destination network address ret = [] for datagram in datagrams: byte_length = len(datagram) network_path.bytes_sent += byte_length ret.append((datagram, network_path.addr)) if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="datagrams_sent", data={"byte_length": byte_length, "count": 1}, ) return ret ===========unchanged ref 0=========== at: aioquic.quic.connection NetworkAddress = Any dump_cid(cid: bytes) -> str QuicConnectionState() END_STATES = frozenset( [ QuicConnectionState.CLOSING, QuicConnectionState.DRAINING, QuicConnectionState.TERMINATED, ] ) at: aioquic.quic.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _discard_epoch(epoch: tls.Epoch) -> None _write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float) -> None _write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None _write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._close_event: Optional[events.ConnectionTerminated] = None self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._handshake_confirmed = False self.host_cid = self._host_cids[0].cid self._network_paths: List[QuicNetworkPath] = [] self._packet_number = 0 self._peer_cid = os.urandom(configuration.connection_id_length) self._peer_token = b"" self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._state = QuicConnectionState.FIRSTFLIGHT ===========unchanged ref 1=========== self._version: Optional[int] = None self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._close_pending = False self._probe_pending = False at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_ack_frame self._handshake_confirmed = True at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase ) at: aioquic.quic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._packet_number = 0 at: aioquic.quic.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.quic.connection.QuicConnection._set_state self._state = state at: aioquic.quic.connection.QuicConnection._write_application self._probe_pending = False at: aioquic.quic.connection.QuicConnection._write_handshake self._probe_pending = False
aioquic.quic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
# module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: <0> crypto_stream: Optional[QuicStream] = None <1> if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid(): <2> crypto = self._cryptos[tls.Epoch.ONE_RTT] <3> crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT] <4> packet_type = PACKET_TYPE_ONE_RTT <5> elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid(): <6> crypto = self._cryptos[tls.Epoch.ZERO_RTT] <7> packet_type = PACKET_TYPE_ZERO_RTT <8> else: <9> return <10> space = self._spaces[tls.Epoch.ONE_RTT] <11> <12> buf = builder.buffer <13> <14> while True: <15> # write header <16> builder.start_packet(packet_type, crypto) <17> <18> if self._handshake_complete: <19> # ACK <20> if space.ack_at is not None and space.ack_at <= now: <21> self._write_ack_frame(builder=builder, space=space) <22> <23> # PATH CHALLENGE <24> if ( <25> not network_path.is_validated <26> and network_path.local_challenge is None <27> ): <28> self._logger.debug( <29> "Network path %s sending challenge", network_path.addr <30> ) <31> network_path.local_challenge = os.urandom(8) <32> builder.start_frame(QuicFrameType.PATH_CHALLENGE) <33> buf.push_bytes(network_path.local_challenge) <34> <35> # log frame <36> if self._quic_logger is not None: <37> builder.quic_logger_frames.append( <38> self._quic_logger.encode</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 data=network_path.local_challenge ) ) # PATH RESPONSE if network_path.remote_challenge is not None: challenge = network_path.remote_challenge builder.start_frame(QuicFrameType.PATH_RESPONSE) buf.push_bytes(challenge) network_path.remote_challenge = None # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_path_response_frame(data=challenge) ) # NEW_CONNECTION_ID for connection_id in self._host_cids: if not connection_id.was_sent: self._write_new_connection_id_frame( builder=builder, connection_id=connection_id ) # RETIRE_CONNECTION_ID while self._retire_connection_ids: sequence_number = self._retire_connection_ids.pop(0) self._write_retire_connection_id_frame( builder=builder, sequence_number=sequence_number ) # STREAMS_BLOCKED if self._streams_blocked_pending: if self._streams_blocked_bidi: self._write_streams_blocked_frame( builder=builder, frame_type=QuicFrameType.STREAMS_BLOCKED_BIDI, limit=self._remote_max_streams_bidi, ) if self._streams_blocked_uni: self._write_streams_blocked_frame( builder=builder, frame_type=QuicFrameType.STREAMS_BLOCKED_UNI, limit=self._remote_max_streams_uni, ) self._streams_blocked_pending = False # connection-</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 2 <s>._remote_max_streams_uni, ) self._streams_blocked_pending = False # connection-level limits self._write_connection_limits(builder=builder, space=space) # stream-level limits for stream in self._streams.values(): self._write_stream_limits(builder=builder, space=space, stream=stream) # PING (user-request) if self._ping_pending: self._logger.info("Sending PING in packet %d", builder.packet_number) self._write_ping_frame(builder, self._ping_pending) self._ping_pending.clear() # PING (probe) if self._probe_pending: self._logger.info( "Sending PING (probe) in packet %d", builder.packet_number ) self._write_ping_frame(builder) self._probe_pending = False # CRYPTO if crypto_stream is not None and not crypto_stream.send_buffer_is_empty: self._write_crypto_frame( builder=builder, space=space, stream=crypto_stream ) for stream in self._streams.values(): # STREAM if not stream.is_blocked and not stream.send_buffer_is_empty: self._remote_max_data_used += self._write_stream_frame( builder=builder, space=space, stream=stream, max_offset=min( stream._send_highest + self._remote_max_data - self._remote_max_data_used, stream.max_stream_data_remote, ), ===========unchanged ref 0=========== at: aioquic.quic.connection QuicNetworkPath(addr: NetworkAddress, bytes_received: int=0, bytes_sent: int=0, is_validated: bool=False, local_challenge: Optional[bytes]=None, remote_challenge: Optional[bytes]=None) at: aioquic.quic.connection.QuicConnection _write_ack_frame(builder: QuicPacketBuilder, space: QuicPacketSpace) _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None _write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None _write_new_connection_id_frame(builder: QuicPacketBuilder, connection_id: QuicConnectionId) -> None _write_ping_frame(builder: QuicPacketBuilder, uids: List[int]=[]) _write_retire_connection_id_frame(builder: QuicPacketBuilder, sequence_number: int) -> None _write_stream_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream, max_offset: int) -> int _write_stream_limits(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None _write_streams_blocked_frame(builder: QuicPacketBuilder, frame_type: QuicFrameType, limit: int) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._handshake_complete = False self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] ===========unchanged ref 1=========== self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=logger_connection_id ) self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(logger_connection_id)} ) self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._create_stream self._streams_blocked_pending = True at: aioquic.quic.connection.QuicConnection._handle_crypto_frame self._handshake_complete = True at: aioquic.quic.connection.QuicConnection._handle_max_data_frame self._remote_max_data = max_data at: aioquic.quic.connection.QuicConnection._handle_max_streams_bidi_frame self._remote_max_streams_bidi = max_streams at: aioquic.quic.connection.QuicConnection._handle_max_streams_uni_frame self._remote_max_streams_uni = max_streams
aioquic.quic.connection/QuicConnection._write_handshake
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<30>:<add> if builder.packet_is_empty: <del> if not builder.end_packet():
# module: aioquic.quic.connection class QuicConnection: def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None: <0> crypto = self._cryptos[epoch] <1> if not crypto.send.is_valid(): <2> return <3> <4> buf = builder.buffer <5> crypto_stream = self._crypto_streams[epoch] <6> space = self._spaces[epoch] <7> <8> while True: <9> if epoch == tls.Epoch.INITIAL: <10> packet_type = PACKET_TYPE_INITIAL <11> else: <12> packet_type = PACKET_TYPE_HANDSHAKE <13> builder.start_packet(packet_type, crypto) <14> <15> # ACK <16> if space.ack_at is not None: <17> self._write_ack_frame(builder=builder, space=space) <18> <19> # CRYPTO <20> if not crypto_stream.send_buffer_is_empty: <21> self._write_crypto_frame( <22> builder=builder, space=space, stream=crypto_stream <23> ) <24> <25> # PADDING (anti-deadlock packet) <26> if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: <27> buf.push_bytes(bytes(builder.remaining_space)) <28> self._probe_pending = False <29> <30> if not builder.end_packet(): <31> break <32>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection _write_ack_frame(builder: QuicPacketBuilder, space: QuicPacketSpace) _write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._probe_pending = False at: aioquic.quic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } at: aioquic.quic.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.quic.connection.QuicConnection._write_application self._probe_pending = False ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_wrong_version(self): client = create_standalone_client(self) builder = QuicPacketBuilder( host_cid=client._peer_cid, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() crypto.setup_initial(client.host_cid, is_client=False, version=client._version) builder.start_packet(PACKET_TYPE_INITIAL, crypto) builder.buffer.push_bytes(bytes(1200)) - builder.end_packet() for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: crypto_stream: Optional[QuicStream] = None if self._cryptos[tls.Epoch.ONE_RTT].send.is_valid(): crypto = self._cryptos[tls.Epoch.ONE_RTT] crypto_stream = self._crypto_streams[tls.Epoch.ONE_RTT] packet_type = PACKET_TYPE_ONE_RTT elif self._cryptos[tls.Epoch.ZERO_RTT].send.is_valid(): crypto = self._cryptos[tls.Epoch.ZERO_RTT] packet_type = PACKET_TYPE_ZERO_RTT else: return space = self._spaces[tls.Epoch.ONE_RTT] buf = builder.buffer while True: # write header builder.start_packet(packet_type, crypto) if self._handshake_complete: # ACK if space.ack_at is not None and space.ack_at <= now: self._write_ack_frame(builder=builder, space=space) # PATH CHALLENGE if ( not network_path.is_validated and network_path.local_challenge is None ): self._logger.debug( "Network path %s sending challenge", network_path.addr ) network_path.local_challenge = os.urandom(8) builder.start_frame(QuicFrameType.PATH_CHALLENGE) buf.push_bytes(network_path.local_challenge) # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_path_challenge_frame( data=network_path.local_challenge ) ) # PATH RESPONSE if network_path.remote_</s> ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 <s> data=network_path.local_challenge ) ) # PATH RESPONSE if network_path.remote_challenge is not None: challenge = network_path.remote_challenge builder.start_frame(QuicFrameType.PATH_RESPONSE) buf.push_bytes(challenge) network_path.remote_challenge = None # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_path_response_frame(data=challenge) ) # NEW_CONNECTION_ID for connection_id in self._host_cids: if not connection_id.was_sent: self._write_new_connection_id_frame( builder=builder, connection_id=connection_id ) # RETIRE_CONNECTION_ID while self._retire_connection_ids: sequence_number = self._retire_connection_ids.pop(0) self._write_retire_connection_id_frame( builder=builder, sequence_number=sequence_number ) # STREAMS_BLOCKED if self._streams_blocked_pending: if self._streams_blocked_bidi: self._write_streams_blocked_frame( builder=builder, frame_type=QuicFrameType.STREAMS_BLOCKED_BIDI, limit=self._remote_max_streams_bidi, ) if self._streams_blocked_uni: self._write_streams_blocked_frame( builder=builder, frame_type=QuicFrameType.STREAMS_BLOCKED_UNI, limit</s>
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_empty
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<5>:<add> self.assertTrue(builder.packet_is_empty) <6>:<del> # nothing to write <7>:<del> <8>:<del> self.assertFalse(builder.end_packet()) <9>:<del> self.assertEqual(builder.buffer.tell(), 0) <10>:<del> self.assertEqual(builder.packet_number, 0) <11>:<del> <12>:<add> # check datagrams
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <4> self.assertEqual(builder.remaining_space, 1236) <5> <6> # nothing to write <7> <8> self.assertFalse(builder.end_packet()) <9> self.assertEqual(builder.buffer.tell(), 0) <10> self.assertEqual(builder.packet_number, 0) <11> <12> datagrams, packets = builder.flush() <13> self.assertEqual(len(datagrams), 0) <14> self.assertEqual(packets, []) <15>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_wrong_version(self): client = create_standalone_client(self) builder = QuicPacketBuilder( host_cid=client._peer_cid, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() crypto.setup_initial(client.host_cid, is_client=False, version=client._version) builder.start_packet(PACKET_TYPE_INITIAL, crypto) builder.buffer.push_bytes(bytes(1200)) - builder.end_packet() for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None: crypto = self._cryptos[epoch] if not crypto.send.is_valid(): return buf = builder.buffer crypto_stream = self._crypto_streams[epoch] space = self._spaces[epoch] while True: if epoch == tls.Epoch.INITIAL: packet_type = PACKET_TYPE_INITIAL else: packet_type = PACKET_TYPE_HANDSHAKE builder.start_packet(packet_type, crypto) # ACK if space.ack_at is not None: self._write_ack_frame(builder=builder, space=space) # CRYPTO if not crypto_stream.send_buffer_is_empty: self._write_crypto_frame( builder=builder, space=space, stream=crypto_stream ) # PADDING (anti-deadlock packet) if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: buf.push_bytes(bytes(builder.remaining_space)) self._probe_pending = False + if builder.packet_is_empty: - if not builder.end_packet(): break ===========changed ref 4=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer + + # finish previous datagram + if self._packet is not None: + self._end_packet() # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_flight_bytes = 0 self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if</s> ===========changed ref 5=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s>start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<8>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <9>:<del> self.assertEqual(builder.buffer.tell(), 1280)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): <0> builder = create_builder(pad_first_datagram=True) <1> crypto = create_crypto() <2> <3> # INITIAL, fully padded <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(100)) <8> self.assertTrue(builder.end_packet()) <9> self.assertEqual(builder.buffer.tell(), 1280) <10> <11> # check datagrams <12> datagrams, packets = builder.flush() <13> self.assertEqual(len(datagrams), 1) <14> self.assertEqual(len(datagrams[0]), 1280) <15> self.assertEqual( <16> packets, <17> [ <18> QuicSentPacket( <19> epoch=Epoch.INITIAL, <20> in_flight=True, <21> is_ack_eliciting=True, <22> is_crypto_packet=True, <23> packet_number=0, <24> packet_type=PACKET_TYPE_INITIAL, <25> sent_bytes=1280, <26> ) <27> ], <28> ) <29>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_wrong_version(self): client = create_standalone_client(self) builder = QuicPacketBuilder( host_cid=client._peer_cid, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() crypto.setup_initial(client.host_cid, is_client=False, version=client._version) builder.start_packet(PACKET_TYPE_INITIAL, crypto) builder.buffer.push_bytes(bytes(1200)) - builder.end_packet() for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None: crypto = self._cryptos[epoch] if not crypto.send.is_valid(): return buf = builder.buffer crypto_stream = self._crypto_streams[epoch] space = self._spaces[epoch] while True: if epoch == tls.Epoch.INITIAL: packet_type = PACKET_TYPE_INITIAL else: packet_type = PACKET_TYPE_HANDSHAKE builder.start_packet(packet_type, crypto) # ACK if space.ack_at is not None: self._write_ack_frame(builder=builder, space=space) # CRYPTO if not crypto_stream.send_buffer_is_empty: self._write_crypto_frame( builder=builder, space=space, stream=crypto_stream ) # PADDING (anti-deadlock packet) if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: buf.push_bytes(bytes(builder.remaining_space)) self._probe_pending = False + if builder.packet_is_empty: - if not builder.end_packet(): break ===========changed ref 5=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer + + # finish previous datagram + if self._packet is not None: + self._end_packet() # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_flight_bytes = 0 self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if</s> ===========changed ref 6=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s>start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<8>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <9>:<del> self.assertEqual(builder.buffer.tell(), 1280) <16>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <17>:<del> self.assertEqual(builder.buffer.tell(), 0)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> # INITIAL, fully padded <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(builder.remaining_space)) <8> self.assertTrue(builder.end_packet()) <9> self.assertEqual(builder.buffer.tell(), 1280) <10> <11> # ONE_RTT, fully padded <12> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <13> self.assertEqual(builder.remaining_space, 1253) <14> builder.start_frame(QuicFrameType.STREAM_BASE) <15> builder.buffer.push_bytes(bytes(builder.remaining_space)) <16> self.assertTrue(builder.end_packet()) <17> self.assertEqual(builder.buffer.tell(), 0) <18> <19> # check datagrams <20> datagrams, packets = builder.flush() <21> self.assertEqual(len(datagrams), 2) <22> self.assertEqual(len(datagrams[0]), 1280) <23> self.assertEqual(len(datagrams[1]), 1280) <24> self.assertEqual( <25> packets, <26> [ <27> QuicSentPacket( <28> epoch=Epoch.INITIAL, <29> in_flight=True, <30> is_ack_eliciting=True, <31> is_crypto_packet=True, <32> packet_number=0, <33> packet_type=PACKET_TYPE_INITIAL, <34> sent_bytes=1280, <35> ), <36> QuicSentPacket( <37> epoch=Epoch.ONE_RTT, <38> in_flight=True, <39> is_ack_elic</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) ===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 3=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_wrong_version(self): client = create_standalone_client(self) builder = QuicPacketBuilder( host_cid=client._peer_cid, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() crypto.setup_initial(client.host_cid, is_client=False, version=client._version) builder.start_packet(PACKET_TYPE_INITIAL, crypto) builder.buffer.push_bytes(bytes(1200)) - builder.end_packet() for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 5=========== # module: aioquic.quic.connection class QuicConnection: def _write_handshake(self, builder: QuicPacketBuilder, epoch: tls.Epoch) -> None: crypto = self._cryptos[epoch] if not crypto.send.is_valid(): return buf = builder.buffer crypto_stream = self._crypto_streams[epoch] space = self._spaces[epoch] while True: if epoch == tls.Epoch.INITIAL: packet_type = PACKET_TYPE_INITIAL else: packet_type = PACKET_TYPE_HANDSHAKE builder.start_packet(packet_type, crypto) # ACK if space.ack_at is not None: self._write_ack_frame(builder=builder, space=space) # CRYPTO if not crypto_stream.send_buffer_is_empty: self._write_crypto_frame( builder=builder, space=space, stream=crypto_stream ) # PADDING (anti-deadlock packet) if self._probe_pending and self._is_client and epoch == tls.Epoch.HANDSHAKE: buf.push_bytes(bytes(builder.remaining_space)) self._probe_pending = False + if builder.packet_is_empty: - if not builder.end_packet(): break
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<8>:<del> self.assertEqual(builder.buffer.tell(), 228) <9>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <10>:<del> self.assertEqual(builder.buffer.tell(), 244) <18>:<del> self.assertEqual(builder.buffer.tell(), 571) <19>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <20>:<del> self.assertEqual(builder.buffer.tell(), 587) <27>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <28>:<del> self.assertEqual(builder.buffer.tell(), 0)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> # INITIAL <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(199)) <8> self.assertEqual(builder.buffer.tell(), 228) <9> self.assertTrue(builder.end_packet()) <10> self.assertEqual(builder.buffer.tell(), 244) <11> <12> # HANDSHAKE <13> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) <14> self.assertEqual(builder.buffer.tell(), 271) <15> self.assertEqual(builder.remaining_space, 993) <16> builder.start_frame(QuicFrameType.CRYPTO) <17> builder.buffer.push_bytes(bytes(299)) <18> self.assertEqual(builder.buffer.tell(), 571) <19> self.assertTrue(builder.end_packet()) <20> self.assertEqual(builder.buffer.tell(), 587) <21> <22> # ONE_RTT <23> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <24> self.assertEqual(builder.remaining_space, 666) <25> builder.start_frame(QuicFrameType.CRYPTO) <26> builder.buffer.push_bytes(bytes(299)) <27> self.assertTrue(builder.end_packet()) <28> self.assertEqual(builder.buffer.tell(), 0) <29> <30> # check datagrams <31> datagrams, packets = builder.flush() <32> self.assertEqual(len(datagrams), 1) <33> self.assertEqual(len(datagrams[0]), 914) <34> self.assertEqual( <35> packets,</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): # offset: 1 QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=244, ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, packet_type=PACKET_TYPE_HANDSHAKE, sent_bytes=343, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=327, ), ], ) ===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: tests.test_packet_builder.QuicPacketBuilderTest.test_long_header_then_long_header builder = create_builder() crypto = create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True</s> ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 <s> epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) ===========changed ref 4=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: + @property + def packet_is_empty(self) -> bool: + """ + Returns `True` if the current packet is empty. + """ + assert self._packet is not None + packet_size = self.buffer.tell() - self._packet_start + return packet_size <= self._header_size + ===========changed ref 5=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ + if self._packet is not None: + self._end_packet() self._flush_current_datagram() + datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets
tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_empty
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<5>:<add> self.assertTrue(builder.packet_is_empty) <6>:<add> # check datagrams <add> datagrams, packets = builder.flush() <add> self.assertEqual(datagrams, []) <add> self.assertEqual(packets, []) <del> # nothing to write <7>:<del> self.assertFalse(builder.end_packet()) <13>:<del> datagrams, packets = builder.flush() <14>:<del> self.assertEqual(len(datagrams), 0) <15>:<del> self.assertEqual(packets, []) <16>:<del>
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_empty(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <4> self.assertEqual(builder.remaining_space, 1253) <5> <6> # nothing to write <7> self.assertFalse(builder.end_packet()) <8> <9> # check builder <10> self.assertEqual(builder.buffer.tell(), 0) <11> self.assertEqual(builder.packet_number, 0) <12> <13> datagrams, packets = builder.flush() <14> self.assertEqual(len(datagrams), 0) <15> self.assertEqual(packets, []) <16>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: tests.test_packet_builder.QuicPacketBuilderTest.test_short_header_empty builder = create_builder() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True</s> ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 <s> epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) ===========changed ref 4=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): builder = create_builder() crypto = create_crypto() # INITIAL builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(199)) - self.assertEqual(builder.buffer.tell(), 228) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 244) # HANDSHAKE builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) self.assertEqual(builder.buffer.tell(), 271) self.assertEqual(builder.remaining_space, 993) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) - self.assertEqual(builder.buffer.tell(), 571) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 587) # ONE_RTT builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 666) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(dat</s>
tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_padding
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<8>:<del> self.assertTrue(builder.end_packet()) <9>:<del> <10>:<del> # check builder <11>:<del> self.assertEqual(builder.buffer.tell(), 0) <12>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertEqual(builder.packet_number, 1)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_padding(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> # ONE_RTT, fully padded <4> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <5> self.assertEqual(builder.remaining_space, 1253) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(builder.remaining_space)) <8> self.assertTrue(builder.end_packet()) <9> <10> # check builder <11> self.assertEqual(builder.buffer.tell(), 0) <12> self.assertEqual(builder.packet_number, 1) <13> <14> # check datagrams <15> datagrams, packets = builder.flush() <16> self.assertEqual(len(datagrams), 1) <17> self.assertEqual(len(datagrams[0]), 1280) <18> self.assertEqual( <19> packets, <20> [ <21> QuicSentPacket( <22> epoch=Epoch.ONE_RTT, <23> in_flight=True, <24> is_ack_eliciting=True, <25> is_crypto_packet=True, <26> packet_number=0, <27> packet_type=PACKET_TYPE_ONE_RTT, <28> sent_bytes=1280, <29> ) <30> ], <31> ) <32>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: tests.test_packet_builder.QuicPacketBuilderTest.test_short_header_padding builder = create_builder() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) + self.assertTrue(builder.packet_is_empty) + # check datagrams + datagrams, packets = builder.flush() + self.assertEqual(datagrams, []) + self.assertEqual(packets, []) - # nothing to write - self.assertFalse(builder.end_packet()) # check builder self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) - datagrams, packets = builder.flush() - self.assertEqual(len(datagrams), 0) - self.assertEqual(packets, []) - ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True</s> ===========changed ref 4=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 <s> epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], )
tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_max_total_bytes_2
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<10>:<add> builder.start_frame(QuicFrameType.CRYPTO) <add> self.assertEqual(builder.remaining_space, 772) <11>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet())
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_max_total_bytes_2(self): <0> """ <1> max_total_bytes allows a short packet. <2> """ <3> builder = create_builder() <4> builder.max_total_bytes = 800 <5> <6> crypto = create_crypto() <7> <8> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <9> self.assertEqual(builder.remaining_space, 773) <10> builder.buffer.push_bytes(bytes(builder.remaining_space)) <11> self.assertTrue(builder.end_packet()) <12> <13> with self.assertRaises(QuicPacketBuilderStop): <14> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <15>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) + self.assertTrue(builder.packet_is_empty) + # check datagrams + datagrams, packets = builder.flush() + self.assertEqual(datagrams, []) + self.assertEqual(packets, []) - # nothing to write - self.assertFalse(builder.end_packet()) # check builder self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) - datagrams, packets = builder.flush() - self.assertEqual(len(datagrams), 0) - self.assertEqual(packets, []) - ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_padding(self): builder = create_builder() crypto = create_crypto() # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) - self.assertTrue(builder.end_packet()) - - # check builder - self.assertEqual(builder.buffer.tell(), 0) + self.assertFalse(builder.packet_is_empty) - self.assertEqual(builder.packet_number, 1) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ) ], ) ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 4=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True</s> ===========changed ref 5=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 <s> epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], )
tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_max_total_bytes_3
Modified
aiortc~aioquic
9b85202690da74c55f49729acc272cfb20cebdd7
[packet_builder] remove QuicPacketBuilder.end_packet from API
<7>:<add> builder.start_frame(QuicFrameType.CRYPTO) <add> self.assertEqual(builder.remaining_space, 1252) <8>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet()) <12>:<add> builder.start_frame(QuicFrameType.CRYPTO) <add> self.assertEqual(builder.remaining_space, 692) <13>:<add> self.assertFalse(builder.packet_is_empty) <del> self.assertTrue(builder.end_packet())
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_max_total_bytes_3(self): <0> builder = create_builder() <1> builder.max_total_bytes = 2000 <2> <3> crypto = create_crypto() <4> <5> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <6> self.assertEqual(builder.remaining_space, 1253) <7> builder.buffer.push_bytes(bytes(builder.remaining_space)) <8> self.assertTrue(builder.end_packet()) <9> <10> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <11> self.assertEqual(builder.remaining_space, 693) <12> builder.buffer.push_bytes(bytes(builder.remaining_space)) <13> self.assertTrue(builder.end_packet()) <14> <15> with self.assertRaises(QuicPacketBuilderStop): <16> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <17>
===========unchanged ref 0=========== at: tests.test_packet_builder.QuicPacketBuilderTest.test_short_header_max_total_bytes_2 datagrams, packets = builder.flush() datagrams, packets = builder.flush() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_max_total_bytes_2(self): """ max_total_bytes allows a short packet. """ builder = create_builder() builder.max_total_bytes = 800 crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 773) + builder.start_frame(QuicFrameType.CRYPTO) + self.assertEqual(builder.remaining_space, 772) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) + self.assertTrue(builder.packet_is_empty) + # check datagrams + datagrams, packets = builder.flush() + self.assertEqual(datagrams, []) + self.assertEqual(packets, []) - # nothing to write - self.assertFalse(builder.end_packet()) # check builder self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) - datagrams, packets = builder.flush() - self.assertEqual(len(datagrams), 0) - self.assertEqual(packets, []) - ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_padding(self): builder = create_builder() crypto = create_crypto() # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) - self.assertTrue(builder.end_packet()) - - # check builder - self.assertEqual(builder.buffer.tell(), 0) + self.assertFalse(builder.packet_is_empty) - self.assertEqual(builder.packet_number, 1) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ) ], ) ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) + self.assertTrue(builder.packet_is_empty) - # nothing to write - - self.assertFalse(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) - self.assertEqual(builder.packet_number, 0) - + # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) ===========changed ref 4=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 5=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) + self.assertFalse(builder.packet_is_empty) - self.assertTrue(builder.end_packet()) - self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True</s>
aioquic.quic.packet_builder/QuicPacketBuilder._end_packet
Modified
aiortc~aioquic
93f6acd2c165e005224186723f92d86e2145c01c
[packet builder] padding causes packet to count in flight bytes
<16>:<add> self._packet.in_flight = True
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: <0> """ <1> Ends the current packet. <2> <3> Returns `True` if the packet contains data, `False` otherwise. <4> """ <5> buf = self.buffer <6> empty = True <7> packet_size = buf.tell() - self._packet_start <8> if packet_size > self._header_size: <9> empty = False <10> <11> # pad initial datagram <12> if self._pad_first_datagram: <13> if self.remaining_space: <14> buf.push_bytes(bytes(self.remaining_space)) <15> packet_size = buf.tell() - self._packet_start <16> <17> # log frame <18> if self._quic_logger is not None: <19> self._packet.quic_logger_frames.append( <20> self._quic_logger.encode_padding_frame() <21> ) <22> self._pad_first_datagram = False <23> <24> # write header <25> if self._packet_long_header: <26> length = ( <27> packet_size <28> - self._header_size <29> + PACKET_NUMBER_SEND_SIZE <30> + self._packet_crypto.aead_tag_size <31> ) <32> <33> buf.seek(self._packet_start) <34> buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) <35> buf.push_uint32(self._version) <36> buf.push_uint8(len(self._peer_cid)) <37> buf.push_bytes(self._peer_cid) <38> buf.push_uint8(len(self._host_cid)) <39> buf.push_bytes(self._host_cid) <40> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <41> buf.push_uint_var(len(self._peer_token)) <42> buf.push_bytes(</s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 1 buf.push_uint16(length | 0x4000) buf.push_uint16(self._packet_number & 0xFFFF) else: buf.seek(self._packet_start) buf.push_uint8( self._packet_type | (self._spin_bit << 5) | (self._packet_crypto.key_phase << 2) | (PACKET_NUMBER_SEND_SIZE - 1) ) buf.push_bytes(self._peer_cid) buf.push_uint16(self._packet_number & 0xFFFF) # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + self._header_size - packet_size ) if padding_size > 0: buf.seek(self._packet_start + packet_size) buf.push_bytes(bytes(padding_size)) packet_size += padding_size # encrypt in place plain = buf.data_slice(self._packet_start, self._packet_start + packet_size) buf.seek(self._packet_start) buf.push_bytes( self._packet_crypto.encrypt_packet( plain[0 : self._header_size], plain[self._header_size : packet_size], self._packet_number, ) ) self._packet.sent_bytes = buf.tell() - self._packet_start self._packets.append(self._packet) if self._packet.in_flight: self._datagram_flight_bytes += self._packet.sent_bytes # short header packets cannot be coallesced, we need a new datagram if not self._packet_long_header: self._flush_current_datagram() self._packet_number += 1 else: #</s> ===========below chunk 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 2 <s>header: self._flush_current_datagram() self._packet_number += 1 else: # "cancel" the packet buf.seek(self._packet_start) self._packet = None self.quic_logger_frames = None return not empty ===========unchanged ref 0=========== at: aioquic.quic.packet_builder PACKET_NUMBER_SEND_SIZE = 2 at: aioquic.quic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._host_cid = host_cid self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version self._datagram_flight_bytes = 0 self._packets: List[QuicSentPacket] = [] self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.quic.packet_builder.QuicPacketBuilder._end_packet self._packet = None at: aioquic.quic.packet_builder.QuicPacketBuilder.flush self._packets = [] at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._datagram_flight_bytes = 0 self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header ===========unchanged ref 1=========== self._packet_start = packet_start self._packet_type = packet_type at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding
Modified
aiortc~aioquic
93f6acd2c165e005224186723f92d86e2145c01c
[packet builder] padding causes packet to count in flight bytes
<9>:<add> <add> # INITIAL, empty <add> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <add> self.assertTrue(builder.packet_is_empty)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): <0> builder = create_builder(pad_first_datagram=True) <1> crypto = create_crypto() <2> <3> # INITIAL, fully padded <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(100)) <8> self.assertFalse(builder.packet_is_empty) <9> <10> # check datagrams <11> datagrams, packets = builder.flush() <12> self.assertEqual(len(datagrams), 1) <13> self.assertEqual(len(datagrams[0]), 1280) <14> self.assertEqual( <15> packets, <16> [ <17> QuicSentPacket( <18> epoch=Epoch.INITIAL, <19> in_flight=True, <20> is_ack_eliciting=True, <21> is_crypto_packet=True, <22> packet_number=0, <23> packet_type=PACKET_TYPE_INITIAL, <24> sent_bytes=1280, <25> ) <26> ], <27> ) <28>
===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: """ Ends the current packet. Returns `True` if the packet contains data, `False` otherwise. """ buf = self.buffer empty = True packet_size = buf.tell() - self._packet_start if packet_size > self._header_size: empty = False # pad initial datagram if self._pad_first_datagram: if self.remaining_space: buf.push_bytes(bytes(self.remaining_space)) packet_size = buf.tell() - self._packet_start + self._packet.in_flight = True # log frame if self._quic_logger is not None: self._packet.quic_logger_frames.append( self._quic_logger.encode_padding_frame() ) self._pad_first_datagram = False # write header if self._packet_long_header: length = ( packet_size - self._header_size + PACKET_NUMBER_SEND_SIZE + self._packet_crypto.aead_tag_size ) buf.seek(self._packet_start) buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) buf.push_uint32(self._version) buf.push_uint8(len(self._peer_cid)) buf.push_bytes(self._peer_cid) buf.push_uint8(len(self._host_cid)) buf.push_bytes(self._host_cid) if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: buf.push_uint_var(len(self._peer_token)) buf.push_bytes(self._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(</s> ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 1 <s>._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(self._packet_number & 0xFFFF) else: buf.seek(self._packet_start) buf.push_uint8( self._packet_type | (self._spin_bit << 5) | (self._packet_crypto.key_phase << 2) | (PACKET_NUMBER_SEND_SIZE - 1) ) buf.push_bytes(self._peer_cid) buf.push_uint16(self._packet_number & 0xFFFF) # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + self._header_size - packet_size ) if padding_size > 0: buf.seek(self._packet_start + packet_size) buf.push_bytes(bytes(padding_size)) packet_size += padding_size + self._packet.in_flight = True + + # log frame + if self._quic_logger is not None: + self._packet.quic_logger_frames.append( + self._quic_logger.encode_padding_frame() + ) # encrypt in place plain = buf.data_slice(self._packet_start, self._packet_start + packet_size) buf.seek(self._packet_start) buf.push_bytes( self._packet_crypto.encrypt_packet( plain[0 : self._header_size], plain[self._header_size : packet_size], self._packet_number, ) ) self._packet.sent_bytes = buf.t</s> ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 2 <s> - self._packet_start self._packets.append(self._packet) if self._packet.in_flight: self._datagram_flight_bytes += self._packet.sent_bytes # short header packets cannot be coallesced, we need a new datagram if not self._packet_long_header: self._flush_current_datagram() self._packet_number += 1 else: # "cancel" the packet buf.seek(self._packet_start) self._packet = None self.quic_logger_frames = None return not empty
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header
Modified
aiortc~aioquic
93f6acd2c165e005224186723f92d86e2145c01c
[packet builder] padding causes packet to count in flight bytes
<10>:<add> # INITIAL, empty <add> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <add> self.assertTrue(builder.packet_is_empty) <add> <16>:<add> <add> # ONE_RTT, empty <add> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <add> self.assertTrue(builder.packet_is_empty)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> # INITIAL, fully padded <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(builder.remaining_space)) <8> self.assertFalse(builder.packet_is_empty) <9> <10> # ONE_RTT, fully padded <11> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <12> self.assertEqual(builder.remaining_space, 1253) <13> builder.start_frame(QuicFrameType.STREAM_BASE) <14> builder.buffer.push_bytes(bytes(builder.remaining_space)) <15> self.assertFalse(builder.packet_is_empty) <16> <17> # check datagrams <18> datagrams, packets = builder.flush() <19> self.assertEqual(len(datagrams), 2) <20> self.assertEqual(len(datagrams[0]), 1280) <21> self.assertEqual(len(datagrams[1]), 1280) <22> self.assertEqual( <23> packets, <24> [ <25> QuicSentPacket( <26> epoch=Epoch.INITIAL, <27> in_flight=True, <28> is_ack_eliciting=True, <29> is_crypto_packet=True, <30> packet_number=0, <31> packet_type=PACKET_TYPE_INITIAL, <32> sent_bytes=1280, <33> ), <34> QuicSentPacket( <35> epoch=Epoch.ONE_RTT, <36> in_flight=True, <37> is_ack_eliciting=True, <38> is_crypto_packet=False, <39> packet_number=1, <40> packet_type</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 sent_bytes=1280, ), ], ) ===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) self.assertFalse(builder.packet_is_empty) + + # INITIAL, empty + builder.start_packet(PACKET_TYPE_INITIAL, crypto) + self.assertTrue(builder.packet_is_empty) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: """ Ends the current packet. Returns `True` if the packet contains data, `False` otherwise. """ buf = self.buffer empty = True packet_size = buf.tell() - self._packet_start if packet_size > self._header_size: empty = False # pad initial datagram if self._pad_first_datagram: if self.remaining_space: buf.push_bytes(bytes(self.remaining_space)) packet_size = buf.tell() - self._packet_start + self._packet.in_flight = True # log frame if self._quic_logger is not None: self._packet.quic_logger_frames.append( self._quic_logger.encode_padding_frame() ) self._pad_first_datagram = False # write header if self._packet_long_header: length = ( packet_size - self._header_size + PACKET_NUMBER_SEND_SIZE + self._packet_crypto.aead_tag_size ) buf.seek(self._packet_start) buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) buf.push_uint32(self._version) buf.push_uint8(len(self._peer_cid)) buf.push_bytes(self._peer_cid) buf.push_uint8(len(self._host_cid)) buf.push_bytes(self._host_cid) if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: buf.push_uint_var(len(self._peer_token)) buf.push_bytes(self._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(</s> ===========changed ref 2=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 1 <s>._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(self._packet_number & 0xFFFF) else: buf.seek(self._packet_start) buf.push_uint8( self._packet_type | (self._spin_bit << 5) | (self._packet_crypto.key_phase << 2) | (PACKET_NUMBER_SEND_SIZE - 1) ) buf.push_bytes(self._peer_cid) buf.push_uint16(self._packet_number & 0xFFFF) # check whether we need padding padding_size = ( PACKET_NUMBER_MAX_SIZE - PACKET_NUMBER_SEND_SIZE + self._header_size - packet_size ) if padding_size > 0: buf.seek(self._packet_start + packet_size) buf.push_bytes(bytes(padding_size)) packet_size += padding_size + self._packet.in_flight = True + + # log frame + if self._quic_logger is not None: + self._packet.quic_logger_frames.append( + self._quic_logger.encode_padding_frame() + ) # encrypt in place plain = buf.data_slice(self._packet_start, self._packet_start + packet_size) buf.seek(self._packet_start) buf.push_bytes( self._packet_crypto.encrypt_packet( plain[0 : self._header_size], plain[self._header_size : packet_size], self._packet_number, ) ) self._packet.sent_bytes = buf.t</s> ===========changed ref 3=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: # offset: 2 <s> - self._packet_start self._packets.append(self._packet) if self._packet.in_flight: self._datagram_flight_bytes += self._packet.sent_bytes # short header packets cannot be coallesced, we need a new datagram if not self._packet_long_header: self._flush_current_datagram() self._packet_number += 1 else: # "cancel" the packet buf.seek(self._packet_start) self._packet = None self.quic_logger_frames = None return not empty
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header
Modified
aiortc~aioquic
93f6acd2c165e005224186723f92d86e2145c01c
[packet builder] padding causes packet to count in flight bytes
<12>:<del> self.assertEqual(builder.buffer.tell(), 271)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): <0> builder = create_builder() <1> crypto = create_crypto() <2> <3> # INITIAL <4> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <5> self.assertEqual(builder.remaining_space, 1236) <6> builder.start_frame(QuicFrameType.CRYPTO) <7> builder.buffer.push_bytes(bytes(199)) <8> self.assertFalse(builder.packet_is_empty) <9> <10> # HANDSHAKE <11> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) <12> self.assertEqual(builder.buffer.tell(), 271) <13> self.assertEqual(builder.remaining_space, 993) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(299)) <16> self.assertFalse(builder.packet_is_empty) <17> <18> # ONE_RTT <19> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <20> self.assertEqual(builder.remaining_space, 666) <21> builder.start_frame(QuicFrameType.CRYPTO) <22> builder.buffer.push_bytes(bytes(299)) <23> self.assertFalse(builder.packet_is_empty) <24> <25> # check datagrams <26> datagrams, packets = builder.flush() <27> self.assertEqual(len(datagrams), 1) <28> self.assertEqual(len(datagrams[0]), 914) <29> self.assertEqual( <30> packets, <31> [ <32> QuicSentPacket( <33> epoch=Epoch.INITIAL, <34> in_flight=True, <35> is_ack_eliciting=True, <36> is_crypto_packet=True, <37> packet_number=0, <38> packet_type=PACKET_TYPE_INITIAL, <39> sent_</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): # offset: 1 ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, packet_type=PACKET_TYPE_HANDSHAKE, sent_bytes=343, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=327, ), ], ) ===========unchanged ref 0=========== at: tests.test_packet_builder create_builder(pad_first_datagram=False) create_crypto() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) self.assertFalse(builder.packet_is_empty) + + # INITIAL, empty + builder.start_packet(PACKET_TYPE_INITIAL, crypto) + self.assertTrue(builder.packet_is_empty) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) ===========changed ref 1=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertFalse(builder.packet_is_empty) + # INITIAL, empty + builder.start_packet(PACKET_TYPE_INITIAL, crypto) + self.assertTrue(builder.packet_is_empty) + # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertFalse(builder.packet_is_empty) + + # ONE_RTT, empty + builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) + self.assertTrue(builder.packet_is_empty) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=</s> ===========changed ref 2=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 <s>ET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) ===========changed ref 3=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> bool: """ Ends the current packet. Returns `True` if the packet contains data, `False` otherwise. """ buf = self.buffer empty = True packet_size = buf.tell() - self._packet_start if packet_size > self._header_size: empty = False # pad initial datagram if self._pad_first_datagram: if self.remaining_space: buf.push_bytes(bytes(self.remaining_space)) packet_size = buf.tell() - self._packet_start + self._packet.in_flight = True # log frame if self._quic_logger is not None: self._packet.quic_logger_frames.append( self._quic_logger.encode_padding_frame() ) self._pad_first_datagram = False # write header if self._packet_long_header: length = ( packet_size - self._header_size + PACKET_NUMBER_SEND_SIZE + self._packet_crypto.aead_tag_size ) buf.seek(self._packet_start) buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) buf.push_uint32(self._version) buf.push_uint8(len(self._peer_cid)) buf.push_bytes(self._peer_cid) buf.push_uint8(len(self._host_cid)) buf.push_bytes(self._host_cid) if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: buf.push_uint_var(len(self._peer_token)) buf.push_bytes(self._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(</s>
aioquic.quic.packet_builder/QuicPacketBuilder.__init__
Modified
aiortc~aioquic
74eaefda6dbd77eb3b393ab175f8aea3262b8961
[packet builder] pad all client datagrams containing INITIAL packets
<5>:<add> self._is_client = is_client <del> self._pad_first_datagram = pad_first_datagram <16>:<add> self._datagram_padding = False
<s>.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, + is_client: bool, - pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): <0> self.max_flight_bytes: Optional[int] = None <1> self.max_total_bytes: Optional[int] = None <2> self.quic_logger_frames: Optional[List[Dict]] = None <3> <4> self._host_cid = host_cid <5> self._pad_first_datagram = pad_first_datagram <6> self._peer_cid = peer_cid <7> self._peer_token = peer_token <8> self._quic_logger = quic_logger <9> self._spin_bit = spin_bit <10> self._version = version <11> <12> # assembled datagrams and packets <13> self._datagrams: List[bytes] = [] <14> self._datagram_flight_bytes = 0 <15> self._datagram_init = True <16> self._packets: List[QuicSentPacket] = [] <17> self._flight_bytes = 0 <18> self._total_bytes = 0 <19> <20> # current packet <21> self._header_size = 0 <22> self._packet: Optional[QuicSentPacket] = None <23> self._packet_crypto: Optional[CryptoPair] = None <24> self._packet_long_header = False <25> self._packet_number = packet_number <26> self._packet_start = 0 <27> self._packet_type = 0 <28> <29> self.buffer = Buffer(PACKET_MAX_SIZE) <30> self._buffer_capacity = PACKET_MAX_SIZE <31>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder PACKET_MAX_SIZE = 1280 QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicPacketBuilder._end_packet self._datagram_padding = True self._datagram_flight_bytes += self._packet.sent_bytes self._packet_number += 1 self._packet = None self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram self._flight_bytes += self._datagram_flight_bytes self._total_bytes += datagram_bytes self._datagram_init = True at: aioquic.quic.packet_builder.QuicPacketBuilder.flush self._datagrams = [] self._packets = [] at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._datagram_flight_bytes = 0 self._datagram_init = False self._datagram_padding = False self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start ===========unchanged ref 1=========== self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.quic.packet_builder/QuicPacketBuilder.flush
Modified
aiortc~aioquic
74eaefda6dbd77eb3b393ab175f8aea3262b8961
[packet builder] pad all client datagrams containing INITIAL packets
<4>:<add> self._end_packet(final=True) <del> self._end_packet()
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: <0> """ <1> Returns the assembled datagrams. <2> """ <3> if self._packet is not None: <4> self._end_packet() <5> self._flush_current_datagram() <6> <7> datagrams = self._datagrams <8> packets = self._packets <9> self._datagrams = [] <10> self._packets = [] <11> return datagrams, packets <12>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) at: aioquic.quic.packet_builder.QuicPacketBuilder _end_packet(self, final: bool) -> None _end_packet(final: bool) -> None _flush_current_datagram() -> None _flush_current_datagram(self) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self._datagrams: List[bytes] = [] self._packets: List[QuicSentPacket] = [] self._packet: Optional[QuicSentPacket] = None at: aioquic.quic.packet_builder.QuicPacketBuilder._end_packet self._packet = None at: aioquic.quic.packet_builder.QuicPacketBuilder.start_packet self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) at: typing Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== <s>.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, + is_client: bool, - pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid + self._is_client = is_client - self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets self._datagrams: List[bytes] = [] self._datagram_flight_bytes = 0 self._datagram_init = True + self._datagram_padding = False self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE
aioquic.quic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
74eaefda6dbd77eb3b393ab175f8aea3262b8961
[packet builder] pad all client datagrams containing INITIAL packets
<7>:<add> self._end_packet(final=False) <del> self._end_packet() <28>:<add> self._datagram_padding = False
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> <5> # finish previous datagram <6> if self._packet is not None: <7> self._end_packet() <8> <9> # if there is too little space remaining, start a new datagram <10> # FIXME: the limit is arbitrary! <11> packet_start = buf.tell() <12> if self._buffer_capacity - packet_start < 128: <13> self._flush_current_datagram() <14> packet_start = 0 <15> <16> # initialize datagram if needed <17> if self._datagram_init: <18> if self.max_flight_bytes is not None: <19> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <20> if remaining_flight_bytes < self._buffer_capacity: <21> self._buffer_capacity = remaining_flight_bytes <22> if self.max_total_bytes is not None: <23> remaining_total_bytes = self.max_total_bytes - self._total_bytes <24> if remaining_total_bytes < self._buffer_capacity: <25> self._buffer_capacity = remaining_total_bytes <26> self._datagram_flight_bytes = 0 <27> self._datagram_init = False <28> <29> # calculate header size <30> packet_long_header = is_long_header(packet_type) <31> if packet_long_header: <32> header_size = 11 + len(self._peer_cid) + len(self._host_cid) <33> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <34> token_length = len(self._peer_token) <35> header_size += size_uint_var(token_length) + token_length <36> else: <37> header_size = 3 + len(self._peer_cid) <38> <39> # check we have enough</s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type self.quic_logger_frames = self._packet.quic_logger_frames buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, packet_type: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list ), quic_logger_frames: List[Dict]=field(default_factory=list)) QuicPacketBuilderStop(*args: object) at: aioquic.quic.packet_builder.QuicPacketBuilder _end_packet(self, final: bool) -> None _end_packet(final: bool) -> None _flush_current_datagram() -> None _flush_current_datagram(self) -> None at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._datagram_flight_bytes = 0 self._datagram_init = True self._datagram_padding = False self._flight_bytes = 0 self._total_bytes = 0 self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE ===========unchanged ref 1=========== at: aioquic.quic.packet_builder.QuicPacketBuilder._end_packet self._datagram_padding = True self._datagram_flight_bytes += self._packet.sent_bytes self._packet_number += 1 self._packet = None self.quic_logger_frames = None at: aioquic.quic.packet_builder.QuicPacketBuilder._flush_current_datagram self._flight_bytes += self._datagram_flight_bytes self._total_bytes += datagram_bytes self._datagram_init = True at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) quic_logger_frames: List[Dict] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def flush(self) -> Tuple[List[bytes], List[QuicSentPacket]]: """ Returns the assembled datagrams. """ if self._packet is not None: + self._end_packet(final=True) - self._end_packet() self._flush_current_datagram() datagrams = self._datagrams packets = self._packets self._datagrams = [] self._packets = [] return datagrams, packets ===========changed ref 1=========== <s>.quic.packet_builder class QuicPacketBuilder: def __init__( self, *, host_cid: bytes, peer_cid: bytes, version: int, + is_client: bool, - pad_first_datagram: bool = False, packet_number: int = 0, peer_token: bytes = b"", quic_logger: Optional[QuicLoggerTrace] = None, spin_bit: bool = False, ): self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid + self._is_client = is_client - self._pad_first_datagram = pad_first_datagram self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version # assembled datagrams and packets self._datagrams: List[bytes] = [] self._datagram_flight_bytes = 0 self._datagram_init = True + self._datagram_padding = False self._packets: List[QuicSentPacket] = [] self._flight_bytes = 0 self._total_bytes = 0 # current packet self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE