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
aioquic.quic.connection/QuicConnection.reset_stream
Modified
aiortc~aioquic
dfbeb83cf95b2ff4e81bd534097ade2ae4bd5939
[streams] refactor local stream creation
<6>:<del> if stream_id not in self._streams: <7>:<del> raise ValueError("Cannot reset an unknown stream") <8>:<del> if stream_is_client_initiated( <9>:<del> stream_id <10>:<del> ) != self._is_client and stream_is_unidirectional(stream_id): <11>:<del> raise ValueError("Cannot reset a peer-initiated unidirectional stream") <12>:<del> <13>:<add> stream = self._get_or_create_stream_for_send(stream_id) <del> stream = self._streams[stream_id]
# module: aioquic.quic.connection class QuicConnection: def reset_stream(self, stream_id: int, error_code: int) -> None: <0> """ <1> Abruptly terminate the sending part of a stream. <2> <3> :param stream_id: The stream's ID. <4> :param error_code: An error code indicating why the stream is being reset. <5> """ <6> if stream_id not in self._streams: <7> raise ValueError("Cannot reset an unknown stream") <8> if stream_is_client_initiated( <9> stream_id <10> ) != self._is_client and stream_is_unidirectional(stream_id): <11> raise ValueError("Cannot reset a peer-initiated unidirectional stream") <12> <13> stream = self._streams[stream_id] <14> stream.reset(error_code) <15>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection _get_or_create_stream_for_send(stream_id) ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_stream_data_peer_initiated(self): with client_and_server() as (client, server): # server creates bidirectional stream server.send_stream_data(1, b"hello") self.assertEqual(roundtrip(server, client), (1, 1)) # server creates unidirectional stream server.send_stream_data(3, b"hello") self.assertEqual(roundtrip(server, client), (1, 1)) # client creates bidirectional stream client.send_stream_data(0, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) # client sends data on server-initiated bidirectional stream client.send_stream_data(1, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) # client creates unidirectional stream client.send_stream_data(2, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) - # client tries to reset unknown stream - with self.assertRaises(ValueError) as cm: - client.reset_stream(4, QuicErrorCode.NO_ERROR) - self.assertEqual(str(cm.exception), "Cannot reset an unknown stream") - # client tries to reset server-initiated unidirectional stream with self.assertRaises(ValueError) as cm: client.reset_stream(3, QuicErrorCode.NO_ERROR) self.assertEqual( + str(cm.exception), + "Cannot send data on peer-initiated unidirectional stream", - str(cm.exception), "Cannot reset a peer-initiated unidirectional stream" + ) + + # client tries to reset unknown server-initiated bidirectional stream + with self.assertRaises(ValueError) as cm: + client.reset_stream(5, QuicErrorCode.NO_ERROR) + self.assertEqual</s> ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_stream_data_peer_initiated(self): # offset: 1 <s>) as cm: + client.reset_stream(5, QuicErrorCode.NO_ERROR) + self.assertEqual( + str(cm.exception), "Cannot send data on unknown peer-initiated stream" ) # client tries to send data on server-initiated unidirectional stream with self.assertRaises(ValueError) as cm: client.send_stream_data(3, b"hello") self.assertEqual( str(cm.exception), "Cannot send data on peer-initiated unidirectional stream", ) # client tries to send data on unknown server-initiated bidirectional stream with self.assertRaises(ValueError) as cm: client.send_stream_data(5, b"hello") self.assertEqual( str(cm.exception), "Cannot send data on unknown peer-initiated stream" )
aioquic.quic.connection/QuicConnection.send_stream_data
Modified
aiortc~aioquic
dfbeb83cf95b2ff4e81bd534097ade2ae4bd5939
[streams] refactor local stream creation
<7>:<del> if stream_is_client_initiated(stream_id) != self._is_client: <8>:<del> if stream_id not in self._streams: <9>:<del> raise ValueError("Cannot send data on unknown peer-initiated stream") <10>:<del> if stream_is_unidirectional(stream_id): <11>:<del> raise ValueError( <12>:<del> "Cannot send data on peer-initiated unidirectional stream" <13>:<del> ) <14>:<del> <15>:<del> try: <16>:<del> stream = self._streams[stream_id] <17>:<del> except KeyError: <18>:<del> self._create_stream(stream_id=stream_id) <19>:<del> stream = self._streams[stream_id] <20>:<add> stream = self._get_or_create_stream_for_send(stream_id)
# module: aioquic.quic.connection class QuicConnection: def send_stream_data( self, stream_id: int, data: bytes, end_stream: bool = False ) -> None: <0> """ <1> Send data on the specific stream. <2> <3> :param stream_id: The stream's ID. <4> :param data: The data to be sent. <5> :param end_stream: If set to `True`, the FIN bit will be set. <6> """ <7> if stream_is_client_initiated(stream_id) != self._is_client: <8> if stream_id not in self._streams: <9> raise ValueError("Cannot send data on unknown peer-initiated stream") <10> if stream_is_unidirectional(stream_id): <11> raise ValueError( <12> "Cannot send data on peer-initiated unidirectional stream" <13> ) <14> <15> try: <16> stream = self._streams[stream_id] <17> except KeyError: <18> self._create_stream(stream_id=stream_id) <19> stream = self._streams[stream_id] <20> stream.write(data, end_stream=end_stream) <21>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.quic.connection.QuicConnection _get_or_create_stream_for_send(stream_id) _stream_can_receive(stream_id: int) -> bool at: aioquic.quic.connection.QuicConnection.__init__ self._events: Deque[events.QuicEvent] = deque() at: collections.deque append(x: _T) -> None ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def reset_stream(self, stream_id: int, error_code: int) -> None: """ Abruptly terminate the sending part of a stream. :param stream_id: The stream's ID. :param error_code: An error code indicating why the stream is being reset. """ - if stream_id not in self._streams: - raise ValueError("Cannot reset an unknown stream") - if stream_is_client_initiated( - stream_id - ) != self._is_client and stream_is_unidirectional(stream_id): - raise ValueError("Cannot reset a peer-initiated unidirectional stream") - + stream = self._get_or_create_stream_for_send(stream_id) - stream = self._streams[stream_id] stream.reset(error_code) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_stream_data_peer_initiated(self): with client_and_server() as (client, server): # server creates bidirectional stream server.send_stream_data(1, b"hello") self.assertEqual(roundtrip(server, client), (1, 1)) # server creates unidirectional stream server.send_stream_data(3, b"hello") self.assertEqual(roundtrip(server, client), (1, 1)) # client creates bidirectional stream client.send_stream_data(0, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) # client sends data on server-initiated bidirectional stream client.send_stream_data(1, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) # client creates unidirectional stream client.send_stream_data(2, b"hello") self.assertEqual(roundtrip(client, server), (1, 1)) - # client tries to reset unknown stream - with self.assertRaises(ValueError) as cm: - client.reset_stream(4, QuicErrorCode.NO_ERROR) - self.assertEqual(str(cm.exception), "Cannot reset an unknown stream") - # client tries to reset server-initiated unidirectional stream with self.assertRaises(ValueError) as cm: client.reset_stream(3, QuicErrorCode.NO_ERROR) self.assertEqual( + str(cm.exception), + "Cannot send data on peer-initiated unidirectional stream", - str(cm.exception), "Cannot reset a peer-initiated unidirectional stream" + ) + + # client tries to reset unknown server-initiated bidirectional stream + with self.assertRaises(ValueError) as cm: + client.reset_stream(5, QuicErrorCode.NO_ERROR) + self.assertEqual</s> ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_stream_data_peer_initiated(self): # offset: 1 <s>) as cm: + client.reset_stream(5, QuicErrorCode.NO_ERROR) + self.assertEqual( + str(cm.exception), "Cannot send data on unknown peer-initiated stream" ) # client tries to send data on server-initiated unidirectional stream with self.assertRaises(ValueError) as cm: client.send_stream_data(3, b"hello") self.assertEqual( str(cm.exception), "Cannot send data on peer-initiated unidirectional stream", ) # client tries to send data on unknown server-initiated bidirectional stream with self.assertRaises(ValueError) as cm: client.send_stream_data(5, b"hello") self.assertEqual( str(cm.exception), "Cannot send data on unknown peer-initiated stream" )
examples.http3_server/HttpServerProtocol.http_event_received
Modified
aiortc~aioquic
86136c6b572c24e007a55add2b2f3d8e9e0ee890
[examples] add some logging
<25>:<add> self._quic._logger.info("HTTP request %s %s", method, path)
# module: examples.http3_server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: H3Event) -> None: <0> if isinstance(event, HeadersReceived) and event.stream_id not in self._handlers: <1> authority = None <2> headers = [] <3> http_version = "0.9" if isinstance(self._http, H0Connection) else "3" <4> raw_path = b"" <5> method = "" <6> protocol = None <7> for header, value in event.headers: <8> if header == b":authority": <9> authority = value <10> headers.append((b"host", value)) <11> elif header == b":method": <12> method = value.decode() <13> elif header == b":path": <14> raw_path = value <15> elif header == b":protocol": <16> protocol = value.decode() <17> elif header and not header.startswith(b":"): <18> headers.append((header, value)) <19> <20> if b"?" in raw_path: <21> path_bytes, query_string = raw_path.split(b"?", maxsplit=1) <22> else: <23> path_bytes, query_string = raw_path, b"" <24> path = path_bytes.decode() <25> <26> # FIXME: add a public API to retrieve peer address <27> client_addr = self._http._quic._network_paths[0].addr <28> client = (client_addr[0], client_addr[1]) <29> <30> handler: Handler <31> scope: Dict <32> if method == "CONNECT" and protocol == "websocket": <33> subprotocols: List[str] = [] <34> for header, value in event.headers: <35> if header == b"sec-websocket-protocol": <36> subprotocols = [x.strip() for x in value.decode().split(",")] <37> scope = { <38> "client": client, <39> "headers": headers, <40> "http_version": http_version, <41> "method": method, <42> "path":</s>
===========below chunk 0=========== # module: examples.http3_server class HttpServerProtocol(QuicConnectionProtocol): def http_event_received(self, event: H3Event) -> None: # offset: 1 "query_string": query_string, "raw_path": raw_path, "root_path": "", "scheme": "wss", "subprotocols": subprotocols, "type": "websocket", } handler = WebSocketHandler( connection=self._http, scope=scope, stream_id=event.stream_id, transmit=self.transmit, ) else: extensions: Dict[str, Dict] = {} if isinstance(self._http, H3Connection): extensions["http.response.push"] = {} scope = { "client": client, "extensions": extensions, "headers": headers, "http_version": http_version, "method": method, "path": path, "query_string": query_string, "raw_path": raw_path, "root_path": "", "scheme": "https", "type": "http", } handler = HttpRequestHandler( authority=authority, connection=self._http, protocol=self, scope=scope, stream_ended=event.stream_ended, stream_id=event.stream_id, transmit=self.transmit, ) self._handlers[event.stream_id] = handler asyncio.ensure_future(handler.run_asgi(application)) elif ( isinstance(event, (DataReceived, HeadersReceived)) and event.stream_id in self._handlers ): handler = self._handlers[event.stream_id] handler.http_event_received(event) ===========unchanged ref 0=========== at: examples.http3_server HttpRequestHandler(*, authority: bytes, connection: HttpConnection, protocol: QuicConnectionProtocol, scope: Dict, stream_ended: bool, stream_id: int, transmit: Callable[[], None]) WebSocketHandler(*, connection: HttpConnection, scope: Dict, stream_id: int, transmit: Callable[[], None]) Handler = Union[HttpRequestHandler, WebSocketHandler] application = getattr(module, attr_str) at: examples.http3_server.HttpServerProtocol.__init__ self._handlers: Dict[int, Handler] = {} self._http: Optional[HttpConnection] = None at: examples.http3_server.HttpServerProtocol.quic_event_received self._http = H3Connection(self._quic) self._http = H0Connection(self._quic) at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.h0.connection/H0Connection.__init__
Modified
aiortc~aioquic
c4488cf51af173991588807861cf2b4f64b33b0a
[h0] handle fragmented requests
<0>:<add> self._buffer: Dict[int, bytes] = {}
# module: aioquic.h0.connection class H0Connection: def __init__(self, quic: QuicConnection): <0> self._headers_received: Dict[int, bool] = {} <1> self._is_client = quic.configuration.is_client <2> self._quic = quic <3>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): + def test_fragmented_request(self): + with h0_client_and_server() as (quic_client, quic_server): + h0_server = H0Connection(quic_server) + stream_id = 0 + + # receive first fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"GET /012", end_stream=False, stream_id=stream_id + ) + ) + self.assertEqual(len(events), 0) + + # receive second fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"34567890", end_stream=False, stream_id=stream_id + ) + ) + + # receive final fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"123456\r\n", end_stream=True, stream_id=stream_id + ) + ) + self.assertEqual(len(events), 2) + + self.assertTrue(isinstance(events[0], HeadersReceived)) + self.assertEqual( + events[0].headers, + [(b":method", b"GET"), (b":path", b"/01234567890123456")], + ) + self.assertEqual(events[0].stream_id, stream_id) + self.assertEqual(events[0].stream_ended, False) + + self.assertTrue(isinstance(events[1], DataReceived)) + self.assertEqual(events[1].data, b"") + self.assertEqual(events[1].stream_id, stream_id) + self.assertEqual(events[1].stream_ended, True) +
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
c4488cf51af173991588807861cf2b4f64b33b0a
[h0] handle fragmented requests
<3>:<add> data = self._buffer.pop(event.stream_id, b"") + event.data <del> data = event.data <11>:<add> elif data.endswith(b"\r\n") or event.end_stream: <del> else: <21>:<add> else: <add> # incomplete request, stash the data <add> self._buffer[event.stream_id] = data <add> return http_events
# module: aioquic.h0.connection class H0Connection: def handle_event(self, event: QuicEvent) -> List[H3Event]: <0> http_events: List[H3Event] = [] <1> <2> if isinstance(event, StreamDataReceived) and (event.stream_id % 4) == 0: <3> data = event.data <4> if not self._headers_received.get(event.stream_id, False): <5> if self._is_client: <6> http_events.append( <7> HeadersReceived( <8> headers=[], stream_ended=False, stream_id=event.stream_id <9> ) <10> ) <11> else: <12> method, path = data.rstrip().split(b" ", 1) <13> http_events.append( <14> HeadersReceived( <15> headers=[(b":method", method), (b":path", path)], <16> stream_ended=False, <17> stream_id=event.stream_id, <18> ) <19> ) <20> data = b"" <21> self._headers_received[event.stream_id] = True <22> <23> http_events.append( <24> DataReceived( <25> data=data, stream_ended=event.end_stream, stream_id=event.stream_id <26> ) <27> ) <28> <29> return http_events <30>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection.__init__ self._buffer: Dict[int, bytes] = {} self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client at: typing List = _alias(list, 1, inst=False, name='List') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.h0.connection class H0Connection: def __init__(self, quic: QuicConnection): + self._buffer: Dict[int, bytes] = {} self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client self._quic = quic ===========changed ref 1=========== # module: tests.test_h0 class H0ConnectionTest(TestCase): + def test_fragmented_request(self): + with h0_client_and_server() as (quic_client, quic_server): + h0_server = H0Connection(quic_server) + stream_id = 0 + + # receive first fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"GET /012", end_stream=False, stream_id=stream_id + ) + ) + self.assertEqual(len(events), 0) + + # receive second fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"34567890", end_stream=False, stream_id=stream_id + ) + ) + + # receive final fragment of the request + events = h0_server.handle_event( + StreamDataReceived( + data=b"123456\r\n", end_stream=True, stream_id=stream_id + ) + ) + self.assertEqual(len(events), 2) + + self.assertTrue(isinstance(events[0], HeadersReceived)) + self.assertEqual( + events[0].headers, + [(b":method", b"GET"), (b":path", b"/01234567890123456")], + ) + self.assertEqual(events[0].stream_id, stream_id) + self.assertEqual(events[0].stream_ended, False) + + self.assertTrue(isinstance(events[1], DataReceived)) + self.assertEqual(events[1].data, b"") + self.assertEqual(events[1].stream_id, stream_id) + self.assertEqual(events[1].stream_ended, True) +
tests.test_connection/QuicConnectionTest.test_handle_max_stream_data_frame
Modified
aiortc~aioquic
ccf1b53843ef604fa655b07713b6623e0268b1e8
[streams] fix broken unit tests
<2>:<add> stream = client._get_or_create_stream_for_send(stream_id=0) <del> stream = client._create_stream(stream_id=0)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_max_stream_data_frame(self): <0> with client_and_server() as (client, server): <1> # client creates bidirectional stream 0 <2> stream = client._create_stream(stream_id=0) <3> self.assertEqual(stream.max_stream_data_remote, 1048576) <4> <5> # client receives MAX_STREAM_DATA raising limit <6> client._handle_max_stream_data_frame( <7> client_receive_context(client), <8> QuicFrameType.MAX_STREAM_DATA, <9> Buffer(data=b"\x00" + encode_uint_var(1048577)), <10> ) <11> self.assertEqual(stream.max_stream_data_remote, 1048577) <12> <13> # client receives MAX_STREAM_DATA lowering limit <14> client._handle_max_stream_data_frame( <15> client_receive_context(client), <16> QuicFrameType.MAX_STREAM_DATA, <17> Buffer(data=b"\x00" + encode_uint_var(1048575)), <18> ) <19> self.assertEqual(stream.max_stream_data_remote, 1048577) <20>
===========unchanged ref 0=========== at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) 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) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None
tests.test_connection/QuicConnectionTest.test_send_max_stream_data_retransmit
Modified
aiortc~aioquic
ccf1b53843ef604fa655b07713b6623e0268b1e8
[streams] fix broken unit tests
<2>:<add> stream = client._get_or_create_stream_for_send(stream_id=0) <del> stream = client._create_stream(stream_id=0)
# 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> self.assertEqual(roundtrip(client, server), (1, 1)) <7> <8> # server sends data, just before raising MAX_STREAM_DATA <9> server.send_stream_data(0, b"Z" * 524288) # 1048576 // 2 <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> self.assertEqual(transfer(server, client), 1) <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.</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_stream_data_retransmit(self): # offset: 1 self.assertEqual(stream.max_stream_data_local_sent, 2097152) ===========unchanged ref 0=========== 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) drop(sender) roundtrip(sender, receiver) transfer(sender, receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_max_stream_data_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 + stream = client._get_or_create_stream_for_send(stream_id=0) - stream = client._create_stream(stream_id=0) self.assertEqual(stream.max_stream_data_remote, 1048576) # client receives MAX_STREAM_DATA raising limit client._handle_max_stream_data_frame( client_receive_context(client), QuicFrameType.MAX_STREAM_DATA, Buffer(data=b"\x00" + encode_uint_var(1048577)), ) self.assertEqual(stream.max_stream_data_remote, 1048577) # client receives MAX_STREAM_DATA lowering limit client._handle_max_stream_data_frame( client_receive_context(client), QuicFrameType.MAX_STREAM_DATA, Buffer(data=b"\x00" + encode_uint_var(1048575)), ) self.assertEqual(stream.max_stream_data_remote, 1048577)
aioquic.quic.logger/QuicLoggerTrace.encode_max_streams_frame
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<3>:<add> "stream_type": "unidirectional" <add> if frame_type == QuicFrameType.MAX_STREAMS_UNI <add> else "bidirectional", <del> "stream_type": "unidirectional" if is_unidirectional else "bidirectional",
# module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: <0> return { <1> "frame_type": "max_streams", <2> "maximum": str(maximum), <3> "stream_type": "unidirectional" if is_unidirectional else "bidirectional", <4> } <5>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_send_max_streams_retransmit(self): + with client_and_server() as (client, server): + # client opens 65 streams + client.send_stream_data(4 * 64, b"Z") + self.assertEqual(transfer(client, server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 128) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 128) + + # MAX_STREAMS is sent and lost + self.assertEqual(drop(server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_DATA is retransmitted and acked + server._on_max_streams_delivery( + QuicDeliveryState.LOST, server._local_max_streams_bidi + ) + self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(roundtrip(server, client), (1, 1)) + self.assertEqual(client._remote_max_streams_bidi, 256) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) +
aioquic.quic.connection/QuicConnection._get_or_create_stream
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<24>:<add> stream_count = (stream_id // 4) + 1 <add> if stream_count > max_streams.value: <del> if stream_id // 4 >= max_streams: <30>:<add> elif stream_count > max_streams.used: <add> max_streams.used = stream_count
# module: aioquic.quic.connection class QuicConnection: def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream: <0> """ <1> Get or create a stream in response to a received frame. <2> """ <3> stream = self._streams.get(stream_id, None) <4> if stream is None: <5> # check initiator <6> if stream_is_client_initiated(stream_id) == self._is_client: <7> raise QuicConnectionError( <8> error_code=QuicErrorCode.STREAM_STATE_ERROR, <9> frame_type=frame_type, <10> reason_phrase="Wrong stream initiator", <11> ) <12> <13> # determine limits <14> if stream_is_unidirectional(stream_id): <15> max_stream_data_local = self._local_max_stream_data_uni <16> max_stream_data_remote = 0 <17> max_streams = self._local_max_streams_uni <18> else: <19> max_stream_data_local = self._local_max_stream_data_bidi_remote <20> max_stream_data_remote = self._remote_max_stream_data_bidi_local <21> max_streams = self._local_max_streams_bidi <22> <23> # check max streams <24> if stream_id // 4 >= max_streams: <25> raise QuicConnectionError( <26> error_code=QuicErrorCode.STREAM_LIMIT_ERROR, <27> frame_type=frame_type, <28> reason_phrase="Too many streams open", <29> ) <30> <31> # create stream <32> self._logger.debug("Stream %d created by peer" % stream_id) <33> stream = self._streams[stream_id] = QuicStream( <34> stream_id=stream_id, <35> max_stream_data_local=max_stream_data_local, <36> max_stream_data_remote=max_stream_data_remote, <37> ) <38> return stream <39>
===========unchanged ref 0=========== at: aioquic.quic.connection NetworkAddress = Any stream_is_client_initiated(stream_id: int) -> bool stream_is_unidirectional(stream_id: int) -> bool QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) 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.__init__ self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._local_max_stream_data_bidi_remote = configuration.max_stream_data self._local_max_stream_data_uni = configuration.max_stream_data self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._network_paths: List[QuicNetworkPath] = [] self._remote_max_stream_data_bidi_local = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._streams: Dict[int, QuicStream] = {} self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) ===========unchanged ref 1=========== 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._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(), } at: aioquic.quic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] at: aioquic.quic.connection.QuicConnection.receive_datagram self._network_paths = [network_path] 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: 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 at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: aioquic.quic.connection + class Limit: + def __init__(self, frame_type: int, name: str, value: int): + self.frame_type = frame_type + self.name = name + self.sent = value + self.used = 0 + self.value = value + ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: return { "frame_type": "max_streams", "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", - "stream_type": "unidirectional" if is_unidirectional else "bidirectional", } ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_send_max_streams_retransmit(self): + with client_and_server() as (client, server): + # client opens 65 streams + client.send_stream_data(4 * 64, b"Z") + self.assertEqual(transfer(client, server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 128) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 128) + + # MAX_STREAMS is sent and lost + self.assertEqual(drop(server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_DATA is retransmitted and acked + server._on_max_streams_delivery( + QuicDeliveryState.LOST, server._local_max_streams_bidi + ) + self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(roundtrip(server, client), (1, 1)) + self.assertEqual(client._remote_max_streams_bidi, 256) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) +
aioquic.quic.connection/QuicConnection._handle_max_streams_bidi_frame
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<11>:<add> frame_type=frame_type, maximum=max_streams <del> is_unidirectional=False, maximum=max_streams
# module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_STREAMS_BIDI frame. <2> <3> This raises number of bidirectional streams we can initiate to the peer. <4> """ <5> max_streams = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_max_streams_frame( <11> is_unidirectional=False, maximum=max_streams <12> ) <13> ) <14> <15> if max_streams > self._remote_max_streams_bidi: <16> self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) <17> self._remote_max_streams_bidi = max_streams <18> self._unblock_streams(is_unidirectional=False) <19>
===========unchanged ref 0=========== at: aioquic.quic.connection 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_send(frame_type: int, stream_id: int) -> None _get_or_create_stream(frame_type: int, stream_id: int) -> QuicStream _get_or_create_stream(self, 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=self._original_destination_connection_id, ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_max_stream_data_frame stream_id = buf.pull_uint_var() max_stream_data = buf.pull_uint_var() at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float 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 _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream: """ Get or create a stream in response to a received frame. """ stream = self._streams.get(stream_id, None) if stream is None: # check initiator if stream_is_client_initiated(stream_id) == self._is_client: raise QuicConnectionError( error_code=QuicErrorCode.STREAM_STATE_ERROR, frame_type=frame_type, reason_phrase="Wrong stream initiator", ) # determine limits if stream_is_unidirectional(stream_id): max_stream_data_local = self._local_max_stream_data_uni max_stream_data_remote = 0 max_streams = self._local_max_streams_uni else: max_stream_data_local = self._local_max_stream_data_bidi_remote max_stream_data_remote = self._remote_max_stream_data_bidi_local max_streams = self._local_max_streams_bidi # check max streams + stream_count = (stream_id // 4) + 1 + if stream_count > max_streams.value: - if stream_id // 4 >= max_streams: raise QuicConnectionError( error_code=QuicErrorCode.STREAM_LIMIT_ERROR, frame_type=frame_type, reason_phrase="Too many streams open", ) + elif stream_count > max_streams.used: + max_streams.used = stream_count # create stream self._logger.debug("Stream %d created by peer" % stream_id) stream = self._streams[stream_id] = QuicStream( stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream: # offset: 1 <s> max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) return stream ===========changed ref 2=========== # module: aioquic.quic.connection + class Limit: + def __init__(self, frame_type: int, name: str, value: int): + self.frame_type = frame_type + self.name = name + self.sent = value + self.used = 0 + self.value = value + ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: return { "frame_type": "max_streams", "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", - "stream_type": "unidirectional" if is_unidirectional else "bidirectional", } ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_send_max_streams_retransmit(self): + with client_and_server() as (client, server): + # client opens 65 streams + client.send_stream_data(4 * 64, b"Z") + self.assertEqual(transfer(client, server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 128) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 128) + + # MAX_STREAMS is sent and lost + self.assertEqual(drop(server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_DATA is retransmitted and acked + server._on_max_streams_delivery( + QuicDeliveryState.LOST, server._local_max_streams_bidi + ) + self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(roundtrip(server, client), (1, 1)) + self.assertEqual(client._remote_max_streams_bidi, 256) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) +
aioquic.quic.connection/QuicConnection._handle_max_streams_uni_frame
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<11>:<add> frame_type=frame_type, maximum=max_streams <del> is_unidirectional=True, maximum=max_streams
# module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_STREAMS_UNI frame. <2> <3> This raises number of unidirectional streams we can initiate to the peer. <4> """ <5> max_streams = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_max_streams_frame( <11> is_unidirectional=True, maximum=max_streams <12> ) <13> ) <14> <15> if max_streams > self._remote_max_streams_uni: <16> self._logger.debug("Remote max_streams_uni raised to %d", max_streams) <17> self._remote_max_streams_uni = max_streams <18> self._unblock_streams(is_unidirectional=True) <19>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _unblock_streams(is_unidirectional: bool) -> 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=self._original_destination_connection_id, ) self._remote_max_streams_bidi = 0 self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicReceiveContext quic_logger_frames: Optional[List[Any]] 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 _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( + frame_type=frame_type, maximum=max_streams - is_unidirectional=False, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False) ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream: """ Get or create a stream in response to a received frame. """ stream = self._streams.get(stream_id, None) if stream is None: # check initiator if stream_is_client_initiated(stream_id) == self._is_client: raise QuicConnectionError( error_code=QuicErrorCode.STREAM_STATE_ERROR, frame_type=frame_type, reason_phrase="Wrong stream initiator", ) # determine limits if stream_is_unidirectional(stream_id): max_stream_data_local = self._local_max_stream_data_uni max_stream_data_remote = 0 max_streams = self._local_max_streams_uni else: max_stream_data_local = self._local_max_stream_data_bidi_remote max_stream_data_remote = self._remote_max_stream_data_bidi_local max_streams = self._local_max_streams_bidi # check max streams + stream_count = (stream_id // 4) + 1 + if stream_count > max_streams.value: - if stream_id // 4 >= max_streams: raise QuicConnectionError( error_code=QuicErrorCode.STREAM_LIMIT_ERROR, frame_type=frame_type, reason_phrase="Too many streams open", ) + elif stream_count > max_streams.used: + max_streams.used = stream_count # create stream self._logger.debug("Stream %d created by peer" % stream_id) stream = self._streams[stream_id] = QuicStream( stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream</s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _get_or_create_stream(self, frame_type: int, stream_id: int) -> QuicStream: # offset: 1 <s> max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) return stream ===========changed ref 3=========== # module: aioquic.quic.connection + class Limit: + def __init__(self, frame_type: int, name: str, value: int): + self.frame_type = frame_type + self.name = name + self.sent = value + self.used = 0 + self.value = value + ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: return { "frame_type": "max_streams", "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", - "stream_type": "unidirectional" if is_unidirectional else "bidirectional", } ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_send_max_streams_retransmit(self): + with client_and_server() as (client, server): + # client opens 65 streams + client.send_stream_data(4 * 64, b"Z") + self.assertEqual(transfer(client, server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 128) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 128) + + # MAX_STREAMS is sent and lost + self.assertEqual(drop(server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_DATA is retransmitted and acked + server._on_max_streams_delivery( + QuicDeliveryState.LOST, server._local_max_streams_bidi + ) + self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(roundtrip(server, client), (1, 1)) + self.assertEqual(client._remote_max_streams_bidi, 256) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) +
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<8>:<add> initial_max_streams_bidi=self._local_max_streams_bidi.value, <del> initial_max_streams_bidi=self._local_max_streams_bidi, <9>:<add> initial_max_streams_uni=self._local_max_streams_uni.value, <del> initial_max_streams_uni=self._local_max_streams_uni,
# 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> max_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> initial_source_connection_id=self._local_initial_source_connection_id, <11> max_ack_delay=25, <12> max_datagram_frame_size=self._configuration.max_datagram_frame_size, <13> quantum_readiness=b"Q" * 1200 <14> if self._configuration.quantum_readiness_test <15> else None, <16> ) <17> if not self._is_client: <18> quic_transport_parameters.original_destination_connection_id = ( <19> self._original_destination_connection_id <20> ) <21> quic_transport_parameters.retry_source_connection_id = ( <22> self._retry_source_connection_id <23> ) <24> <25> # log event <26> if self._quic_logger is not None: <27> self._quic_logger.log_event( <28> category="transport", <29> event="parameters_set", <30> data=self._quic_logger.encode_transport_</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========unchanged ref 0=========== at: aioquic.quic.connection.Limit.__init__ self.value = value at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._local_ack_delay_exponent = 3 self._local_active_connection_id_limit = 8 self._local_max_data = configuration.max_data self._local_max_stream_data_bidi_local = configuration.max_stream_data self._local_max_stream_data_bidi_remote = configuration.max_stream_data self._local_max_stream_data_uni = configuration.max_stream_data self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._remote_ack_delay_exponent = 3 self._remote_active_connection_id_limit = 0 self._remote_max_idle_timeout = 0.0 # seconds self._remote_max_datagram_frame_size: Optional[int] = None 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._parse_transport_parameters quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) at: aioquic.quic.connection.QuicConnection._write_connection_limits self._local_max_data *= 2 ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: + def _on_max_streams_delivery( + self, delivery: QuicDeliveryState, max_streams: Limit + ) -> None: + """ + Callback when a MAX_STREAMS frame is acknowledged or lost. + """ + if delivery != QuicDeliveryState.ACKED: + max_streams.sent = 0 + ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_UNI frame. This raises number of unidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( + frame_type=frame_type, maximum=max_streams - is_unidirectional=True, maximum=max_streams ) ) if max_streams > self._remote_max_streams_uni: self._logger.debug("Remote max_streams_uni raised to %d", max_streams) self._remote_max_streams_uni = max_streams self._unblock_streams(is_unidirectional=True) ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( + frame_type=frame_type, maximum=max_streams - is_unidirectional=False, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False) ===========changed ref 3=========== # module: aioquic.quic.connection + class Limit: + def __init__(self, frame_type: int, name: str, value: int): + self.frame_type = frame_type + self.name = name + self.sent = value + self.used = 0 + self.value = value + ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: return { "frame_type": "max_streams", "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", - "stream_type": "unidirectional" if is_unidirectional else "bidirectional", } ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_send_max_streams_retransmit(self): + with client_and_server() as (client, server): + # client opens 65 streams + client.send_stream_data(4 * 64, b"Z") + self.assertEqual(transfer(client, server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 128) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 128) + + # MAX_STREAMS is sent and lost + self.assertEqual(drop(server), 1) + self.assertEqual(client._remote_max_streams_bidi, 128) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_DATA is retransmitted and acked + server._on_max_streams_delivery( + QuicDeliveryState.LOST, server._local_max_streams_bidi + ) + self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(roundtrip(server, client), (1, 1)) + self.assertEqual(client._remote_max_streams_bidi, 256) + self.assertEqual(server._local_max_streams_bidi.sent, 256) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) +
aioquic.quic.connection/QuicConnection._write_connection_limits
Modified
aiortc~aioquic
b4853eb5d6e8cf45dbcd10945fa673741f357877
[streams] send MAX_STREAMS as needed
<1>:<add> Raise MAX_DATA or MAX_STREAMS if needed. <del> Raise MAX_DATA if needed.
# module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: <0> """ <1> Raise MAX_DATA if needed. <2> """ <3> if self._local_max_data_used * 2 > self._local_max_data: <4> self._local_max_data *= 2 <5> self._logger.debug("Local max_data raised to %d", self._local_max_data) <6> if self._local_max_data_sent != self._local_max_data: <7> buf = builder.start_frame( <8> QuicFrameType.MAX_DATA, <9> capacity=MAX_DATA_FRAME_CAPACITY, <10> handler=self._on_max_data_delivery, <11> ) <12> buf.push_uint_var(self._local_max_data) <13> self._local_max_data_sent = self._local_max_data <14> <15> # log frame <16> if self._quic_logger is not None: <17> builder.quic_logger_frames.append( <18> self._quic_logger.encode_max_data_frame(self._local_max_data) <19> ) <20>
===========unchanged ref 0=========== at: aioquic.quic.connection APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 # + reason length TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 + 8 # + reason length 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=self._original_destination_connection_id, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._write_connection_close_frame error_code = QuicErrorCode.APPLICATION_ERROR frame_type = QuicFrameType.PADDING reason_bytes = reason_phrase.encode("utf8") reason_length = len(reason_bytes) ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: + def _on_max_streams_delivery( + self, delivery: QuicDeliveryState, max_streams: Limit + ) -> None: + """ + Callback when a MAX_STREAMS frame is acknowledged or lost. + """ + if delivery != QuicDeliveryState.ACKED: + max_streams.sent = 0 + ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: quic_transport_parameters = QuicTransportParameters( ack_delay_exponent=self._local_ack_delay_exponent, active_connection_id_limit=self._local_active_connection_id_limit, max_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.value, - initial_max_streams_bidi=self._local_max_streams_bidi, + initial_max_streams_uni=self._local_max_streams_uni.value, - initial_max_streams_uni=self._local_max_streams_uni, initial_source_connection_id=self._local_initial_source_connection_id, max_ack_delay=25, max_datagram_frame_size=self._configuration.max_datagram_frame_size, quantum_readiness=b"Q" * 1200 if self._configuration.quantum_readiness_test else None, ) if not self._is_client: quic_transport_parameters.original_destination_connection_id = ( self._original_destination_connection_id ) quic_transport_parameters.retry_source_connection_id = ( self._retry_source_connection_id ) # log event if self._quic_logger is not None: self._quic_logger.log_event( category="transport", </s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 <s>._quic_logger is not None: self._quic_logger.log_event( category="transport", event="parameters_set", data=self._quic_logger.encode_transport_parameters( owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========changed ref 3=========== # module: aioquic.quic.connection + class Limit: + def __init__(self, frame_type: int, name: str, value: int): + self.frame_type = frame_type + self.name = name + self.sent = value + self.used = 0 + self.value = value + ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - def encode_max_streams_frame(self, is_unidirectional: bool, maximum: int) -> Dict: return { "frame_type": "max_streams", "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", - "stream_type": "unidirectional" if is_unidirectional else "bidirectional", } ===========changed ref 5=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_UNI frame. This raises number of unidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( + frame_type=frame_type, maximum=max_streams - is_unidirectional=True, maximum=max_streams ) ) if max_streams > self._remote_max_streams_uni: self._logger.debug("Remote max_streams_uni raised to %d", max_streams) self._remote_max_streams_uni = max_streams self._unblock_streams(is_unidirectional=True) ===========changed ref 6=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( + frame_type=frame_type, maximum=max_streams - is_unidirectional=False, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False)
tests.test_connection/QuicConnectionTest.test_handle_stream_frame_over_max_data
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<2>:<add> client._local_max_data.used = client._local_max_data.value <del> client._local_max_data_used = client._local_max_data
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): <0> with client_and_server() as (client, server): <1> # artificially raise received data counter <2> client._local_max_data_used = client._local_max_data <3> <4> # client receives STREAM frame <5> frame_type = QuicFrameType.STREAM_BASE | 4 <6> stream_id = 1 <7> with self.assertRaises(QuicConnectionError) as cm: <8> client._handle_stream_frame( <9> client_receive_context(client), <10> frame_type, <11> Buffer(data=encode_uint_var(stream_id) + encode_uint_var(1)), <12> ) <13> self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) <14> self.assertEqual(cm.exception.frame_type, frame_type) <15> self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") <16>
===========unchanged ref 0=========== at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) 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) 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)
tests.test_connection/QuicConnectionTest.test_send_max_data_retransmit
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<2>:<add> client._local_max_data.used = client._local_max_data.value <del> client._local_max_data_used = client._local_max_data <3>:<add> self.assertEqual(client._local_max_data.sent, 1048576) <add> self.assertEqual(client._local_max_data.used, 1048576) <add> self.assertEqual(client._local_max_data.value, 1048576) <7>:<add> self.assertEqual(client._local_max_data.sent, 2097152) <del> self.assertEqual(client._local_max_data_sent, 2097152) <8>:<add> self.assertEqual(client._local_max_data.used, 1048576) <add> self.assertEqual(client._local_max_data.value, 2097152) <10>:<add> # MAX_DATA loss is detected <add> client._on_connection_limit_delivery( <add> QuicDeliveryState.LOST, client._local_max_data <add> ) <add> self.assertEqual(client._local_max_data.sent, 0) <add> self.assertEqual(client._local_max_data.used, 1048576) <add>
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_data_retransmit(self): <0> with client_and_server() as (client, server): <1> # artificially raise received data counter <2> client._local_max_data_used = client._local_max_data <3> self.assertEqual(server._remote_max_data, 1048576) <4> <5> # MAX_DATA is sent and lost <6> self.assertEqual(drop(client), 1) <7> self.assertEqual(client._local_max_data_sent, 2097152) <8> self.assertEqual(server._remote_max_data, 1048576) <9> <10> # MAX_DATA is retransmitted and acked <11> client._on_max_data_delivery(QuicDeliveryState.LOST) <12> self.assertEqual(client._local_max_data_sent, 0) <13> self.assertEqual(roundtrip(client, server), (1, 1)) <14> self.assertEqual(server._remote_max_data, 2097152) <15>
===========unchanged ref 0=========== 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) drop(sender) roundtrip(sender, receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit")
tests.test_connection/QuicConnectionTest.test_send_max_streams_retransmit
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<16>:<add> # MAX_STREAMS loss is detected <del> # MAX_DATA is retransmitted and acked <17>:<add> server._on_connection_limit_delivery( <del> server._on_max_streams_delivery( <20>:<add> self.assertEqual(client._remote_max_streams_bidi, 128) <21>:<add> self.assertEqual(server._local_max_streams_bidi.used, 65) <add> self.assertEqual(server._local_max_streams_bidi.value, 256) <add> <add> # MAX_STREAMS is retransmitted and acked
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_streams_retransmit(self): <0> with client_and_server() as (client, server): <1> # client opens 65 streams <2> client.send_stream_data(4 * 64, b"Z") <3> self.assertEqual(transfer(client, server), 1) <4> self.assertEqual(client._remote_max_streams_bidi, 128) <5> self.assertEqual(server._local_max_streams_bidi.sent, 128) <6> self.assertEqual(server._local_max_streams_bidi.used, 65) <7> self.assertEqual(server._local_max_streams_bidi.value, 128) <8> <9> # MAX_STREAMS is sent and lost <10> self.assertEqual(drop(server), 1) <11> self.assertEqual(client._remote_max_streams_bidi, 128) <12> self.assertEqual(server._local_max_streams_bidi.sent, 256) <13> self.assertEqual(server._local_max_streams_bidi.used, 65) <14> self.assertEqual(server._local_max_streams_bidi.value, 256) <15> <16> # MAX_DATA is retransmitted and acked <17> server._on_max_streams_delivery( <18> QuicDeliveryState.LOST, server._local_max_streams_bidi <19> ) <20> self.assertEqual(server._local_max_streams_bidi.sent, 0) <21> self.assertEqual(roundtrip(server, client), (1, 1)) <22> self.assertEqual(client._remote_max_streams_bidi, 256) <23> self.assertEqual(server._local_max_streams_bidi.sent, 256) <24> self.assertEqual(server._local_max_streams_bidi.used, 65) <25> self.assertEqual(server._local_max_streams_bidi.value, 256) <26>
===========unchanged ref 0=========== 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) drop(sender) roundtrip(sender, receiver) transfer(sender, receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_data_retransmit(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data + self.assertEqual(client._local_max_data.sent, 1048576) + self.assertEqual(client._local_max_data.used, 1048576) + self.assertEqual(client._local_max_data.value, 1048576) self.assertEqual(server._remote_max_data, 1048576) # MAX_DATA is sent and lost self.assertEqual(drop(client), 1) + self.assertEqual(client._local_max_data.sent, 2097152) - self.assertEqual(client._local_max_data_sent, 2097152) + self.assertEqual(client._local_max_data.used, 1048576) + self.assertEqual(client._local_max_data.value, 2097152) self.assertEqual(server._remote_max_data, 1048576) + # MAX_DATA loss is detected + client._on_connection_limit_delivery( + QuicDeliveryState.LOST, client._local_max_data + ) + self.assertEqual(client._local_max_data.sent, 0) + self.assertEqual(client._local_max_data.used, 1048576) + self.assertEqual(client._local_max_data.value, 2097152) + # MAX_DATA is retransmitted and acked - client._on_max_data_delivery(QuicDeliveryState.LOST) - self.assertEqual(client._local_max_data_sent, 0) self.assertEqual(roundtrip(client, server), (1, 1)) + self.assertEqual(</s> ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_data_retransmit(self): # offset: 1 <s>, 0) self.assertEqual(roundtrip(client, server), (1, 1)) + self.assertEqual(client._local_max_data.sent, 2097152) + self.assertEqual(client._local_max_data.used, 1048576) + self.assertEqual(client._local_max_data.value, 2097152) self.assertEqual(server._remote_max_data, 2097152)
aioquic.quic.connection/QuicConnection._handle_max_data_frame
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<10>:<add> self._quic_logger.encode_connection_limit_frame( <add> frame_type=frame_type, maximum=max_data <add> ) <del> self._quic_logger.encode_max_data_frame(maximum=max_data)
# module: aioquic.quic.connection class QuicConnection: def _handle_max_data_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_DATA frame. <2> <3> This adjusts the total amount of we can send to the peer. <4> """ <5> max_data = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_max_data_frame(maximum=max_data) <11> ) <12> <13> if max_data > self._remote_max_data: <14> self._logger.debug("Remote max_data raised to %d", max_data) <15> self._remote_max_data = max_data <16>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) 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=self._original_destination_connection_id, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 0=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_data_frame(self, maximum: int) -> Dict: - return {"frame_type": "max_data", "maximum": str(maximum)} - ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - return { - "frame_type": "max_streams", - "maximum": str(maximum), - "stream_type": "unidirectional" - if frame_type == QuicFrameType.MAX_STREAMS_UNI - else "bidirectional", - } - ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_connection_limit_frame(self, frame_type: int, maximum: int) -> Dict: + if frame_type == QuicFrameType.MAX_DATA: + return {"frame_type": "max_data", "maximum": str(maximum)} + else: + return { + "frame_type": "max_streams", + "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", + } + ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") ===========changed ref 4=========== # module: aioquic.quic.connection logger = logging.getLogger("quic") CRYPTO_BUFFER_SIZE = 16384 EPOCH_SHORTCUTS = { "I": tls.Epoch.INITIAL, "H": tls.Epoch.HANDSHAKE, "0": tls.Epoch.ZERO_RTT, "1": tls.Epoch.ONE_RTT, } MAX_EARLY_DATA = 0xFFFFFFFF 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", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any # frame sizes ACK_FRAME_CAPACITY = 64 # FIXME: this is arbitrary! APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 # + reason length + CONNECTION_LIMIT_FRAME_CAPACITY = 1 + 8 HANDSHAKE_DONE_FRAME_CAPACITY = 1 - MAX_DATA_FRAME_CAPACITY = 1 + 8 MAX_STREAM_DATA_FRAME_CAPACITY = 1 + 8 + 8 - MAX_STREAMS_FRAME_CAPACITY = 1 + 8 NEW_CONNECTION_ID_FRAME_CAPACITY = 1 + 8 + 8 + 1 + 20 + 16 PATH_CHALLENGE_FRAME_CAPACITY = 1 + 8 PATH_RESPONSE_FRAME_CAPACITY = 1 + 8 PING_FRAME_CAPACITY = 1 RESET_STREAM_CAPACITY = 1 + 8 + 8 + 8 RETIRE_CONNECTION_ID_CAPACITY = 1 + 8 STREAMS_BLOCKED_CAPACITY = 1 + 8 TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 + 8 # + reason length ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_streams_retransmit(self): with client_and_server() as (client, server): # client opens 65 streams client.send_stream_data(4 * 64, b"Z") self.assertEqual(transfer(client, server), 1) self.assertEqual(client._remote_max_streams_bidi, 128) self.assertEqual(server._local_max_streams_bidi.sent, 128) self.assertEqual(server._local_max_streams_bidi.used, 65) self.assertEqual(server._local_max_streams_bidi.value, 128) # MAX_STREAMS is sent and lost self.assertEqual(drop(server), 1) self.assertEqual(client._remote_max_streams_bidi, 128) self.assertEqual(server._local_max_streams_bidi.sent, 256) self.assertEqual(server._local_max_streams_bidi.used, 65) self.assertEqual(server._local_max_streams_bidi.value, 256) + # MAX_STREAMS loss is detected - # MAX_DATA is retransmitted and acked + server._on_connection_limit_delivery( - server._on_max_streams_delivery( QuicDeliveryState.LOST, server._local_max_streams_bidi ) + self.assertEqual(client._remote_max_streams_bidi, 128) self.assertEqual(server._local_max_streams_bidi.sent, 0) + self.assertEqual(server._local_max_streams_bidi.used, 65) + self.assertEqual(server._local_max_streams_bidi.value, 256) + + # MAX_STREAMS is retransmitted and acked self.assertEqual(roundtrip(server, client), (1, 1)) self.assertEqual(client._remote_max_streams_bidi, 256) self.</s> ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_send_max_streams_retransmit(self): # offset: 1 <s>), (1, 1)) self.assertEqual(client._remote_max_streams_bidi, 256) self.assertEqual(server._local_max_streams_bidi.sent, 256) self.assertEqual(server._local_max_streams_bidi.used, 65) self.assertEqual(server._local_max_streams_bidi.value, 256)
aioquic.quic.connection/QuicConnection._handle_max_streams_bidi_frame
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<10>:<add> self._quic_logger.encode_connection_limit_frame( <del> self._quic_logger.encode_max_streams_frame(
# module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_STREAMS_BIDI frame. <2> <3> This raises number of bidirectional streams we can initiate to the peer. <4> """ <5> max_streams = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_max_streams_frame( <11> frame_type=frame_type, maximum=max_streams <12> ) <13> ) <14> <15> if max_streams > self._remote_max_streams_bidi: <16> self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) <17> self._remote_max_streams_bidi = max_streams <18> self._unblock_streams(is_unidirectional=False) <19>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) 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=self._original_destination_connection_id, ) self._remote_max_streams_bidi = 0 at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_max_stream_data_frame max_stream_data = buf.pull_uint_var() stream = self._get_or_create_stream(frame_type, stream_id) at: aioquic.quic.connection.QuicConnection._handle_max_streams_bidi_frame self._remote_max_streams_bidi = max_streams at: aioquic.quic.connection.QuicReceiveContext quic_logger_frames: Optional[List[Any]] ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_data_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_DATA frame. This adjusts the total amount of we can send to the peer. """ max_data = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( + frame_type=frame_type, maximum=max_data + ) - self._quic_logger.encode_max_data_frame(maximum=max_data) ) if max_data > self._remote_max_data: self._logger.debug("Remote max_data raised to %d", max_data) self._remote_max_data = max_data ===========changed ref 1=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_data_frame(self, maximum: int) -> Dict: - return {"frame_type": "max_data", "maximum": str(maximum)} - ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - return { - "frame_type": "max_streams", - "maximum": str(maximum), - "stream_type": "unidirectional" - if frame_type == QuicFrameType.MAX_STREAMS_UNI - else "bidirectional", - } - ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_connection_limit_frame(self, frame_type: int, maximum: int) -> Dict: + if frame_type == QuicFrameType.MAX_DATA: + return {"frame_type": "max_data", "maximum": str(maximum)} + else: + return { + "frame_type": "max_streams", + "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", + } + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") ===========changed ref 5=========== # module: aioquic.quic.connection logger = logging.getLogger("quic") CRYPTO_BUFFER_SIZE = 16384 EPOCH_SHORTCUTS = { "I": tls.Epoch.INITIAL, "H": tls.Epoch.HANDSHAKE, "0": tls.Epoch.ZERO_RTT, "1": tls.Epoch.ONE_RTT, } MAX_EARLY_DATA = 0xFFFFFFFF 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", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any # frame sizes ACK_FRAME_CAPACITY = 64 # FIXME: this is arbitrary! APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 # + reason length + CONNECTION_LIMIT_FRAME_CAPACITY = 1 + 8 HANDSHAKE_DONE_FRAME_CAPACITY = 1 - MAX_DATA_FRAME_CAPACITY = 1 + 8 MAX_STREAM_DATA_FRAME_CAPACITY = 1 + 8 + 8 - MAX_STREAMS_FRAME_CAPACITY = 1 + 8 NEW_CONNECTION_ID_FRAME_CAPACITY = 1 + 8 + 8 + 1 + 20 + 16 PATH_CHALLENGE_FRAME_CAPACITY = 1 + 8 PATH_RESPONSE_FRAME_CAPACITY = 1 + 8 PING_FRAME_CAPACITY = 1 RESET_STREAM_CAPACITY = 1 + 8 + 8 + 8 RETIRE_CONNECTION_ID_CAPACITY = 1 + 8 STREAMS_BLOCKED_CAPACITY = 1 + 8 TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 + 8 # + reason length
aioquic.quic.connection/QuicConnection._handle_max_streams_uni_frame
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<10>:<add> self._quic_logger.encode_connection_limit_frame( <del> self._quic_logger.encode_max_streams_frame(
# module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a MAX_STREAMS_UNI frame. <2> <3> This raises number of unidirectional streams we can initiate to the peer. <4> """ <5> max_streams = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_max_streams_frame( <11> frame_type=frame_type, maximum=max_streams <12> ) <13> ) <14> <15> if max_streams > self._remote_max_streams_uni: <16> self._logger.debug("Remote max_streams_uni raised to %d", max_streams) <17> self._remote_max_streams_uni = max_streams <18> self._unblock_streams(is_unidirectional=True) <19>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _unblock_streams(is_unidirectional: bool) -> 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=self._original_destination_connection_id, ) self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_max_streams_bidi_frame max_streams = buf.pull_uint_var() at: aioquic.quic.connection.QuicConnection._handle_max_streams_uni_frame self._remote_max_streams_uni = max_streams at: aioquic.quic.connection.QuicReceiveContext quic_logger_frames: Optional[List[Any]] ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( - self._quic_logger.encode_max_streams_frame( frame_type=frame_type, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False) ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_data_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_DATA frame. This adjusts the total amount of we can send to the peer. """ max_data = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( + frame_type=frame_type, maximum=max_data + ) - self._quic_logger.encode_max_data_frame(maximum=max_data) ) if max_data > self._remote_max_data: self._logger.debug("Remote max_data raised to %d", max_data) self._remote_max_data = max_data ===========changed ref 2=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_data_frame(self, maximum: int) -> Dict: - return {"frame_type": "max_data", "maximum": str(maximum)} - ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - return { - "frame_type": "max_streams", - "maximum": str(maximum), - "stream_type": "unidirectional" - if frame_type == QuicFrameType.MAX_STREAMS_UNI - else "bidirectional", - } - ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_connection_limit_frame(self, frame_type: int, maximum: int) -> Dict: + if frame_type == QuicFrameType.MAX_DATA: + return {"frame_type": "max_data", "maximum": str(maximum)} + else: + return { + "frame_type": "max_streams", + "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", + } + ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") ===========changed ref 6=========== # module: aioquic.quic.connection logger = logging.getLogger("quic") CRYPTO_BUFFER_SIZE = 16384 EPOCH_SHORTCUTS = { "I": tls.Epoch.INITIAL, "H": tls.Epoch.HANDSHAKE, "0": tls.Epoch.ZERO_RTT, "1": tls.Epoch.ONE_RTT, } MAX_EARLY_DATA = 0xFFFFFFFF 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", ], ] STREAM_FLAGS = 0x07 NetworkAddress = Any # frame sizes ACK_FRAME_CAPACITY = 64 # FIXME: this is arbitrary! APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 # + reason length + CONNECTION_LIMIT_FRAME_CAPACITY = 1 + 8 HANDSHAKE_DONE_FRAME_CAPACITY = 1 - MAX_DATA_FRAME_CAPACITY = 1 + 8 MAX_STREAM_DATA_FRAME_CAPACITY = 1 + 8 + 8 - MAX_STREAMS_FRAME_CAPACITY = 1 + 8 NEW_CONNECTION_ID_FRAME_CAPACITY = 1 + 8 + 8 + 1 + 20 + 16 PATH_CHALLENGE_FRAME_CAPACITY = 1 + 8 PATH_RESPONSE_FRAME_CAPACITY = 1 + 8 PING_FRAME_CAPACITY = 1 RESET_STREAM_CAPACITY = 1 + 8 + 8 + 8 RETIRE_CONNECTION_ID_CAPACITY = 1 + 8 STREAMS_BLOCKED_CAPACITY = 1 + 8 TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 8 + 8 + 8 # + reason length
aioquic.quic.connection/QuicConnection._handle_stream_frame
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<40>:<add> if self._local_max_data.used + newly_received > self._local_max_data.value: <del> if self._local_max_data_used + newly_
# 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> if offset + length > UINT_VAR_MAX: <13> raise QuicConnectionError( <14> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <15> frame_type=frame_type, <16> reason_phrase="offset + length cannot exceed 2^62 - 1", <17> ) <18> frame = QuicStreamFrame( <19> offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1) <20> ) <21> <22> # log frame <23> if self._quic_logger is not None: <24> context.quic_logger_frames.append( <25> self._quic_logger.encode_stream_frame(frame, stream_id=stream_id) <26> ) <27> <28> # check stream direction <29> self._assert_stream_can_receive(frame_type, stream_id) <30> <31> # check flow-control limits <32> stream = self._get_or_create_stream(frame_type, stream_id) <33> if offset + length > stream.max_stream_data_local: <34> raise QuicConnectionError( <35> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <36> frame_type=frame_type, <37> reason_phrase="Over stream data limit", <38> ) <39> newly_received = max(0, offset + length - stream._recv_highest) <40> if self._local_max_data_used + newly_</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 raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over connection data limit", ) event = stream.add_frame(frame) 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.Limit.__init__ self.used = 0 self.value = value at: aioquic.quic.connection.QuicConnection _assert_stream_can_receive(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._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_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_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_UNI frame. This raises number of unidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( - self._quic_logger.encode_max_streams_frame( frame_type=frame_type, maximum=max_streams ) ) if max_streams > self._remote_max_streams_uni: self._logger.debug("Remote max_streams_uni raised to %d", max_streams) self._remote_max_streams_uni = max_streams self._unblock_streams(is_unidirectional=True) ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( - self._quic_logger.encode_max_streams_frame( frame_type=frame_type, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False) ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_data_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_DATA frame. This adjusts the total amount of we can send to the peer. """ max_data = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( + frame_type=frame_type, maximum=max_data + ) - self._quic_logger.encode_max_data_frame(maximum=max_data) ) if max_data > self._remote_max_data: self._logger.debug("Remote max_data raised to %d", max_data) self._remote_max_data = max_data ===========changed ref 3=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_data_frame(self, maximum: int) -> Dict: - return {"frame_type": "max_data", "maximum": str(maximum)} - ===========changed ref 4=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - return { - "frame_type": "max_streams", - "maximum": str(maximum), - "stream_type": "unidirectional" - if frame_type == QuicFrameType.MAX_STREAMS_UNI - else "bidirectional", - } - ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_connection_limit_frame(self, frame_type: int, maximum: int) -> Dict: + if frame_type == QuicFrameType.MAX_DATA: + return {"frame_type": "max_data", "maximum": str(maximum)} + else: + return { + "frame_type": "max_streams", + "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", + } + ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stream_frame_over_max_data(self): with client_and_server() as (client, server): # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value - client._local_max_data_used = client._local_max_data # client receives STREAM frame frame_type = QuicFrameType.STREAM_BASE | 4 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(1)), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) self.assertEqual(cm.exception.frame_type, frame_type) self.assertEqual(cm.exception.reason_phrase, "Over connection data limit")
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<4>:<add> initial_max_data=self._local_max_data.value, <del> initial_max_data=self._local_max_data,
# 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> max_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.value, <9> initial_max_streams_uni=self._local_max_streams_uni.value, <10> initial_source_connection_id=self._local_initial_source_connection_id, <11> max_ack_delay=25, <12> max_datagram_frame_size=self._configuration.max_datagram_frame_size, <13> quantum_readiness=b"Q" * 1200 <14> if self._configuration.quantum_readiness_test <15> else None, <16> ) <17> if not self._is_client: <18> quic_transport_parameters.original_destination_connection_id = ( <19> self._original_destination_connection_id <20> ) <21> quic_transport_parameters.retry_source_connection_id = ( <22> self._retry_source_connection_id <23> ) <24> <25> # log event <26> if self._quic_logger is not None: <27> self._quic_logger.log_event( <28> category="transport", <29> event="parameters_set", <30> data=self._quic_logger.</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionState() at: aioquic.quic.connection.Limit.__init__ self.value = value at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._local_initial_source_connection_id = self._host_cids[0].cid self._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._local_max_stream_data_bidi_local = configuration.max_stream_data self._local_max_stream_data_bidi_remote = configuration.max_stream_data self._local_max_stream_data_uni = configuration.max_stream_data self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._retry_source_connection_id = retry_source_connection_id self._state = QuicConnectionState.FIRSTFLIGHT self._original_destination_connection_id = self._peer_cid self._original_destination_connection_id = ( original_destination_connection_id ) ===========unchanged ref 1=========== self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_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, max_idle_timeout=int(self._configuration.idle_timeout * 1000), initial_max_data=self._local_max_data.value, 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.value, initial_max_streams_uni=self._local_max_streams_uni.value, initial_source_connection_id=self._local_initial_source_connection_id, max_ack_delay=25, max_datagram_frame_size=self._configuration.max_datagram_frame_size, quantum_readiness=b"Q" * 1200 if self._configuration.quantum_readiness_test else None, ) at: aioquic.quic.connection.QuicConnection.receive_datagram self._retry_source_connection_id = header.source_cid at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] ===========unchanged ref 2=========== 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 _on_max_streams_delivery( - self, delivery: QuicDeliveryState, max_streams: Limit - ) -> None: - """ - Callback when a MAX_STREAMS frame is acknowledged or lost. - """ - if delivery != QuicDeliveryState.ACKED: - max_streams.sent = 0 - ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: + def _on_connection_limit_delivery( + self, delivery: QuicDeliveryState, limit: Limit + ) -> None: + """ + Callback when a MAX_DATA or MAX_STREAMS frame is acknowledged or lost. + """ + if delivery != QuicDeliveryState.ACKED: + limit.sent = 0 + ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: - def _on_max_data_delivery(self, delivery: QuicDeliveryState) -> None: - """ - Callback when a MAX_DATA frame is acknowledged or lost. - """ - if delivery != QuicDeliveryState.ACKED: - self._local_max_data_sent = 0 - ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_uni_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_UNI frame. This raises number of unidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( - self._quic_logger.encode_max_streams_frame( frame_type=frame_type, maximum=max_streams ) ) if max_streams > self._remote_max_streams_uni: self._logger.debug("Remote max_streams_uni raised to %d", max_streams) self._remote_max_streams_uni = max_streams self._unblock_streams(is_unidirectional=True) ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _handle_max_streams_bidi_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a MAX_STREAMS_BIDI frame. This raises number of bidirectional streams we can initiate to the peer. """ max_streams = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( + self._quic_logger.encode_connection_limit_frame( - self._quic_logger.encode_max_streams_frame( frame_type=frame_type, maximum=max_streams ) ) if max_streams > self._remote_max_streams_bidi: self._logger.debug("Remote max_streams_bidi raised to %d", max_streams) self._remote_max_streams_bidi = max_streams self._unblock_streams(is_unidirectional=False)
aioquic.quic.connection/QuicConnection._write_connection_limits
Modified
aiortc~aioquic
d6b2ac69178dd77ae2acfb7de943336c452f197d
[connection] use same code for MAX_DATA and MAX_STREAMS
<3>:<add> for limit in ( <del> if self._local_max_data_used * 2 > self._local_max_data: <4>:<add> self._local_max_data, <del> self._local_max_data *= 2 <5>:<add> self._local_max_streams_bidi, <add> self._local_max_streams_uni, <add> ): <add> if limit.used * 2 > limit.value: <add> limit.value *= 2 <add> self._logger.debug("Local %s raised to %d", limit.name, limit.value) <add> if limit.value != limit.sent: <del> self._logger.debug("Local max_data raised to %d", self._local_max_data) <6>:<del> if self._local_max_data_sent != self._local_max_data: <7>:<add> buf = builder.start_frame( <del> buf = builder.start_frame( <8>:<add> limit.frame_type, <del> QuicFrameType.MAX_DATA, <9>:<add> capacity=CONNECTION_LIMIT_FRAME_CAPACITY, <del> capacity=MAX_DATA_FRAME_CAPACITY, <10>:<add> handler=self._on_connection_limit_delivery, <del> handler=self._on_max_data_delivery, <11>:<del> ) <12>:<del> buf.push_uint_var(self._local_max_data) <13>:<del> self._local_max_data_sent = self._local_max_data <14>:<del> <15>:<del> # log frame <16>:<del> if self._quic_logger is not None: <17>:<del> builder.quic_logger_frames.append( <18>:<del> self._quic_logger.encode_max_data_frame(self._local_max_data) <19>:<add> handler_args=(limit,), <20>:<del> <21>:<del> for max_streams in (self._local_max_streams_bidi, self._local_max_streams_uni): <22>:<del> if max_streams.used * 2 > max_streams.value: <23>:<del> max_streams.value *= 2 <24>:<del> self._logger.debug( <25>:<del> "Local %s raised to %d", max_streams.name, max_streams.value <26>:<del> ) <27>:<del> if max_streams.value != max_streams.sent: <28>:<del> buf = builder.start_frame( <29>:<del> max_streams.frame_type, <30>:<del> capacity=MAX_STREAMS_FRAME_CAPACITY, <31>:<del> handler=self._on_max_streams_delivery, <32>:<del> handler_args=(max_streams,), <33>:<del> ) <34>:<add> buf.push_uint_var(limit.value) <del> buf.push_uint_var(max
# module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: <0> """ <1> Raise MAX_DATA or MAX_STREAMS if needed. <2> """ <3> if self._local_max_data_used * 2 > self._local_max_data: <4> self._local_max_data *= 2 <5> self._logger.debug("Local max_data raised to %d", self._local_max_data) <6> if self._local_max_data_sent != self._local_max_data: <7> buf = builder.start_frame( <8> QuicFrameType.MAX_DATA, <9> capacity=MAX_DATA_FRAME_CAPACITY, <10> handler=self._on_max_data_delivery, <11> ) <12> buf.push_uint_var(self._local_max_data) <13> self._local_max_data_sent = self._local_max_data <14> <15> # log frame <16> if self._quic_logger is not None: <17> builder.quic_logger_frames.append( <18> self._quic_logger.encode_max_data_frame(self._local_max_data) <19> ) <20> <21> for max_streams in (self._local_max_streams_bidi, self._local_max_streams_uni): <22> if max_streams.used * 2 > max_streams.value: <23> max_streams.value *= 2 <24> self._logger.debug( <25> "Local %s raised to %d", max_streams.name, max_streams.value <26> ) <27> if max_streams.value != max_streams.sent: <28> buf = builder.start_frame( <29> max_streams.frame_type, <30> capacity=MAX_STREAMS_FRAME_CAPACITY, <31> handler=self._on_max_streams_delivery, <32> handler_args=(max_streams,), <33> ) <34> buf.push_uint_var(max</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _write_connection_limits( self, builder: QuicPacketBuilder, space: QuicPacketSpace ) -> None: # offset: 1 max_streams.sent = max_streams.value # log frame if self._quic_logger is not None: builder.quic_logger_frames.append( self._quic_logger.encode_max_streams_frame( frame_type=max_streams.frame_type, maximum=max_streams.value, ) ) ===========unchanged ref 0=========== at: aioquic.quic.connection CONNECTION_LIMIT_FRAME_CAPACITY = 1 + 8 at: aioquic.quic.connection.Limit.__init__ self.name = name self.sent = value self.used = 0 self.value = value at: aioquic.quic.connection.QuicConnection _on_connection_limit_delivery(delivery: QuicDeliveryState, limit: Limit) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None 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 _on_connection_limit_delivery( + self, delivery: QuicDeliveryState, limit: Limit + ) -> None: + """ + Callback when a MAX_DATA or MAX_STREAMS frame is acknowledged or lost. + """ + if delivery != QuicDeliveryState.ACKED: + limit.sent = 0 + ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: - def _on_max_streams_delivery( - self, delivery: QuicDeliveryState, max_streams: Limit - ) -> None: - """ - Callback when a MAX_STREAMS frame is acknowledged or lost. - """ - if delivery != QuicDeliveryState.ACKED: - max_streams.sent = 0 - ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: - def _on_max_data_delivery(self, delivery: QuicDeliveryState) -> None: - """ - Callback when a MAX_DATA frame is acknowledged or lost. - """ - if delivery != QuicDeliveryState.ACKED: - self._local_max_data_sent = 0 - ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: quic_transport_parameters = QuicTransportParameters( ack_delay_exponent=self._local_ack_delay_exponent, active_connection_id_limit=self._local_active_connection_id_limit, max_idle_timeout=int(self._configuration.idle_timeout * 1000), + initial_max_data=self._local_max_data.value, - 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.value, initial_max_streams_uni=self._local_max_streams_uni.value, initial_source_connection_id=self._local_initial_source_connection_id, max_ack_delay=25, max_datagram_frame_size=self._configuration.max_datagram_frame_size, quantum_readiness=b"Q" * 1200 if self._configuration.quantum_readiness_test else None, ) if not self._is_client: quic_transport_parameters.original_destination_connection_id = ( self._original_destination_connection_id ) quic_transport_parameters.retry_source_connection_id = ( self._retry_source_connection_id ) # log event if self._quic_logger is not None: self._quic_logger.log_event( category="transport", event="parameters_set", data=self._quic_logger.encode_transport_parameters( owner="local</s> ===========changed ref 4=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 <s> event="parameters_set", data=self._quic_logger.encode_transport_parameters( owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========changed ref 5=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_data_frame(self, maximum: int) -> Dict: - return {"frame_type": "max_data", "maximum": str(maximum)} - ===========changed ref 6=========== # module: aioquic.quic.logger class QuicLoggerTrace: - def encode_max_streams_frame(self, frame_type: int, maximum: int) -> Dict: - return { - "frame_type": "max_streams", - "maximum": str(maximum), - "stream_type": "unidirectional" - if frame_type == QuicFrameType.MAX_STREAMS_UNI - else "bidirectional", - } - ===========changed ref 7=========== # module: aioquic.quic.logger class QuicLoggerTrace: + def encode_connection_limit_frame(self, frame_type: int, maximum: int) -> Dict: + if frame_type == QuicFrameType.MAX_DATA: + return {"frame_type": "max_data", "maximum": str(maximum)} + else: + return { + "frame_type": "max_streams", + "maximum": str(maximum), + "stream_type": "unidirectional" + if frame_type == QuicFrameType.MAX_STREAMS_UNI + else "bidirectional", + } +
aioquic.quic.connection/QuicConnection._discard_epoch
Modified
aiortc~aioquic
943fb376961c8738d9de49090f289fdab55ed2ae
[connection] only discard a packet space once
<0>:<add> if not self._spaces[epoch].discarded: <add> self._logger.debug("Discarding epoch %s", epoch) <del> self._logger.debug("Discarding epoch %s", epoch) <1>:<add> self._cryptos[epoch].teardown() <del> self._cryptos[epoch].teardown() <2>:<add> self._loss.discard_space(self._spaces[epoch]) <del> self._loss.discard_space(self._spaces[epoch]) <3>:<add> self._spaces[epoch].discarded = True <del> self._spaces[epoch].discarded = True
# module: aioquic.quic.connection class QuicConnection: def _discard_epoch(self, epoch: tls.Epoch) -> None: <0> self._logger.debug("Discarding epoch %s", epoch) <1> self._cryptos[epoch].teardown() <2> self._loss.discard_space(self._spaces[epoch]) <3> self._spaces[epoch].discarded = True <4>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection.__init__ self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_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._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(), } 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.interop/test_rebinding
Modified
aiortc~aioquic
7dbebde35a433f0bc49c66a1f3e506ec77dd1a7e
[interop] check PATH_CHALLENGE is received for rebinding
<13>:<add> # check log <add> path_challenges = 0 <add> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <add> "traces" <add> ][0]["events"]: <add> if ( <add> category == "transport" <add> and event == "packet_received" <add> and data["packet_type"] == "1RTT" <add> ): <add> for frame in data["frames"]: <add> if frame["frame_type"] == "path_challenge": <add> path_challenges += 1 <add> if path_challenges: <add> server.result |= Result.B <del> server.result |= Result.B <14>:<add> else: <add> protocol._quic._logger.warning("No PATH_CHALLENGE received")
# module: examples.interop def test_rebinding(server: Server, configuration: QuicConfiguration): <0> async with connect( <1> server.host, server.port, configuration=configuration <2> ) as protocol: <3> # cause some traffic <4> await protocol.ping() <5> <6> # replace transport <7> protocol._transport.close() <8> await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0)) <9> <10> # cause more traffic <11> await protocol.ping() <12> <13> server.result |= Result.B <14>
===========unchanged ref 0=========== at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair 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) loop = asyncio.get_event_loop() 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
aioquic.quic.crypto/CryptoContext.__init__
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
<6>:<add> self._setup_cb = setup_cb <add> self._teardown_cb = teardown_cb
# module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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> self.version: Optional[int] = None <6>
===========unchanged ref 0=========== at: aioquic.quic.crypto.derive_key_iv_hp algorithm = cipher_suite_hash(cipher_suite) key_size = 32 key_size = 16 ===========changed ref 0=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass +
aioquic.quic.crypto/CryptoPair.__init__
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
<1>:<add> self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) <add> self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) <del> self.recv = CryptoContext() <2>:<del> self.send = CryptoContext()
# module: aioquic.quic.crypto class CryptoPair: + def __init__( + self, + recv_setup_cb: Callback = NoCallback, + recv_teardown_cb: Callback = NoCallback, + send_setup_cb: Callback = NoCallback, + send_teardown_cb: Callback = NoCallback, + ) -> None: - def __init__(self) -> None: <0> self.aead_tag_size = 16 <1> self.recv = CryptoContext() <2> self.send = CryptoContext() <3> self._update_key_requested = False <4>
===========unchanged ref 0=========== at: aioquic.quic.crypto.CryptoContext.__init__ self.aead: Optional[AEAD] = None self.key_phase = key_phase self.secret: Optional[bytes] = None at: aioquic.quic.crypto.CryptoContext.setup self.aead = AEAD(aead_cipher_name, key, iv) self.secret = secret at: aioquic.quic.crypto.CryptoContext.teardown self.aead = None self.secret = None ===========changed ref 0=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass + ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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 + self._setup_cb = setup_cb + self._teardown_cb = teardown_cb
aioquic.quic.crypto/CryptoPair.decrypt_packet
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
<4>:<add> self._update_key("remote_update") <del> self._update_key()
# module: aioquic.quic.crypto class CryptoPair: def decrypt_packet( self, packet: bytes, encrypted_offset: int, expected_packet_number: int ) -> Tuple[bytes, bytes, int]: <0> plain_header, payload, packet_number, update_key = self.recv.decrypt_packet( <1> packet, encrypted_offset, expected_packet_number <2> ) <3> if update_key: <4> self._update_key() <5> return plain_header, payload, packet_number <6>
===========unchanged ref 0=========== at: aioquic.quic.crypto CryptoContext(key_phase: int=0, setup_cb: Callback=NoCallback, teardown_cb: Callback=NoCallback) at: aioquic.quic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes, version: int) -> None at: aioquic.quic.crypto.CryptoContext.__init__ self.cipher_suite: Optional[CipherSuite] = None self.key_phase = key_phase at: aioquic.quic.crypto.CryptoContext.setup self.cipher_suite = cipher_suite at: aioquic.quic.crypto.CryptoContext.teardown self.cipher_suite = None ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoPair: + def __init__( + self, + recv_setup_cb: Callback = NoCallback, + recv_teardown_cb: Callback = NoCallback, + send_setup_cb: Callback = NoCallback, + send_teardown_cb: Callback = NoCallback, + ) -> None: - def __init__(self) -> None: self.aead_tag_size = 16 + self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) + self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) - self.recv = CryptoContext() - self.send = CryptoContext() self._update_key_requested = False ===========changed ref 1=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass + ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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 + self._setup_cb = setup_cb + self._teardown_cb = teardown_cb
aioquic.quic.crypto/CryptoPair.encrypt_packet
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
<1>:<add> self._update_key("local_update") <del> self._update_key()
# module: aioquic.quic.crypto class CryptoPair: def encrypt_packet( self, plain_header: bytes, plain_payload: bytes, packet_number: int ) -> bytes: <0> if self._update_key_requested: <1> self._update_key() <2> return self.send.encrypt_packet(plain_header, plain_payload, packet_number) <3>
===========unchanged ref 0=========== at: aioquic.quic.crypto.CryptoContext.__init__ self.version: Optional[int] = None at: aioquic.quic.crypto.CryptoContext.setup self.version = version at: aioquic.quic.crypto.next_key_phase crypto = CryptoContext(key_phase=int(not self.key_phase)) ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoPair: def decrypt_packet( self, packet: bytes, encrypted_offset: int, expected_packet_number: int ) -> Tuple[bytes, bytes, int]: plain_header, payload, packet_number, update_key = self.recv.decrypt_packet( packet, encrypted_offset, expected_packet_number ) if update_key: + self._update_key("remote_update") - self._update_key() return plain_header, payload, packet_number ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoPair: + def __init__( + self, + recv_setup_cb: Callback = NoCallback, + recv_teardown_cb: Callback = NoCallback, + send_setup_cb: Callback = NoCallback, + send_teardown_cb: Callback = NoCallback, + ) -> None: - def __init__(self) -> None: self.aead_tag_size = 16 + self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) + self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) - self.recv = CryptoContext() - self.send = CryptoContext() self._update_key_requested = False ===========changed ref 2=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass + ===========changed ref 3=========== # module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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 + self._setup_cb = setup_cb + self._teardown_cb = teardown_cb
aioquic.quic.crypto/CryptoPair._update_key
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
<0>:<add> apply_key_phase(self.recv, next_key_phase(self.recv), trigger=trigger) <del> apply_key_phase(self.recv, next_key_phase(self.recv)) <1>:<add> apply_key_phase(self.send, next_key_phase(self.send), trigger=trigger) <del> apply_key_phase(self.send, next_key_phase(self.send))
# module: aioquic.quic.crypto class CryptoPair: + def _update_key(self, trigger: str) -> None: - def _update_key(self) -> None: <0> apply_key_phase(self.recv, next_key_phase(self.recv)) <1> apply_key_phase(self.send, next_key_phase(self.send)) <2> self._update_key_requested = False <3>
===========unchanged ref 0=========== at: aioquic.quic.crypto INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 at: aioquic.quic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes, version: int) -> None at: aioquic.quic.crypto.CryptoPair.__init__ self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) at: aioquic.quic.crypto.CryptoPair.setup_initial recv_label, send_label = b"server in", b"client in" recv_label, send_label = b"client in", b"server in" algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) initial_secret = hkdf_extract(algorithm, INITIAL_SALT, cid) ===========changed ref 0=========== # module: aioquic.quic.crypto class CryptoPair: def encrypt_packet( self, plain_header: bytes, plain_payload: bytes, packet_number: int ) -> bytes: if self._update_key_requested: + self._update_key("local_update") - self._update_key() return self.send.encrypt_packet(plain_header, plain_payload, packet_number) ===========changed ref 1=========== # module: aioquic.quic.crypto class CryptoPair: def decrypt_packet( self, packet: bytes, encrypted_offset: int, expected_packet_number: int ) -> Tuple[bytes, bytes, int]: plain_header, payload, packet_number, update_key = self.recv.decrypt_packet( packet, encrypted_offset, expected_packet_number ) if update_key: + self._update_key("remote_update") - self._update_key() return plain_header, payload, packet_number ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoPair: + def __init__( + self, + recv_setup_cb: Callback = NoCallback, + recv_teardown_cb: Callback = NoCallback, + send_setup_cb: Callback = NoCallback, + send_teardown_cb: Callback = NoCallback, + ) -> None: - def __init__(self) -> None: self.aead_tag_size = 16 + self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) + self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) - self.recv = CryptoContext() - self.send = CryptoContext() self._update_key_requested = False ===========changed ref 3=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass + ===========changed ref 4=========== # module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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 + self._setup_cb = setup_cb + self._teardown_cb = teardown_cb
aioquic.quic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
39a211a40a9beacfc12cc0fa1f8d4e033c29ef4d
[qlog] log key_updated and key_retired
# module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context( <2> alpn_protocols=self._configuration.alpn_protocols, <3> cadata=self._configuration.cadata, <4> cafile=self._configuration.cafile, <5> capath=self._configuration.capath, <6> cipher_suites=self.configuration.cipher_suites, <7> is_client=self._is_client, <8> logger=self._logger, <9> max_early_data=None if self._is_client else MAX_EARLY_DATA, <10> server_name=self._configuration.server_name, <11> verify_mode=self._configuration.verify_mode, <12> ) <13> self.tls.certificate = self._configuration.certificate <14> self.tls.certificate_chain = self._configuration.certificate_chain <15> self.tls.certificate_private_key = self._configuration.private_key <16> self.tls.handshake_extensions = [ <17> ( <18> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <19> self._serialize_transport_parameters(), <20> ) <21> ] <22> <23> # TLS session resumption <24> session_ticket = self._configuration.session_ticket <25> if ( <26> self._is_client <27> and session_ticket is not None <28> and session_ticket.is_valid <29> and session_ticket.server_name == self._configuration.server_name <30> ): <31> self.tls.session_ticket = self._configuration.session_ticket <32> <33> # parse saved QUIC transport parameters - for 0-RTT <34> if session_ticket.max_early_data_size == MAX_EARLY_DATA: <35> for ext_type, ext_data in session_ticket.other_extensions: <36> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <37> self._parse_transport_parameters( <38> ext_data, from</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 ) break # TLS callbacks self.tls.alpn_cb = self._alpn_handler if self._session_ticket_fetcher is not None: self.tls.get_session_ticket_cb = self._session_ticket_fetcher if self._session_ticket_handler is not None: self.tls.new_session_ticket_cb = self._handle_session_ticket self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._crypto_buffers = { tls.Epoch.INITIAL: Buffer(capacity=CRYPTO_BUFFER_SIZE), tls.Epoch.HANDSHAKE: Buffer(capacity=CRYPTO_BUFFER_SIZE), tls.Epoch.ONE_RTT: Buffer(capacity=CRYPTO_BUFFER_SIZE), } 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(), } self._cryptos[tls.Epoch.INITIAL].setup_initial( cid=peer_cid, is_client=self._is_client, version=self._version ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic.quic.connection CRYPTO_BUFFER_SIZE = 16384 MAX_EARLY_DATA = 0xFFFFFFFF at: aioquic.quic.connection.QuicConnection _alpn_handler(alpn_protocol: str) -> None _handle_session_ticket(session_ticket: tls.SessionTicket) -> None _log_key_retired(key_type: str, trigger: str) -> None _log_key_updated(key_type: str, trigger: str) -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _serialize_transport_parameters() -> bytes _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._cryptos: Dict[tls.Epoch, CryptoPair] = {} self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() ===========changed ref 0=========== # module: aioquic.quic.crypto + def NoCallback(trigger: str) -> None: + pass + ===========changed ref 1=========== # module: aioquic.quic.crypto + Callback = Callable[[str], None] ===========changed ref 2=========== # module: aioquic.quic.crypto class CryptoPair: def encrypt_packet( self, plain_header: bytes, plain_payload: bytes, packet_number: int ) -> bytes: if self._update_key_requested: + self._update_key("local_update") - self._update_key() return self.send.encrypt_packet(plain_header, plain_payload, packet_number) ===========changed ref 3=========== # module: aioquic.quic.crypto class CryptoPair: def decrypt_packet( self, packet: bytes, encrypted_offset: int, expected_packet_number: int ) -> Tuple[bytes, bytes, int]: plain_header, payload, packet_number, update_key = self.recv.decrypt_packet( packet, encrypted_offset, expected_packet_number ) if update_key: + self._update_key("remote_update") - self._update_key() return plain_header, payload, packet_number ===========changed ref 4=========== # module: aioquic.quic.crypto class CryptoContext: + def __init__( + self, + key_phase: int = 0, + setup_cb: Callback = NoCallback, + teardown_cb: Callback = NoCallback, + ) -> None: - 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 + self._setup_cb = setup_cb + self._teardown_cb = teardown_cb ===========changed ref 5=========== # module: aioquic.quic.crypto class CryptoPair: + def __init__( + self, + recv_setup_cb: Callback = NoCallback, + recv_teardown_cb: Callback = NoCallback, + send_setup_cb: Callback = NoCallback, + send_teardown_cb: Callback = NoCallback, + ) -> None: - def __init__(self) -> None: self.aead_tag_size = 16 + self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) + self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) - self.recv = CryptoContext() - self.send = CryptoContext() self._update_key_requested = False ===========changed ref 6=========== # module: aioquic.quic.crypto class CryptoPair: + def _update_key(self, trigger: str) -> None: - def _update_key(self) -> None: + apply_key_phase(self.recv, next_key_phase(self.recv), trigger=trigger) - apply_key_phase(self.recv, next_key_phase(self.recv)) + apply_key_phase(self.send, next_key_phase(self.send), trigger=trigger) - apply_key_phase(self.send, next_key_phase(self.send)) self._update_key_requested = False
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
f99b692f2c9d4e0a8e207b1413ad1db1020bf7d8
[packet builder] pad long header packets for protection sample
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 1.0) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <26> now = 0.1 <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 1.1) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client only receives first datagram and sends ACKS <35> now = 0.2 <36> client.receive_datagram(items[0</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [97]) self.assertAlmostEqual(client.get_timer(), 0.625) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertIsNone(client.next_event()) # client PTO - HANDSHAKE PING now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [44]) self.assertAlmostEqual(client.get_timer(), 1.875) # server receives PING, discards INITIAL and sends ACK now = 0.725 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [48]) self.assertAlmostEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 874]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s>, 874]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertIsNone(server.next_event()) # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [329]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 1.925) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
aioquic.quic.packet_builder/QuicPacketBuilder._end_packet
Modified
aiortc~aioquic
f99b692f2c9d4e0a8e207b1413ad1db1020bf7d8
[packet builder] pad long header packets for protection sample
<6>:<add> # padding to ensure sufficient sample size <add> padding_size = ( <add> PACKET_NUMBER_MAX_SIZE <add> - PACKET_NUMBER_SEND_SIZE <add> + self._header_size <add> - packet_size <add> ) <add> <add> # padding for initial datagram <del> # pad initial datagram <11>:<add> and self.remaining_flight_space <add> and self.remaining_flight_space > padding_size <12>:<add> padding_size = self.remaining_flight_space <del> if self.remaining_flight_space: <13>:<del> buf.push_bytes(bytes(self.remaining_flight_space)) <14>:<del> packet_size = buf.tell() - self._packet_start <15>:<del> self._packet.in_flight = True <17>:<add> # write padding <add> if padding_size > 0: <add> buf.push_bytes(bytes(padding_size)) <add> packet_size += padding_size <add> self._packet.in_flight = True <add> <add> # log frame <del> # log frame <18>:<add> if self._quic_logger is not None: <del> if self._quic_logger is not None: <19>:<add> self._packet.quic_logger_frames.append( <del> self._packet.quic_logger_frames.append( <20>:<add> self._quic_logger.encode_padding_frame() <del> self._quic_logger.encode_padding_frame() <21>:<add> ) <del> )
# module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> None: <0> """ <1> Ends the current packet. <2> """ <3> buf = self._buffer <4> packet_size = buf.tell() - self._packet_start <5> if packet_size > self._header_size: <6> # pad initial datagram <7> if ( <8> self._is_client <9> and self._packet_type == PACKET_TYPE_INITIAL <10> and self._packet.is_crypto_packet <11> ): <12> if self.remaining_flight_space: <13> buf.push_bytes(bytes(self.remaining_flight_space)) <14> packet_size = buf.tell() - self._packet_start <15> self._packet.in_flight = True <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> <23> # write header <24> if self._packet_long_header: <25> length = ( <26> packet_size <27> - self._header_size <28> + PACKET_NUMBER_SEND_SIZE <29> + self._packet_crypto.aead_tag_size <30> ) <31> <32> buf.seek(self._packet_start) <33> buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) <34> buf.push_uint32(self._version) <35> buf.push_uint8(len(self._peer_cid)) <36> buf.push_bytes(self._peer_cid) <37> buf.push_uint8(len(self._host_cid)) <38> buf.push_bytes(self._host_cid) <39> if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <40> buf.push_uint_var(len(self._peer_token)) <41> buf.push</s>
===========below chunk 0=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> None: # 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 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.tell() - self._packet_start self._packets.append(self._packet) if self._packet.in_flight: self._datagram_flight_bytes += self._packet.</s> ===========below chunk 1=========== # module: aioquic.quic.packet_builder class QuicPacketBuilder: def _end_packet(self) -> None: # offset: 2 <s>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 ===========unchanged ref 0=========== at: aioquic.quic.packet_builder PACKET_NUMBER_SEND_SIZE = 2 at: aioquic.quic.packet_builder.QuicPacketBuilder.__init__ self.quic_logger_frames: Optional[List[Dict]] = None self._host_cid = host_cid self._is_client = is_client self._peer_cid = peer_cid self._peer_token = peer_token self._quic_logger = quic_logger self._spin_bit = spin_bit self._version = version self._datagrams: List[bytes] = [] self._datagram_flight_bytes = 0 self._packets: List[QuicSentPacket] = [] self._flight_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) 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._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: 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: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertEqual(client.get_timer(), 1.0) # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost now = 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 1050]) self.assertEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) # client only receives first datagram and sends ACKS now = 0.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(dat</s>
aioquic.quic.connection/QuicConnection._handle_crypto_frame
Modified
aiortc~aioquic
4073f1930dce8209b305c5462238075ca3163075
[recovery] use peer_completed_address_validation
# 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> if offset + length > UINT_VAR_MAX: <6> raise QuicConnectionError( <7> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <8> frame_type=frame_type, <9> reason_phrase="offset + length cannot exceed 2^62 - 1", <10> ) <11> frame = QuicStreamFrame(offset=offset, data=buf.pull_bytes(length)) <12> <13> # log frame <14> if self._quic_logger is not None: <15> context.quic_logger_frames.append( <16> self._quic_logger.encode_crypto_frame(frame) <17> ) <18> <19> stream = self._crypto_streams[context.epoch] <20> event = stream.add_frame(frame) <21> if event is not None: <22> # pass data to TLS layer <23> try: <24> self.tls.handle_message(event.data, self._crypto_buffers) <25> self._push_crypto_data() <26> except tls.Alert as exc: <27> raise QuicConnectionError( <28> error_code=QuicErrorCode.CRYPTO_ERROR + int(exc.description), <29> frame_type=frame_type, <30> reason_phrase=str(exc), <31> ) <32> <33> # parse transport parameters <34> if ( <35> not self._parameters_received <36> and self.tls.received_extensions is not None <37> ): <38> for ext_type, ext_data in self.tls.received_extensions: <39> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <40> self._parse_transport_parameters(ext_data) <41> self._parameters_received = True <42> </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 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 # for servers, the handshake is now confirmed if not self._is_client: self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True self._handshake_done_pending = 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 _discard_epoch(epoch: tls.Epoch) -> None _replenish_connection_ids() -> None _push_crypto_data() -> None _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None _unblock_streams(is_unidirectional: bool) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._is_client = configuration.is_client 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._handshake_confirmed = 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=self._original_destination_connection_id, ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) self._loss = QuicPacketRecovery( peer_completed_address_validation=not self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._handshake_done_pending = False ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_handshake_done_frame self._handshake_confirmed = True 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, cipher_suites=self.configuration.cipher_suites, 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=CRYPTO_BUFFER_SIZE), tls.Epoch.HANDSHAKE: Buffer(capacity=CRYPTO_BUFFER_SIZE), tls.Epoch.ONE_RTT: Buffer(capacity=CRYPTO_BUFFER_SIZE), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } at: aioquic.quic.connection.QuicConnection._on_handshake_done_delivery self._handshake_done_pending = True at: aioquic.quic.connection.QuicConnection._write_application self._handshake_done_pending = False at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float ===========unchanged ref 2=========== at: collections.deque append(x: _T) -> None at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] info(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 __init__( self, *, configuration: QuicConfiguration, original_destination_connection_id: Optional[bytes] = None, retry_source_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_destination_connection_id is None ), "Cannot set original_destination_connection_id for a client" assert ( retry_source_connection_id is None ), "Cannot set retry_source_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" assert ( original_destination_connection_id is not None ), "original_destination_connection_id is required for a server" # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} 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._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os</s>
tests.test_recovery/QuicPacketRecoveryTest.setUp
Modified
aiortc~aioquic
4073f1930dce8209b305c5462238075ca3163075
[recovery] use peer_completed_address_validation
<5>:<add> peer_completed_address_validation=True, send_probe=send_probe <del> is_client_without_1rtt=False, send_probe=send_probe
# module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def setUp(self): <0> self.INITIAL_SPACE = QuicPacketSpace() <1> self.HANDSHAKE_SPACE = QuicPacketSpace() <2> self.ONE_RTT_SPACE = QuicPacketSpace() <3> <4> self.recovery = QuicPacketRecovery( <5> is_client_without_1rtt=False, send_probe=send_probe <6> ) <7> self.recovery.spaces = [ <8> self.INITIAL_SPACE, <9> self.HANDSHAKE_SPACE, <10> self.ONE_RTT_SPACE, <11> ] <12>
===========unchanged ref 0=========== at: tests.test_recovery send_probe() at: unittest.case.TestCase failureException = AssertionError longMessage = True maxDiff = 80*8 _diffThreshold = 2**16 setUp(self) -> None failUnlessEqual = assertEquals = _deprecate(assertEqual) failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) assertNotRegexpMatches = _deprecate(assertNotRegex) ===========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, 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 transport parameters received" # update current epoch if not self._handshake_complete and</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> ), "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 # for servers, the handshake is now confirmed if not self._is_client: self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True self._handshake_done_pending = True + self._loss.peer_completed_address_validation = 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.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_destination_connection_id: Optional[bytes] = None, retry_source_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_destination_connection_id is None ), "Cannot set original_destination_connection_id for a client" assert ( retry_source_connection_id is None ), "Cannot set retry_source_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" assert ( original_destination_connection_id is not None ), "original_destination_connection_id is required for a server" # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} 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._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os</s>
aioquic.quic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
4073f1930dce8209b305c5462238075ca3163075
[recovery] use peer_completed_address_validation
<0>:<del> self.is_client_without_1rtt = is_client_without_1rtt <2>:<add> self.peer_completed_address_validation = peer_completed_address_validation
# module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, + peer_completed_address_validation: bool, - 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._cc = QuicCongestionControl() <19> self._pacer = QuicPacketPacer() <20>
===========unchanged ref 0=========== at: aioquic.quic.recovery QuicPacketSpace() QuicPacketPacer() QuicCongestionControl() 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_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time at: math inf: float at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def setUp(self): self.INITIAL_SPACE = QuicPacketSpace() self.HANDSHAKE_SPACE = QuicPacketSpace() self.ONE_RTT_SPACE = QuicPacketSpace() self.recovery = QuicPacketRecovery( + peer_completed_address_validation=True, send_probe=send_probe - is_client_without_1rtt=False, send_probe=send_probe ) self.recovery.spaces = [ self.INITIAL_SPACE, self.HANDSHAKE_SPACE, self.ONE_RTT_SPACE, ] ===========changed ref 1=========== # 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, 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 transport parameters received" # update current epoch if not self._handshake_complete and</s> ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s> ), "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 # for servers, the handshake is now confirmed if not self._is_client: self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True self._handshake_done_pending = True + self._loss.peer_completed_address_validation = 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 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_destination_connection_id: Optional[bytes] = None, retry_source_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_destination_connection_id is None ), "Cannot set original_destination_connection_id for a client" assert ( retry_source_connection_id is None ), "Cannot set retry_source_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" assert ( original_destination_connection_id is not None ), "original_destination_connection_id is required for a server" # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} 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._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os</s>
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
4073f1930dce8209b305c5462238075ca3163075
[recovery] use peer_completed_address_validation
<7>:<add> not self.peer_completed_address_validation <del> self.is_client_without_1rtt
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_loss_detection_time(self) -> float: <0> # loss timer <1> loss_space = self.get_earliest_loss_space() <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 = self.get_probe_timeout() * (2 ** self._pto_count) <14> return self._time_of_last_sent_ack_eliciting_packet + timeout <15> <16> return None <17>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_INITIAL_RTT = 0.5 # seconds at: aioquic.quic.recovery.QuicPacketRecovery get_earliest_loss_space() -> Optional[QuicPacketSpace] get_probe_timeout() -> float at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._time_of_last_sent_ack_eliciting_packet = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True 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 __init__( self, + peer_completed_address_validation: bool, - 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.peer_completed_address_validation = peer_completed_address_validation 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._cc = QuicCongestionControl() self._pacer = QuicPacketPacer() ===========changed ref 1=========== # module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def setUp(self): self.INITIAL_SPACE = QuicPacketSpace() self.HANDSHAKE_SPACE = QuicPacketSpace() self.ONE_RTT_SPACE = QuicPacketSpace() self.recovery = QuicPacketRecovery( + peer_completed_address_validation=True, send_probe=send_probe - is_client_without_1rtt=False, send_probe=send_probe ) self.recovery.spaces = [ self.INITIAL_SPACE, self.HANDSHAKE_SPACE, self.ONE_RTT_SPACE, ] ===========changed ref 2=========== # 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, 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 transport parameters received" # update current epoch if not self._handshake_complete and</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _handle_crypto_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s> ), "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 # for servers, the handshake is now confirmed if not self._is_client: self._discard_epoch(tls.Epoch.HANDSHAKE) self._handshake_confirmed = True self._handshake_done_pending = True + self._loss.peer_completed_address_validation = 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 )
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
7637750166d9296b857367c3d0462052ad136324
[recovery] rename get_earliest_loss_space to get_loss_space
<1>:<add> loss_space = self.get_loss_space() <del> loss_space = self.get_earliest_loss_space()
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_loss_detection_time(self) -> float: <0> # loss timer <1> loss_space = self.get_earliest_loss_space() <2> if loss_space is not None: <3> return loss_space.loss_time <4> <5> # packet timer <6> if ( <7> not self.peer_completed_address_validation <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 = self.get_probe_timeout() * (2 ** self._pto_count) <14> return self._time_of_last_sent_ack_eliciting_packet + timeout <15> <16> return None <17>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_INITIAL_RTT = 0.5 # seconds QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery get_probe_timeout() -> float at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._time_of_last_sent_ack_eliciting_packet = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True 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_space(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
7637750166d9296b857367c3d0462052ad136324
[recovery] rename get_earliest_loss_space to get_loss_space
<0>:<add> loss_space = self.get_loss_space() <del> loss_space = self.get_earliest_loss_space()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: <0> loss_space = self.get_earliest_loss_space() <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> self._on_packets_lost( <9> tuple( <10> filter( <11> lambda i: i.is_crypto_packet, space.sent_packets.values() <12> ) <13> ), <14> space=space, <15> now=now, <16> ) <17> <18> self._send_probe() <19>
===========unchanged ref 0=========== at: aioquic.quic.recovery.QuicPacketRecovery get_loss_space() -> Optional[QuicPacketSpace] get_loss_space(self) -> Optional[QuicPacketSpace] _detect_loss(space: QuicPacketSpace, now: float) -> None _on_packets_lost(packets: Iterable[QuicSentPacket], space: QuicPacketSpace, now: float) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] self._send_probe = send_probe self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: + def get_loss_space(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_space(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_loss_space() - loss_space = self.get_earliest_loss_space() if loss_space is not None: return loss_space.loss_time # packet timer if ( not self.peer_completed_address_validation 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.get_probe_timeout() * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
examples.interop/test_throughput
Modified
aiortc~aioquic
cc8782fab3ee36194c4ff5d88021f4557223dfdd
[interop] update servers
<1>:<add> if not server.throughput: <add> return
# 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%s" % (size, server.throughput_file_suffix) <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") </s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 if failures == 0: server.result |= Result.T ===========unchanged ref 0=========== 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: bool=True, 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: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: http3_client HttpClient(*args, **kwargs) 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 ===========unchanged ref 1=========== 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: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), + Server("f5", "f5quic.com", retry_port=4433, throughput=False), - Server("f5", "f5quic.com", retry_port=4433), + Server("haskell", "mew.org", structured_logging=True), - Server("haskell", "mew.org"), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", port=443, structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", structured_logging=True ), Server("ngtcp2", "nghttp2.org", push_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("quic-go", "interop.seemann.io", port</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s>gert.org", http3=False), + Server("quic-go", "interop.seemann.io", port=443, retry_port=443), - Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
examples.interop/run
Modified
aiortc~aioquic
cc8782fab3ee36194c4ff5d88021f4557223dfdd
[interop] update servers
<8>:<add> quic_logger=QuicDirectoryLogger(quic_log) if quic_log else QuicLogger(), <del> quic_logger=QuicLogger(), <23>:<del> if quic_log: <24>:<del> with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: <25>:<del> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) <26>:<del>
# module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: <0> for server in servers: <1> if server.structured_logging: <2> server.result |= Result.L <3> for test_name, test_func in tests: <4> print("\n=== %s %s ===\n" % (server.name, test_name)) <5> configuration = QuicConfiguration( <6> alpn_protocols=H3_ALPN + H0_ALPN, <7> is_client=True, <8> quic_logger=QuicLogger(), <9> secrets_log_file=secrets_log_file, <10> verify_mode=server.verify_mode, <11> ) <12> if test_name == "test_throughput": <13> timeout = 60 <14> else: <15> timeout = 10 <16> try: <17> await asyncio.wait_for( <18> test_func(server, configuration), timeout=timeout <19> ) <20> except Exception as exc: <21> print(exc) <22> <23> if quic_log: <24> with open("%s-%s.qlog" % (server.name, test_name), "w") as logger_fp: <25> json.dump(configuration.quic_logger.to_dict(), logger_fp, indent=4) <26> <27> print("") <28> print_result(server) <29> <30> # print summary <31> if len(servers) > 1: <32> print("SUMMARY") <33> for server in servers: <34> print_result(server) <35>
===========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 result: Result = field(default_factory=lambda: Result(0)) structured_logging: bool = False verify_mode: Optional[int] = None at: quic_logger QuicDirectoryLogger(path: str) ===========changed ref 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): failures = 0 + if not server.throughput: + return for size in [5000000, 10000000]: print("Testing %d bytes download" % size) path = "/%d%s" % (size, server.throughput_file_suffix) # perform HTTP request over TCP start = time.time() response = requests.get("https://" + server.host + path, verify=False) tcp_octets = len(response.content) tcp_elapsed = time.time() - start assert tcp_octets == size, "HTTP/TCP response size mismatch" # perform HTTP request over QUIC if server.http3: configuration.alpn_protocols = H3_ALPN else: configuration.alpn_protocols = H0_ALPN start = time.time() async with connect( server.host, server.port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) http_events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, path) ) quic_elapsed = time.time() - start quic_octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): quic_octets += len(http_event.data) assert quic_octets == size, "HTTP/QUIC response size mismatch" print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) if quic_elapsed > 1.1 * tcp_elapsed: failures += 1 print(" => FAIL") else: print(" => PASS") if failures == 0: server.result |= Result.T ===========changed ref 1=========== # 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: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 2=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), + Server("f5", "f5quic.com", retry_port=4433, throughput=False), - Server("f5", "f5quic.com", retry_port=4433), + Server("haskell", "mew.org", structured_logging=True), - Server("haskell", "mew.org"), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", port=443, structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", structured_logging=True ), Server("ngtcp2", "nghttp2.org", push_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("quic-go", "interop.seemann.io", port</s> ===========changed ref 3=========== # module: examples.interop # offset: 1 <s>gert.org", http3=False), + Server("quic-go", "interop.seemann.io", port=443, retry_port=443), - Server("quic-go", "quic.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
aioquic.tls/Context._build_session_ticket
Modified
aiortc~aioquic
6a781bdd36887283c88de919e726112381f1ce31
[tls] for clients, store *received* extensions
<17>:<add> other_extensions=other_extensions, <del> other_extensions=self.handshake_extensions,
# module: aioquic.tls class Context: def _build_session_ticket( + self, new_session_ticket: NewSessionTicket, other_extensions: List[Extension] - self, new_session_ticket: NewSessionTicket ) -> SessionTicket: <0> resumption_master_secret = self.key_schedule.derive_secret(b"res master") <1> resumption_secret = hkdf_expand_label( <2> algorithm=self.key_schedule.algorithm, <3> secret=resumption_master_secret, <4> label=b"resumption", <5> hash_value=new_session_ticket.ticket_nonce, <6> length=self.key_schedule.algorithm.digest_size, <7> ) <8> <9> timestamp = utcnow() <10> return SessionTicket( <11> age_add=new_session_ticket.ticket_age_add, <12> cipher_suite=self.key_schedule.cipher_suite, <13> max_early_data_size=new_session_ticket.max_early_data_size, <14> not_valid_after=timestamp <15> + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), <16> not_valid_before=timestamp, <17> other_extensions=self.handshake_extensions, <18> resumption_secret=resumption_secret, <19> server_name=self._server_name, <20> ticket=new_session_ticket.ticket, <21> ) <22>
===========unchanged ref 0=========== at: aioquic.tls utcnow = datetime.datetime.utcnow hkdf_expand_label(algorithm: hashes.HashAlgorithm, secret: bytes, label: bytes, hash_value: bytes, length: int) -> bytes Extension = Tuple[int, bytes] NewSessionTicket(ticket_lifetime: int=0, ticket_age_add: int=0, ticket_nonce: bytes=b"", ticket: bytes=b"", max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) SessionTicket(age_add: int, cipher_suite: CipherSuite, not_valid_after: datetime.datetime, not_valid_before: datetime.datetime, resumption_secret: bytes, server_name: str, ticket: bytes, max_early_data_size: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.Context.__init__ self._server_name = server_name self.key_schedule: Optional[KeySchedule] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(cipher_suite) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.KeySchedule derive_secret(label: bytes) -> bytes at: aioquic.tls.KeySchedule.__init__ self.algorithm = cipher_suite_hash(cipher_suite) self.cipher_suite = cipher_suite at: aioquic.tls.NewSessionTicket ticket_lifetime: int = 0 ticket_age_add: int = 0 ticket_nonce: bytes = b"" ticket: bytes = b"" max_early_data_size: Optional[int] = None ===========unchanged ref 1=========== other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: aioquic.tls.SessionTicket age_add: int cipher_suite: CipherSuite not_valid_after: datetime.datetime not_valid_before: datetime.datetime resumption_secret: bytes server_name: str ticket: bytes max_early_data_size: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: typing List = _alias(list, 1, inst=False, name='List')
aioquic.tls/Context._client_handle_new_session_ticket
Modified
aiortc~aioquic
6a781bdd36887283c88de919e726112381f1ce31
[tls] for clients, store *received* extensions
<4>:<add> ticket = self._build_session_ticket( <del> ticket = self._build_session_ticket(new_session_ticket) <5>:<add> new_session_ticket, self.received_extensions <add> )
# module: aioquic.tls class Context: def _client_handle_new_session_ticket(self, input_buf: Buffer) -> None: <0> new_session_ticket = pull_new_session_ticket(input_buf) <1> <2> # notify application <3> if self.new_session_ticket_cb is not None: <4> ticket = self._build_session_ticket(new_session_ticket) <5> self.new_session_ticket_cb(ticket) <6>
===========unchanged ref 0=========== at: aioquic.tls pull_new_session_ticket(buf: Buffer) -> NewSessionTicket at: aioquic.tls.Context _build_session_ticket(self, new_session_ticket: NewSessionTicket, other_extensions: List[Extension]) -> SessionTicket _build_session_ticket(new_session_ticket: NewSessionTicket, other_extensions: List[Extension]) -> SessionTicket at: aioquic.tls.Context.__init__ self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.received_extensions: Optional[List[Extension]] = None at: aioquic.tls.Context._client_handle_encrypted_extensions self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._server_handle_hello self.received_extensions = peer_hello.other_extensions ===========changed ref 0=========== # module: aioquic.tls class Context: def _build_session_ticket( + self, new_session_ticket: NewSessionTicket, other_extensions: List[Extension] - self, new_session_ticket: NewSessionTicket ) -> SessionTicket: resumption_master_secret = self.key_schedule.derive_secret(b"res master") resumption_secret = hkdf_expand_label( algorithm=self.key_schedule.algorithm, secret=resumption_master_secret, label=b"resumption", hash_value=new_session_ticket.ticket_nonce, length=self.key_schedule.algorithm.digest_size, ) timestamp = utcnow() return SessionTicket( age_add=new_session_ticket.ticket_age_add, cipher_suite=self.key_schedule.cipher_suite, max_early_data_size=new_session_ticket.max_early_data_size, not_valid_after=timestamp + datetime.timedelta(seconds=new_session_ticket.ticket_lifetime), not_valid_before=timestamp, + other_extensions=other_extensions, - other_extensions=self.handshake_extensions, resumption_secret=resumption_secret, server_name=self._server_name, ticket=new_session_ticket.ticket, )
aioquic.quic.crypto/CryptoPair.setup_initial
Modified
aiortc~aioquic
22282cf0e3cd30583e57b342db7e096883a53ce1
[crypto] update salt and test vectors for draft-29
<5>:<add> if version < QuicProtocolVersion.DRAFT_29: <add> initial_salt = INITIAL_SALT_DRAFT_23 <add> else: <add> initial_salt = INITIAL_SALT_DRAFT_29 <add> <6>:<add> initial_secret = hkdf_extract(algorithm, initial_salt, 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> algorithm = cipher_suite_hash(INITIAL_CIPHER_SUITE) <6> initial_secret = hkdf_extract(algorithm, INITIAL_SALT, cid) <7> self.recv.setup( <8> cipher_suite=INITIAL_CIPHER_SUITE, <9> secret=hkdf_expand_label( <10> algorithm, initial_secret, recv_label, b"", algorithm.digest_size <11> ), <12> version=version, <13> ) <14> self.send.setup( <15> cipher_suite=INITIAL_CIPHER_SUITE, <16> secret=hkdf_expand_label( <17> algorithm, initial_secret, send_label, b"", algorithm.digest_size <18> ), <19> version=version, <20> ) <21>
===========unchanged ref 0=========== at: aioquic.quic.crypto INITIAL_CIPHER_SUITE = CipherSuite.AES_128_GCM_SHA256 INITIAL_SALT_DRAFT_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") INITIAL_SALT_DRAFT_29 = binascii.unhexlify("afbfec289993d24c9e9786f19c6111e04390a899") at: aioquic.quic.crypto.CryptoContext setup(cipher_suite: CipherSuite, secret: bytes, version: int) -> None at: aioquic.quic.crypto.CryptoPair.__init__ self.recv = CryptoContext(setup_cb=recv_setup_cb, teardown_cb=recv_teardown_cb) self.send = CryptoContext(setup_cb=send_setup_cb, teardown_cb=send_teardown_cb) ===========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_23 = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") - INITIAL_SALT = binascii.unhexlify("c3eef712c72ebb5a11a7d2432bb46365bef9f502") + INITIAL_SALT_DRAFT_29 = binascii.unhexlify("afbfec289993d24c9e9786f19c6111e04390a899") SAMPLE_SIZE = 16 Callback = Callable[[str], None]
examples.interop/test_throughput
Modified
aiortc~aioquic
89ecff5c6693d541ca5b182d03fbc07c4f0af8c9
[interop] use httpx instead of requests
<10>:<add> response = httpx.get("https://" + server.host + path, verify=False) <del> response = requests.get("https://" + server.host + path, verify=False)
# module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): <0> failures = 0 <1> if not server.throughput: <2> return <3> <4> for size in [5000000, 10000000]: <5> print("Testing %d bytes download" % size) <6> path = "/%d%s" % (size, server.throughput_file_suffix) <7> <8> # perform HTTP request over TCP <9> start = time.time() <10> response = requests.get("https://" + server.host + path, verify=False) <11> tcp_octets = len(response.content) <12> tcp_elapsed = time.time() - start <13> assert tcp_octets == size, "HTTP/TCP response size mismatch" <14> <15> # perform HTTP request over QUIC <16> if server.http3: <17> configuration.alpn_protocols = H3_ALPN <18> else: <19> configuration.alpn_protocols = H0_ALPN <20> start = time.time() <21> async with connect( <22> server.host, <23> server.port, <24> configuration=configuration, <25> create_protocol=HttpClient, <26> ) as protocol: <27> protocol = cast(HttpClient, protocol) <28> <29> http_events = await protocol.get( <30> "https://{}:{}{}".format(server.host, server.port, path) <31> ) <32> quic_elapsed = time.time() - start <33> quic_octets = 0 <34> for http_event in http_events: <35> if isinstance(http_event, DataReceived): <36> quic_octets += len(http_event.data) <37> assert quic_octets == size, "HTTP/QUIC response size mismatch" <38> <39> print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) <40> print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) <41> <42> if quic_elapsed > 1.1 * tcp_elapsed: <43> failures += 1 <44> print(" => FAIL")</s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 print(" => PASS") if failures == 0: server.result |= Result.T ===========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 = "/" push_path: Optional[str] = None result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None structured_logging: bool = False throughput: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None at: http3_client HttpClient(*args, **kwargs) at: httpx._api get(url: URL | str, *, params: QueryParamTypes | None=None, headers: HeaderTypes | None=None, cookies: CookieTypes | None=None, auth: AuthTypes | None=None, proxy: ProxyTypes | None=None, proxies: ProxiesTypes | None=None, follow_redirects: bool=False, cert: CertTypes | None=None, verify: VerifyTypes=True, timeout: TimeoutTypes=DEFAULT_TIMEOUT_CONFIG, trust_env: bool=True) -> Response 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
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
2128e45659cf8626b5c97b6caca1184411e56ff9
[recovery] mark _get_loss_space as "private"
<1>:<add> loss_space = self._get_loss_space() <del> loss_space = self.get_loss_space()
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_loss_detection_time(self) -> float: <0> # loss timer <1> loss_space = self.get_loss_space() <2> if loss_space is not None: <3> return loss_space.loss_time <4> <5> # packet timer <6> if ( <7> not self.peer_completed_address_validation <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 = self.get_probe_timeout() * (2 ** self._pto_count) <14> return self._time_of_last_sent_ack_eliciting_packet + timeout <15> <16> return None <17>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_INITIAL_RTT = 0.5 # seconds at: aioquic.quic.recovery.QuicPacketRecovery get_probe_timeout() -> float _get_loss_space() -> Optional[QuicPacketSpace] at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._time_of_last_sent_ack_eliciting_packet = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True 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
aioquic.quic.recovery/QuicPacketRecovery.on_loss_detection_timeout
Modified
aiortc~aioquic
2128e45659cf8626b5c97b6caca1184411e56ff9
[recovery] mark _get_loss_space as "private"
<0>:<add> loss_space = self._get_loss_space() <del> loss_space = self.get_loss_space()
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_loss_detection_timeout(self, now: float) -> None: <0> loss_space = self.get_loss_space() <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> self._on_packets_lost( <9> tuple( <10> filter( <11> lambda i: i.is_crypto_packet, space.sent_packets.values() <12> ) <13> ), <14> space=space, <15> now=now, <16> ) <17> <18> self._send_probe() <19>
===========unchanged ref 0=========== at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery _on_packets_lost(packets: Iterable[QuicSentPacket], space: QuicPacketSpace, now: float) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._send_probe = send_probe self._time_of_last_sent_ack_eliciting_packet = 0.0 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 get_loss_space(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_loss_detection_time(self) -> float: # loss timer + loss_space = self._get_loss_space() - loss_space = self.get_loss_space() if loss_space is not None: return loss_space.loss_time # packet timer if ( not self.peer_completed_address_validation 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.get_probe_timeout() * (2 ** self._pto_count) return self._time_of_last_sent_ack_eliciting_packet + timeout return None
aioquic.quic.recovery/QuicPacketRecovery.get_loss_detection_time
Modified
aiortc~aioquic
91e0f051ddbeba8e59ad047f154e3f5bf25993f4
[recovery] rework PTO calculation
<10>:<del> if not self._rtt_initialized: <11>:<del> timeout = 2 * K_INITIAL_RTT * (2 ** self._pto_count) <12>:<del> else: <13>:<add> timeout = self.get_probe_timeout() * (2 ** self._pto_count) <del> 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_loss_space() <2> if loss_space is not None: <3> return loss_space.loss_time <4> <5> # packet timer <6> if ( <7> not self.peer_completed_address_validation <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 = self.get_probe_timeout() * (2 ** self._pto_count) <14> return self._time_of_last_sent_ack_eliciting_packet + timeout <15> <16> return None <17>
===========unchanged ref 0=========== at: aioquic.quic.recovery.QuicPacketRecovery _get_loss_space() -> Optional[QuicPacketSpace] at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._rtt_initialized = False self._time_of_last_sent_ack_eliciting_packet = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_initialized = True 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
aioquic.quic.recovery/QuicPacketRecovery.get_probe_timeout
Modified
aiortc~aioquic
91e0f051ddbeba8e59ad047f154e3f5bf25993f4
[recovery] rework PTO calculation
<0>:<add> if not self._rtt_initialized: <add> return 2 * K_INITIAL_RTT
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_probe_timeout(self) -> float: <0> return ( <1> self._rtt_smoothed <2> + max(4 * self._rtt_variance, K_GRANULARITY) <3> + self.max_ack_delay <4> ) <5>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_GRANULARITY = 0.001 # seconds at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received 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 get_loss_detection_time(self) -> float: # loss timer loss_space = self._get_loss_space() if loss_space is not None: return loss_space.loss_time # packet timer if ( not self.peer_completed_address_validation 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.get_probe_timeout() * (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
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
9d8fe935af355020313a81873ce506980fbf2908
[recovery] lower initial RTT to 250ms
<27>:<add> self.assertEqual(client.get_timer(), 0.5) <del> self.assertEqual(client.get_timer(), 1.0) <30>:<add> now = client.get_timer() <del> now = 1.0 <34>:<add> self.assertEqual(client.get_timer(), 1.5) <del> self.assertEqual(client.get_timer(), 3.0) <37>:<add> now += 0.1 <del> now = 1.1
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): <0> """ <1> Check connection is established even in the client's INITIAL is lost. <2> """ <3> <4> def datagram_sizes(items): <5> return [len(x[0]) for x in items] <6> <7> client_configuration = QuicConfiguration(is_client=True) <8> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <9> <10> client = QuicConnection(configuration=client_configuration) <11> client._ack_delay = 0 <12> <13> server_configuration = QuicConfiguration(is_client=False) <14> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <15> <16> server = QuicConnection( <17> configuration=server_configuration, <18> original_destination_connection_id=client.original_destination_connection_id, <19> ) <20> server._ack_delay = 0 <21> <22> # client sends INITIAL <23> now = 0.0 <24> client.connect(SERVER_ADDR, now=now) <25> items = client.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280]) <27> self.assertEqual(client.get_timer(), 1.0) <28> <29> # INITIAL is lost <30> now = 1.0 <31> client.handle_timer(now=now) <32> items = client.datagrams_to_send(now=now) <33> self.assertEqual(datagram_sizes(items), [1280]) <34> self.assertEqual(client.get_timer(), 3.0) <35> <36> # server receives INITIAL, sends INITIAL + HANDSHAKE <37> now = 1.1 <38> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <39> items = server.datagrams_to_send(now=now) <40> self.assertEqual(datagram_sizes(items), [1280,</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 self.assertEqual(server.get_timer(), 2.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 1.825) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now = 1.4 client.receive_dat</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>(server.next_event()), events.ConnectionIdIssued) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
9d8fe935af355020313a81873ce506980fbf2908
[recovery] lower initial RTT to 250ms
<23>:<add> self.assertEqual(client.get_timer(), 0.5) <del> self.assertEqual(client.get_timer(), 1.0) <26>:<add> now += 0.1 <del> now = 0.1 <30>:<add> self.assertEqual(server.get_timer(), 0.6) <del> self.assertEqual(server.get_timer(), 1.1) <35>:<add> now += 0.1 <del> now = 0.2
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 1.0) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <26> now = 0.1 <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 1.1) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client only receives first datagram and sends ACKS <35> now = 0.2 <36> client.receive_datagram(items[0</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [97]) self.assertAlmostEqual(client.get_timer(), 0.625) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertIsNone(client.next_event()) # client PTO - HANDSHAKE PING now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [45]) self.assertAlmostEqual(client.get_timer(), 1.875) # server receives PING, discards INITIAL and sends ACK now = 0.725 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [48]) self.assertAlmostEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 874]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s>, 874]) self.assertAlmostEqual(server.get_timer(), 3.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertIsNone(server.next_event()) # handshake continues normally now = 1.2 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [329]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 1.925) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now = 1.4 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.5) - self.assertEqual(client.get_timer(), 1.0) # INITIAL is lost + now = client.get_timer() - now = 1.0 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 1.5) - self.assertEqual(client.get_timer(), 3.0) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += 0.1 - now = 1.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now)</s>
tests.test_connection/QuicConnectionTest.test_connect_with_loss_3
Modified
aiortc~aioquic
9d8fe935af355020313a81873ce506980fbf2908
[recovery] lower initial RTT to 250ms
<23>:<add> self.assertEqual(client.get_timer(), 0.5) <del> self.assertEqual(client.get_timer(), 1.0) <26>:<add> now += 0.1 <del> now = 0.1 <30>:<add> self.assertEqual(server.get_timer(), 0.6) <del> self.assertEqual(server.get_timer(), 1.1) <35>:<add> now += 0.1 <del> now = 0.2
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 1.0) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE <26> now = 0.1 <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 1.1) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client receives INITIAL + HANDSHAKE <35> now = 0.2 <36> client.receive_datagram(items[0][0], SERVER_ADDR, now=</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 1 client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 0.825) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) # server completes handshake now = 0.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 0.825) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) # server PTO - 1-RTT PING now = 0.825 server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [29]) self.assertAlmostEqual(server.get_timer(), 1.875) # client receives PING, sends ACK now = 0.9 client.receive_datagram(items[0][0], SERVER</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 2 <s> client receives PING, sends ACK now = 0.9 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 0.825) # server receives ACK, retransmits HANDSHAKE_DONE now = 1.0 self.assertFalse(server._handshake_done_pending) server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) self.assertTrue(server._handshake_done_pending) items = server.datagrams_to_send(now=now) self.assertFalse(server._handshake_done_pending) self.assertEqual(datagram_sizes(items), [224]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.5) - self.assertEqual(client.get_timer(), 1.0) # INITIAL is lost + now = client.get_timer() - now = 1.0 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 1.5) - self.assertEqual(client.get_timer(), 3.0) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += 0.1 - now = 1.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now)</s>
aioquic.quic.packet/get_retry_integrity_tag
Modified
aiortc~aioquic
e7ca4712e1d7e1fb1d706d54fdface8b40b6e957
[retry] update key and nonce for draft-29
<10>:<add> if version < QuicProtocolVersion.DRAFT_29: <add> aead_key = RETRY_AEAD_KEY_DRAFT_25 <add> aead_nonce = RETRY_AEAD_NONCE_DRAFT_25 <add> else: <add> aead_key = RETRY_AEAD_KEY_DRAFT_29 <add> aead_nonce = RETRY_AEAD_NONCE_DRAFT_29 <add> <11>:<add> aead = AESGCM(aead_key) <del> aead = AESGCM(RETRY_AEAD_KEY) <12>:<add> integrity_tag = aead.encrypt(aead_nonce, b"", buf.data) <del> integrity_tag = aead.encrypt(RETRY_AEAD_NONCE, b"", buf.data)
# module: aioquic.quic.packet def get_retry_integrity_tag( + packet_without_tag: bytes, original_destination_cid: bytes, version: int - packet_without_tag: bytes, original_destination_cid: bytes ) -> bytes: <0> """ <1> Calculate the integrity tag for a RETRY packet. <2> """ <3> # build Retry pseudo packet <4> buf = Buffer(capacity=1 + len(original_destination_cid) + len(packet_without_tag)) <5> buf.push_uint8(len(original_destination_cid)) <6> buf.push_bytes(original_destination_cid) <7> buf.push_bytes(packet_without_tag) <8> assert buf.eof() <9> <10> # run AES-128-GCM <11> aead = AESGCM(RETRY_AEAD_KEY) <12> integrity_tag = aead.encrypt(RETRY_AEAD_NONCE, b"", buf.data) <13> assert len(integrity_tag) == RETRY_INTEGRITY_TAG_SIZE <14> return integrity_tag <15>
===========unchanged ref 0=========== at: aioquic.quic.packet RETRY_AEAD_KEY_DRAFT_25 = binascii.unhexlify("4d32ecdb2a2133c841e4043df27d4430") RETRY_AEAD_NONCE_DRAFT_25 = binascii.unhexlify("4d1611d05513a552c587d575") QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========changed ref 0=========== # module: aioquic.quic.packet PACKET_LONG_HEADER = 0x80 PACKET_FIXED_BIT = 0x40 PACKET_SPIN_BIT = 0x20 PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_ZERO_RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT PACKET_TYPE_MASK = 0xF0 CONNECTION_ID_MAX_SIZE = 20 PACKET_NUMBER_MAX_SIZE = 4 + RETRY_AEAD_KEY_DRAFT_25 = binascii.unhexlify("4d32ecdb2a2133c841e4043df27d4430") - RETRY_AEAD_KEY = binascii.unhexlify("4d32ecdb2a2133c841e4043df27d4430") + RETRY_AEAD_KEY_DRAFT_29 = binascii.unhexlify("ccce187ed09a09d05728155a6cb96be1") + RETRY_AEAD_NONCE_DRAFT_25 = binascii.unhexlify("4d1611d05513a552c587d575") - RETRY_AEAD_NONCE = binascii.unhexlify("4d1611d05513a552c587d575") + RETRY_AEAD_NONCE_DRAFT_29 = binascii.unhexlify("e54930f97f2136f0530a8c1c") RETRY_INTEGRITY_TAG_SIZE = 16
aioquic.quic.packet/encode_quic_retry
Modified
aiortc~aioquic
e7ca4712e1d7e1fb1d706d54fdface8b40b6e957
[retry] update key and nonce for draft-29
<14>:<add> buf.push_bytes( <add> get_retry_integrity_tag(buf.data, original_destination_cid, version=version) <del> buf.push_bytes(get_retry_integrity_tag(buf.data, original_destination_cid)) <15>:<add> )
# module: aioquic.quic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: <0> buf = Buffer( <1> capacity=7 <2> + len(destination_cid) <3> + len(source_cid) <4> + len(retry_token) <5> + RETRY_INTEGRITY_TAG_SIZE <6> ) <7> buf.push_uint8(PACKET_TYPE_RETRY) <8> buf.push_uint32(version) <9> buf.push_uint8(len(destination_cid)) <10> buf.push_bytes(destination_cid) <11> buf.push_uint8(len(source_cid)) <12> buf.push_bytes(source_cid) <13> buf.push_bytes(retry_token) <14> buf.push_bytes(get_retry_integrity_tag(buf.data, original_destination_cid)) <15> assert buf.eof() <16> return buf.data <17>
===========unchanged ref 0=========== at: aioquic.quic.packet PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 RETRY_INTEGRITY_TAG_SIZE = 16 at: aioquic.quic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes token: bytes = b"" integrity_tag: bytes = b"" rest_length: int = 0 at: aioquic.quic.packet.pull_quic_header packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) ===========changed ref 0=========== # module: aioquic.quic.packet def get_retry_integrity_tag( + packet_without_tag: bytes, original_destination_cid: bytes, version: int - packet_without_tag: bytes, original_destination_cid: bytes ) -> bytes: """ Calculate the integrity tag for a RETRY packet. """ # build Retry pseudo packet buf = Buffer(capacity=1 + len(original_destination_cid) + len(packet_without_tag)) buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(packet_without_tag) assert buf.eof() + if version < QuicProtocolVersion.DRAFT_29: + aead_key = RETRY_AEAD_KEY_DRAFT_25 + aead_nonce = RETRY_AEAD_NONCE_DRAFT_25 + else: + aead_key = RETRY_AEAD_KEY_DRAFT_29 + aead_nonce = RETRY_AEAD_NONCE_DRAFT_29 + # run AES-128-GCM + aead = AESGCM(aead_key) - aead = AESGCM(RETRY_AEAD_KEY) + integrity_tag = aead.encrypt(aead_nonce, b"", buf.data) - integrity_tag = aead.encrypt(RETRY_AEAD_NONCE, b"", buf.data) assert len(integrity_tag) == RETRY_INTEGRITY_TAG_SIZE return integrity_tag ===========changed ref 1=========== # module: aioquic.quic.packet PACKET_LONG_HEADER = 0x80 PACKET_FIXED_BIT = 0x40 PACKET_SPIN_BIT = 0x20 PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_ZERO_RTT = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x10 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT PACKET_TYPE_MASK = 0xF0 CONNECTION_ID_MAX_SIZE = 20 PACKET_NUMBER_MAX_SIZE = 4 + RETRY_AEAD_KEY_DRAFT_25 = binascii.unhexlify("4d32ecdb2a2133c841e4043df27d4430") - RETRY_AEAD_KEY = binascii.unhexlify("4d32ecdb2a2133c841e4043df27d4430") + RETRY_AEAD_KEY_DRAFT_29 = binascii.unhexlify("ccce187ed09a09d05728155a6cb96be1") + RETRY_AEAD_NONCE_DRAFT_25 = binascii.unhexlify("4d1611d05513a552c587d575") - RETRY_AEAD_NONCE = binascii.unhexlify("4d1611d05513a552c587d575") + RETRY_AEAD_NONCE_DRAFT_29 = binascii.unhexlify("e54930f97f2136f0530a8c1c") RETRY_INTEGRITY_TAG_SIZE = 16
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<27>:<add> self.assertEqual(client.get_timer(), 0.2) <del> self.assertEqual(client.get_timer(), 0.5) <34>:<add> self.assertAlmostEqual(client.get_timer(), 0.6) <del> self.assertEqual(client.get_timer(), 1.5) <37>:<add> now += TICK <del> now += 0.1
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): <0> """ <1> Check connection is established even in the client's INITIAL is lost. <2> """ <3> <4> def datagram_sizes(items): <5> return [len(x[0]) for x in items] <6> <7> client_configuration = QuicConfiguration(is_client=True) <8> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <9> <10> client = QuicConnection(configuration=client_configuration) <11> client._ack_delay = 0 <12> <13> server_configuration = QuicConfiguration(is_client=False) <14> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <15> <16> server = QuicConnection( <17> configuration=server_configuration, <18> original_destination_connection_id=client.original_destination_connection_id, <19> ) <20> server._ack_delay = 0 <21> <22> # client sends INITIAL <23> now = 0.0 <24> client.connect(SERVER_ADDR, now=now) <25> items = client.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280]) <27> self.assertEqual(client.get_timer(), 0.5) <28> <29> # INITIAL is lost <30> now = client.get_timer() <31> client.handle_timer(now=now) <32> items = client.datagrams_to_send(now=now) <33> self.assertEqual(datagram_sizes(items), [1280]) <34> self.assertEqual(client.get_timer(), 1.5) <35> <36> # server receives INITIAL, sends INITIAL + HANDSHAKE <37> now += 0.1 <38> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <39> items = server.datagrams_to_send(now=now) <40> self.assertEqual(datagram_sizes(items), [</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 self.assertEqual(server.get_timer(), 1.1) self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # handshake continues normally now += 0.1 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 1.325) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 1.325) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now += 0.1 client.receive_dat</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>(server.next_event()), events.ConnectionIdIssued) now += 0.1 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 60.9) # idle timeout ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<23>:<add> self.assertEqual(client.get_timer(), 0.2) <del> self.assertEqual(client.get_timer(), 0.5) <26>:<add> now += TICK <del> now += 0.1 <30>:<add> self.assertEqual(server.get_timer(), 0.25) <del> self.assertEqual(server.get_timer(), 0.6) <35>:<add> now += TICK <del> now += 0.1
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 0.5) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <26> now += 0.1 <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 0.6) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client only receives first datagram and sends ACKS <35> now += 0.1 <36> client.receive_datagram(items[0</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [97]) self.assertAlmostEqual(client.get_timer(), 0.625) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertIsNone(client.next_event()) # client PTO - HANDSHAKE PING now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [45]) self.assertAlmostEqual(client.get_timer(), 1.875) # server receives PING, discards INITIAL and sends ACK now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [48]) self.assertAlmostEqual(server.get_timer(), 0.6) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 874]) self.assertAlmostEqual(server.get_timer(), 1.6) self.assertEqual(len</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s> 874]) self.assertAlmostEqual(server.get_timer(), 1.6) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertIsNone(server.next_event()) # handshake continues normally now += 0.1 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [329]) self.assertAlmostEqual(client.get_timer(), 1.95) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 1.425) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now += 0.1 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_1 client = QuicConnection(configuration=client_configuration) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.2) - self.assertEqual(client.get_timer(), 0.5) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertAlmostEqual(client.get_timer(), 0.6) - self.assertEqual(client.get_timer(), 1.5) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += TICK - now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(dat</s>
tests.test_connection/QuicConnectionTest.test_connect_with_loss_3
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<23>:<add> self.assertEqual(client.get_timer(), 0.2) <del> self.assertEqual(client.get_timer(), 0.5) <26>:<add> now += TICK <del> now += 0.1 <30>:<add> self.assertEqual(server.get_timer(), 0.25) <del> self.assertEqual(server.get_timer(), 0.6) <35>:<add> now += TICK <del> now += 0.1
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 0.5) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE <26> now += 0.1 <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 0.6) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client receives INITIAL + HANDSHAKE <35> now += 0.1 <36> client.receive_datagram(items[0][0], SERVER_ADDR, now=</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 1 client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 0.825) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) # server completes handshake now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 0.825) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) # server PTO - 1-RTT PING now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [29]) self.assertAlmostEqual(server.get_timer(), 1.875) # client receives PING, sends ACK now += 0.1 client.receive_datagram(items[0][0</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 2 <s> # client receives PING, sends ACK now += 0.1 client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 0.825) # server receives ACK, retransmits HANDSHAKE_DONE now += 0.1 self.assertFalse(server._handshake_done_pending) server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) self.assertTrue(server._handshake_done_pending) items = server.datagrams_to_send(now=now) self.assertFalse(server._handshake_done_pending) self.assertEqual(datagram_sizes(items), [224]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_2 client = QuicConnection(configuration=client_configuration) at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.2) - self.assertEqual(client.get_timer(), 0.5) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertAlmostEqual(client.get_timer(), 0.6) - self.assertEqual(client.get_timer(), 1.5) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += TICK - now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(dat</s>
aioquic.quic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<10>:<add> self._rtt_initial = initial_rtt
# module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, + initial_rtt: float, peer_completed_address_validation: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: <0> self.max_ack_delay = 0.025 <1> self.peer_completed_address_validation = peer_completed_address_validation <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._cc = QuicCongestionControl() <19> self._pacer = QuicPacketPacer() <20>
===========unchanged ref 0=========== at: aioquic.quic.recovery QuicPacketSpace() QuicCongestionControl() 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_sent self._time_of_last_sent_ack_eliciting_packet = packet.sent_time at: math inf: float at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.quic.recovery # loss detection K_PACKET_THRESHOLD = 3 - K_INITIAL_RTT = 0.25 # seconds K_GRANULARITY = 0.001 # seconds K_TIME_THRESHOLD = 9 / 8 K_MICRO_SECOND = 0.000001 K_SECOND = 1.0 # congestion control K_MAX_DATAGRAM_SIZE = 1280 K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 ===========changed ref 1=========== # module: tests.test_connection + TICK = 0.05 # seconds ===========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. """ max_data: int = 1048576 """ Connection-wide flow control limit. """ max_stream_data: int = 1048576 """ Per-stream flow control limit. """ 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) cipher_suites: Optional[List[CipherSuite]] = None + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None</s> ===========changed ref 3=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None private_key: Any = None quantum_readiness_test: bool = False supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_29, QuicProtocolVersion.DRAFT_28, ] ) verify_mode: Optional[int] = None ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.2) - self.assertEqual(client.get_timer(), 0.5) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertAlmostEqual(client.get_timer(), 0.6) - self.assertEqual(client.get_timer(), 1.5) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += TICK - now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(dat</s>
aioquic.quic.recovery/QuicPacketRecovery.get_probe_timeout
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<1>:<add> return 2 * self._rtt_initial <del> return 2 * K_INITIAL_RTT
# module: aioquic.quic.recovery class QuicPacketRecovery: def get_probe_timeout(self) -> float: <0> if not self._rtt_initialized: <1> return 2 * K_INITIAL_RTT <2> return ( <3> self._rtt_smoothed <4> + max(4 * self._rtt_variance, K_GRANULARITY) <5> + self.max_ack_delay <6> ) <7>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_GRANULARITY = 0.001 # seconds at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.max_ack_delay = 0.025 self._rtt_initial = initial_rtt self._rtt_initialized = False self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received 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 ) ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, + initial_rtt: float, peer_completed_address_validation: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.max_ack_delay = 0.025 self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 + self._rtt_initial = initial_rtt 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._cc = QuicCongestionControl() self._pacer = QuicPacketPacer() ===========changed ref 1=========== # module: aioquic.quic.recovery # loss detection K_PACKET_THRESHOLD = 3 - K_INITIAL_RTT = 0.25 # seconds K_GRANULARITY = 0.001 # seconds K_TIME_THRESHOLD = 9 / 8 K_MICRO_SECOND = 0.000001 K_SECOND = 1.0 # congestion control K_MAX_DATAGRAM_SIZE = 1280 K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 ===========changed ref 2=========== # module: tests.test_connection + TICK = 0.05 # seconds ===========changed ref 3=========== # 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. """ max_data: int = 1048576 """ Connection-wide flow control limit. """ max_stream_data: int = 1048576 """ Per-stream flow control limit. """ 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) cipher_suites: Optional[List[CipherSuite]] = None + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None</s> ===========changed ref 4=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None private_key: Any = None quantum_readiness_test: bool = False supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_29, QuicProtocolVersion.DRAFT_28, ] ) verify_mode: Optional[int] = None ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertEqual(client.get_timer(), 0.2) - self.assertEqual(client.get_timer(), 0.5) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) + self.assertAlmostEqual(client.get_timer(), 0.6) - self.assertEqual(client.get_timer(), 1.5) # server receives INITIAL, sends INITIAL + HANDSHAKE + now += TICK - now += 0.1 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(dat</s>
aioquic.quic.recovery/QuicPacketRecovery._detect_loss
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<6>:<add> else self._rtt_initial <del> else K_INITIAL_RTT
# module: aioquic.quic.recovery class QuicPacketRecovery: def _detect_loss(self, space: QuicPacketSpace, now: float) -> None: <0> """ <1> Check whether any packets should be declared lost. <2> """ <3> loss_delay = K_TIME_THRESHOLD * ( <4> max(self._rtt_latest, self._rtt_smoothed) <5> if self._rtt_initialized <6> else K_INITIAL_RTT <7> ) <8> packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD <9> time_threshold = now - loss_delay <10> <11> lost_packets = [] <12> space.loss_time = None <13> for packet_number, packet in space.sent_packets.items(): <14> if packet_number > space.largest_acked_packet: <15> break <16> <17> if packet_number <= packet_threshold or packet.sent_time <= time_threshold: <18> lost_packets.append(packet) <19> else: <20> packet_loss_time = packet.sent_time + loss_delay <21> if space.loss_time is None or space.loss_time > packet_loss_time: <22> space.loss_time = packet_loss_time <23> <24> self._on_packets_lost(lost_packets, space=space, now=now) <25>
===========unchanged ref 0=========== at: aioquic.quic.recovery K_PACKET_THRESHOLD = 3 K_TIME_THRESHOLD = 9 / 8 QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self._rtt_initial = initial_rtt self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_smoothed = 0.0 at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_initialized = True self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.largest_acked_packet = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {} ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def get_probe_timeout(self) -> float: if not self._rtt_initialized: + return 2 * self._rtt_initial - return 2 * K_INITIAL_RTT return ( self._rtt_smoothed + max(4 * self._rtt_variance, K_GRANULARITY) + self.max_ack_delay ) ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, + initial_rtt: float, peer_completed_address_validation: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.max_ack_delay = 0.025 self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 + self._rtt_initial = initial_rtt 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._cc = QuicCongestionControl() self._pacer = QuicPacketPacer() ===========changed ref 2=========== # module: aioquic.quic.recovery # loss detection K_PACKET_THRESHOLD = 3 - K_INITIAL_RTT = 0.25 # seconds K_GRANULARITY = 0.001 # seconds K_TIME_THRESHOLD = 9 / 8 K_MICRO_SECOND = 0.000001 K_SECOND = 1.0 # congestion control K_MAX_DATAGRAM_SIZE = 1280 K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 ===========changed ref 3=========== # module: tests.test_connection + TICK = 0.05 # seconds ===========changed ref 4=========== # 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. """ max_data: int = 1048576 """ Connection-wide flow control limit. """ max_stream_data: int = 1048576 """ Per-stream flow control limit. """ 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) cipher_suites: Optional[List[CipherSuite]] = None + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None</s> ===========changed ref 5=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None private_key: Any = None quantum_readiness_test: bool = False supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_29, QuicProtocolVersion.DRAFT_28, ] ) verify_mode: Optional[int] = None
tests.test_recovery/QuicPacketRecoveryTest.setUp
Modified
aiortc~aioquic
c2673a5a64dd74dd8aa056cfc5a325c29cd20f55
[recovery] lower initial RTT to 0.1 seconds
<5>:<add> initial_rtt=0.1, <add> peer_completed_address_validation=True, <del> peer_completed_address_validation=True, send_probe=send_probe <6>:<add> send_probe=send_probe,
# module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def setUp(self): <0> self.INITIAL_SPACE = QuicPacketSpace() <1> self.HANDSHAKE_SPACE = QuicPacketSpace() <2> self.ONE_RTT_SPACE = QuicPacketSpace() <3> <4> self.recovery = QuicPacketRecovery( <5> peer_completed_address_validation=True, send_probe=send_probe <6> ) <7> self.recovery.spaces = [ <8> self.INITIAL_SPACE, <9> self.HANDSHAKE_SPACE, <10> self.ONE_RTT_SPACE, <11> ] <12>
===========unchanged ref 0=========== at: tests.test_recovery send_probe() at: unittest.case.TestCase failureException = AssertionError longMessage = True maxDiff = 80*8 _diffThreshold = 2**16 setUp(self) -> None failUnlessEqual = assertEquals = _deprecate(assertEqual) failUnlessEqual = assertEquals = _deprecate(assertEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failIfEqual = assertNotEquals = _deprecate(assertNotEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual) failUnless = assert_ = _deprecate(assertTrue) failUnless = assert_ = _deprecate(assertTrue) failUnlessRaises = _deprecate(assertRaises) failIf = _deprecate(assertFalse) assertRaisesRegexp = _deprecate(assertRaisesRegex) assertRegexpMatches = _deprecate(assertRegex) assertNotRegexpMatches = _deprecate(assertNotRegex) ===========changed ref 0=========== # module: tests.test_connection + TICK = 0.05 # seconds ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def get_probe_timeout(self) -> float: if not self._rtt_initialized: + return 2 * self._rtt_initial - return 2 * K_INITIAL_RTT return ( self._rtt_smoothed + max(4 * self._rtt_variance, K_GRANULARITY) + self.max_ack_delay ) ===========changed ref 2=========== # module: aioquic.quic.recovery # loss detection K_PACKET_THRESHOLD = 3 - K_INITIAL_RTT = 0.25 # seconds K_GRANULARITY = 0.001 # seconds K_TIME_THRESHOLD = 9 / 8 K_MICRO_SECOND = 0.000001 K_SECOND = 1.0 # congestion control K_MAX_DATAGRAM_SIZE = 1280 K_INITIAL_WINDOW = 10 * K_MAX_DATAGRAM_SIZE K_MINIMUM_WINDOW = 2 * K_MAX_DATAGRAM_SIZE K_LOSS_REDUCTION_FACTOR = 0.5 ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( self, + initial_rtt: float, peer_completed_address_validation: bool, send_probe: Callable[[], None], quic_logger: Optional[QuicLoggerTrace] = None, ) -> None: self.max_ack_delay = 0.025 self.peer_completed_address_validation = peer_completed_address_validation self.spaces: List[QuicPacketSpace] = [] # callbacks self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 + self._rtt_initial = initial_rtt 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._cc = QuicCongestionControl() self._pacer = QuicPacketPacer() ===========changed ref 4=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def _detect_loss(self, space: QuicPacketSpace, now: float) -> None: """ Check whether any packets should be declared lost. """ loss_delay = K_TIME_THRESHOLD * ( max(self._rtt_latest, self._rtt_smoothed) if self._rtt_initialized + else self._rtt_initial - else K_INITIAL_RTT ) packet_threshold = space.largest_acked_packet - K_PACKET_THRESHOLD time_threshold = now - loss_delay lost_packets = [] space.loss_time = None for packet_number, packet in space.sent_packets.items(): if packet_number > space.largest_acked_packet: break if packet_number <= packet_threshold or packet.sent_time <= time_threshold: lost_packets.append(packet) else: packet_loss_time = packet.sent_time + loss_delay if space.loss_time is None or space.loss_time > packet_loss_time: space.loss_time = packet_loss_time self._on_packets_lost(lost_packets, space=space, now=now) ===========changed ref 5=========== # 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. """ max_data: int = 1048576 """ Connection-wide flow control limit. """ max_stream_data: int = 1048576 """ Per-stream flow control limit. """ 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) cipher_suites: Optional[List[CipherSuite]] = None + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None</s> ===========changed ref 6=========== # module: aioquic.quic.configuration @dataclass class QuicConfiguration: # offset: 1 <s> + initial_rtt: float = 0.1 max_datagram_frame_size: Optional[int] = None private_key: Any = None quantum_readiness_test: bool = False supported_versions: List[int] = field( default_factory=lambda: [ QuicProtocolVersion.DRAFT_29, QuicProtocolVersion.DRAFT_28, ] ) verify_mode: Optional[int] = None
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
f9ac036393e14fd1970ceaaec2f9a54c96ab6dc5
[connection] don't set ODCID for draft-27 without retry
<17>:<add> if not self._is_client and ( <del> if not self._is_client: <18>:<add> self._version >= QuicProtocolVersion.DRAFT_28 <add> or self._retry_source_connection_id <add> ):
# 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> max_idle_timeout=int(self._configuration.idle_timeout * 1000), <4> initial_max_data=self._local_max_data.value, <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.value, <9> initial_max_streams_uni=self._local_max_streams_uni.value, <10> initial_source_connection_id=self._local_initial_source_connection_id, <11> max_ack_delay=25, <12> max_datagram_frame_size=self._configuration.max_datagram_frame_size, <13> quantum_readiness=b"Q" * 1200 <14> if self._configuration.quantum_readiness_test <15> else None, <16> ) <17> if not self._is_client: <18> quic_transport_parameters.original_destination_connection_id = ( <19> self._original_destination_connection_id <20> ) <21> quic_transport_parameters.retry_source_connection_id = ( <22> self._retry_source_connection_id <23> ) <24> <25> # log event <26> if self._quic_logger is not None: <27> self._quic_logger.log_event( <28> category="transport", <29> event="parameters_set", <30> data=self._quic_</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========unchanged ref 0=========== at: aioquic.quic.connection.Limit.__init__ self.value = value 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_initial_source_connection_id = self._host_cids[0].cid self._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._local_max_stream_data_bidi_local = configuration.max_stream_data self._local_max_stream_data_bidi_remote = configuration.max_stream_data self._local_max_stream_data_uni = configuration.max_stream_data self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._retry_source_connection_id = retry_source_connection_id self._version: Optional[int] = None self._original_destination_connection_id = self._peer_cid self._original_destination_connection_id = ( original_destination_connection_id ) ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self._retry_source_connection_id = header.source_cid
examples.interop/test_migration
Modified
aiortc~aioquic
710f108764e4ed912ddcbfdf08b3055d18f21bef
[interop] improve migration test case
<6>:<del> # change connection ID and replace transport <7>:<del> protocol.change_connection_id() <8>:<add> # replace transport <10>:<add> <add> # change connection ID <add> protocol.change_connection_id() <16>:<add> path_challenges = 0 <25>:<add> for frame in data["frames"]: <add> if frame["frame_type"] == "path_challenge": <add> path_challenges += 1 <add> <add> if not path_challenges: <add> protocol._quic._logger.warning("No PATH_CHALLENGE received") <add> elif len(dcids) < 2: <del> if len(dcids) == 2: <26>:<add> protocol._quic._logger.warning("DCID did not change") <add> else:
# module: examples.interop def test_migration(server: Server, configuration: QuicConfiguration): <0> async with connect( <1> server.host, server.port, configuration=configuration <2> ) as protocol: <3> # cause some traffic <4> await protocol.ping() <5> <6> # change connection ID and replace transport <7> protocol.change_connection_id() <8> protocol._transport.close() <9> await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0)) <10> <11> # cause more traffic <12> await protocol.ping() <13> <14> # check log <15> dcids = set() <16> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <17> "traces" <18> ][0]["events"]: <19> if ( <20> category == "transport" <21> and event == "packet_received" <22> and data["packet_type"] == "1RTT" <23> ): <24> dcids.add(data["header"]["dcid"]) <25> if len(dcids) == 2: <26> server.result |= Result.M <27>
===========unchanged ref 0=========== at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: examples.interop loop = asyncio.get_event_loop() 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: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 0=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433, throughput=False), Server("haskell", "mew.org", structured_logging=True), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", - port=443, structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", structured_logging=True ), Server("ngtcp2", "nghttp2.org", push_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("quic-go", "interop.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("</s> ===========changed ref 1=========== # module: examples.interop # offset: 1 <s> Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
examples.interop/test_rebinding
Modified
aiortc~aioquic
710f108764e4ed912ddcbfdf08b3055d18f21bef
[interop] improve migration test case
<26>:<add> if not path_challenges: <del> if path_challenges: <27>:<add> protocol._quic._logger.warning("No PATH_CHALLENGE received") <add> else: <28>:<del> else: <29>:<del> protocol._quic._logger.warning("No PATH_CHALLENGE received")
# module: examples.interop def test_rebinding(server: Server, configuration: QuicConfiguration): <0> async with connect( <1> server.host, server.port, configuration=configuration <2> ) as protocol: <3> # cause some traffic <4> await protocol.ping() <5> <6> # replace transport <7> protocol._transport.close() <8> await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0)) <9> <10> # cause more traffic <11> await protocol.ping() <12> <13> # check log <14> path_challenges = 0 <15> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <16> "traces" <17> ][0]["events"]: <18> if ( <19> category == "transport" <20> and event == "packet_received" <21> and data["packet_type"] == "1RTT" <22> ): <23> for frame in data["frames"]: <24> if frame["frame_type"] == "path_challenge": <25> path_challenges += 1 <26> if path_challenges: <27> server.result |= Result.B <28> else: <29> protocol._quic._logger.warning("No PATH_CHALLENGE received") <30>
===========unchanged ref 0=========== at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair 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: bool=True, throughput_file_suffix: str="", verify_mode: Optional[int]=None) loop = asyncio.get_event_loop() at: examples.interop.Server host: str port: int = 4433 result: Result = field(default_factory=lambda: Result(0)) at: examples.interop.test_migration dcids = set() ===========changed ref 0=========== # module: examples.interop def test_migration(server: Server, configuration: QuicConfiguration): async with connect( server.host, server.port, configuration=configuration ) as protocol: # cause some traffic await protocol.ping() - # change connection ID and replace transport - protocol.change_connection_id() + # replace transport protocol._transport.close() await loop.create_datagram_endpoint(lambda: protocol, local_addr=("::", 0)) + + # change connection ID + protocol.change_connection_id() # cause more traffic await protocol.ping() # check log dcids = set() + path_challenges = 0 for stamp, category, event, data in configuration.quic_logger.to_dict()[ "traces" ][0]["events"]: if ( category == "transport" and event == "packet_received" and data["packet_type"] == "1RTT" ): dcids.add(data["header"]["dcid"]) + for frame in data["frames"]: + if frame["frame_type"] == "path_challenge": + path_challenges += 1 + + if not path_challenges: + protocol._quic._logger.warning("No PATH_CHALLENGE received") + elif len(dcids) < 2: - if len(dcids) == 2: + protocol._quic._logger.warning("DCID did not change") + else: server.result |= Result.M ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433, throughput=False), Server("haskell", "mew.org", structured_logging=True), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", - port=443, structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", structured_logging=True ), Server("ngtcp2", "nghttp2.org", push_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("quic-go", "interop.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s> Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
examples.interop/test_stateless_retry
Modified
aiortc~aioquic
c067a2708f73524e9e9f11fe3519a6f0e07e50f9
[interop] don't test retry if it is not supported
<0>:<add> # skip test if there is not retry port <add> if server.retry_port is None: <add> return <add>
# module: examples.interop def test_stateless_retry(server: Server, configuration: QuicConfiguration): <0> async with connect( <1> server.host, server.retry_port, configuration=configuration <2> ) as protocol: <3> await protocol.ping() <4> <5> # check log <6> for stamp, category, event, data in configuration.quic_logger.to_dict()[ <7> "traces" <8> ][0]["events"]: <9> if ( <10> category == "transport" <11> and event == "packet_received" <12> and data["packet_type"] == "retry" <13> ): <14> server.result |= Result.S <15>
===========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: bool=True, 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: bool = True throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 0=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433, throughput=False), Server("haskell", "mew.org", structured_logging=True), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", structured_logging=True, throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( + "mvfst", + "fb.mvfst.net", + port=443, + push_path="/push", + retry_port=None, + structured_logging=True, - "mvfst", "fb.mvfst.net", port=443, push_path="/push", structured_logging=True ), Server("ngtcp2", "nghttp2.org", push_path="/?push=/100"), + Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=None), - 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=</s> ===========changed ref 1=========== # module: examples.interop # offset: 1 <s>=ssl.CERT_NONE), Server("picoquic", "test.privateoctopus.com", structured_logging=True), Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "interop.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
examples.interop/test_throughput
Modified
aiortc~aioquic
2b2352bd060c10e90fe80aadb7dfe48a8508ab82
[interop] make throughput path customisable
<1>:<add> if server.throughput_path is None: <del> if not server.throughput: <5>:<add> path = server.throughput_path % {"size": size} <add> print("Testing %d bytes download: %s" % (size, path)) <del> print("Testing %d bytes download" % size) <6>:<del> path = "/%d%s" % (size, server.throughput_file_suffix)
# module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): <0> failures = 0 <1> if not server.throughput: <2> return <3> <4> for size in [5000000, 10000000]: <5> print("Testing %d bytes download" % size) <6> path = "/%d%s" % (size, server.throughput_file_suffix) <7> <8> # perform HTTP request over TCP <9> start = time.time() <10> response = httpx.get("https://" + server.host + path, verify=False) <11> tcp_octets = len(response.content) <12> tcp_elapsed = time.time() - start <13> assert tcp_octets == size, "HTTP/TCP response size mismatch" <14> <15> # perform HTTP request over QUIC <16> if server.http3: <17> configuration.alpn_protocols = H3_ALPN <18> else: <19> configuration.alpn_protocols = H0_ALPN <20> start = time.time() <21> async with connect( <22> server.host, <23> server.port, <24> configuration=configuration, <25> create_protocol=HttpClient, <26> ) as protocol: <27> protocol = cast(HttpClient, protocol) <28> <29> http_events = await protocol.get( <30> "https://{}:{}{}".format(server.host, server.port, path) <31> ) <32> quic_elapsed = time.time() - start <33> quic_octets = 0 <34> for http_event in http_events: <35> if isinstance(http_event, DataReceived): <36> quic_octets += len(http_event.data) <37> assert quic_octets == size, "HTTP/QUIC response size mismatch" <38> <39> print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) <40> print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) <41> <42> if quic_elapsed > 1.1 * tcp_elapsed: <43> failures += 1 <44> print(" => FAIL</s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 else: print(" => PASS") if failures == 0: server.result |= Result.T ===========unchanged ref 0=========== 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: bool=True, throughput_path: Optional[str]="/%(size)d", 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: bool = True throughput_path: Optional[str] = "/%(size)d" verify_mode: Optional[int] = None at: http3_client HttpClient(*args, **kwargs) at: httpx._api get(url: URL | str, *, params: QueryParamTypes | None=None, headers: HeaderTypes | None=None, cookies: CookieTypes | None=None, auth: AuthTypes | None=None, proxy: ProxyTypes | None=None, proxies: ProxiesTypes | None=None, follow_redirects: bool=False, cert: CertTypes | None=None, verify: VerifyTypes=True, timeout: TimeoutTypes=DEFAULT_TIMEOUT_CONFIG, trust_env: bool=True) -> Response 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 = "/" push_path: Optional[str] = None result: Result = field(default_factory=lambda: Result(0)) session_resumption_port: Optional[int] = None structured_logging: bool = False throughput: bool = True + throughput_path: Optional[str] = "/%(size)d" - throughput_file_suffix: str = "" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), + Server("f5", "f5quic.com", retry_port=4433, throughput_path=None), - Server("f5", "f5quic.com", retry_port=4433, throughput=False), + Server( + "haskell", "mew.org", structured_logging=True, throughput_path="/num/%(size)s" + ), - Server("haskell", "mew.org", structured_logging=True), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", structured_logging=True, + throughput_path="/%(size)d.txt", - throughput_file_suffix=".txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", retry_port=None, structured_logging=True, ), Server("ngtcp2", "nghttp2.org", push_path="/?push=/100"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=None), Server("pandora", "pandora.cm.in.tum.de", verify_mode=ssl.CERT_NONE), Server("picoquic</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s>andora.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("quic-go", "interop.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
aioquic.quic.connection/QuicConnection._write_application
Modified
aiortc~aioquic
f46588899953323c0786db7675c9dd369dbf3973
[connection] only update state when RETIRE_CONNECTION_ID is written
# 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> while True: <13> # apply pacing, except if we have ACKs to send <14> if space.ack_at is None or space.ack_at >= now: <15> self._pacing_at = self._loss._pacer.next_send_time(now=now) <16> if self._pacing_at is not None: <17> break <18> builder.start_packet(packet_type, crypto) <19> <20> if self._handshake_complete: <21> # ACK <22> if space.ack_at is not None and space.ack_at <= now: <23> self._write_ack_frame(builder=builder, space=space, now=now) <24> <25> # HANDSHAKE_DONE <26> if self._handshake_done_pending: <27> self._write_handshake_done_frame(builder=builder) <28> self._handshake_done_pending = False <29> <30> # PATH CHALLENGE <31> if ( <32> not network_path.is_validated <33> and network_path.local_challenge is None <34> ): <35> challenge = os.ur</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 1 self._write_path_challenge_frame( builder=builder, challenge=challenge ) network_path.local_challenge = challenge # PATH RESPONSE if network_path.remote_challenge is not None: self._write_path_response_frame( builder=builder, challenge=network_path.remote_challenge ) network_path.remote_challenge = None # 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 # MAX_DATA and MAX_STREAMS self._write_connection_limits(builder=builder, space=space) # stream-level limits for stream in self._streams.values(): self</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>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._write_ping_frame(builder, self._ping_pending) self._ping_pending.clear() # PING (probe) if self._probe_pending: self._write_ping_frame(builder, comment="probe") 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 ) # DATAGRAM while self._datagrams_pending: try: self._write_datagram_frame( builder=builder, data=self._datagrams_pending[0], frame_type=QuicFrameType.DATAGRAM_WITH_LENGTH, ) self._datagrams_pending.popleft() except QuicPacketBuilderStop: break # STREAM and RESET_STREAM for stream in self._streams.values(): if stream.reset_pending: self._write_reset_stream_frame( builder=builder, frame_type=QuicFrameType.RESET_STREAM, stream=stream, ) elif not stream.is_blocked and not stream.send_buffer_is_empty: self._remote_max_data_used += self._write_stream_frame( builder=builder, </s> ===========below chunk 2=========== # module: aioquic.quic.connection class QuicConnection: def _write_application( self, builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float ) -> None: # offset: 3 <s>=space, stream=stream, max_offset=min( stream._send_highest + self._remote_max_data - self._remote_max_data_used, stream.max_stream_data_remote, ), ) if builder.packet_is_empty: break else: self._loss._pacer.update_after_send(now=now) ===========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, now: float) -> None _write_connection_limits(builder: QuicPacketBuilder, space: QuicPacketSpace) -> None _write_crypto_frame(builder: QuicPacketBuilder, space: QuicPacketSpace, stream: QuicStream) -> bool _write_datagram_frame(builder: QuicPacketBuilder, data: bytes, frame_type: QuicFrameType) -> bool _write_handshake_done_frame(builder: QuicPacketBuilder) -> None _write_new_connection_id_frame(builder: QuicPacketBuilder, connection_id: QuicConnectionId) -> None _write_path_challenge_frame(builder: QuicPacketBuilder, challenge: bytes) -> None _write_path_response_frame(builder: QuicPacketBuilder, challenge: bytes) -> None _write_ping_frame(builder: QuicPacketBuilder, uids: List[int]=[], comment="") _write_reset_stream_frame(builder: QuicPacketBuilder, frame_type: QuicFrameType, stream: QuicStream) -> None _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
tests.test_connection/QuicConnectionTest.test_receive_datagram_reserved_bits_non_zero
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<3>:<add> host_cid=client._peer_cid.cid, <del> host_cid=client._peer_cid, <9>:<add> crypto.setup_initial( <add> client._peer_cid.cid, is_client=False, version=client._version <del> crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) <10>:<add> )
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_reserved_bits_non_zero(self): <0> client = create_standalone_client(self) <1> <2> builder = QuicPacketBuilder( <3> host_cid=client._peer_cid, <4> is_client=False, <5> peer_cid=client.host_cid, <6> version=client._version, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) <10> crypto.encrypt_packet_real = crypto.encrypt_packet <11> <12> def encrypt_packet(plain_header, plain_payload, packet_number): <13> # mess with reserved bits <14> plain_header = bytes([plain_header[0] | 0x0C]) + plain_header[1:] <15> return crypto.encrypt_packet_real( <16> plain_header, plain_payload, packet_number <17> ) <18> <19> crypto.encrypt_packet = encrypt_packet <20> <21> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <22> buf = builder.start_frame(QuicFrameType.PADDING) <23> buf.push_bytes(bytes(builder.remaining_flight_space)) <24> <25> for datagram in builder.flush()[0]: <26> client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) <27> self.assertEqual(drop(client), 1) <28> self.assertEqual( <29> client._close_event, <30> events.ConnectionTerminated( <31> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <32> frame_type=None, <33> reason_phrase="Reserved bits must be zero", <34> ), <35> ) <36>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) 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
tests.test_connection/QuicConnectionTest.test_receive_datagram_wrong_version
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<3>:<add> host_cid=client._peer_cid.cid, <del> host_cid=client._peer_cid, <9>:<add> crypto.setup_initial( <add> client._peer_cid.cid, is_client=False, version=client._version <del> crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) <10>:<add> )
# 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> is_client=False, <5> peer_cid=client.host_cid, <6> version=0xFF000011, # DRAFT_16 <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) <10> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <11> buf = builder.start_frame(QuicFrameType.PADDING) <12> buf.push_bytes(bytes(builder.remaining_flight_space)) <13> <14> for datagram in builder.flush()[0]: <15> client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) <16> self.assertEqual(drop(client), 0) <17>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) drop(sender) at: time time() -> float at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_reserved_bits_non_zero(self): client = create_standalone_client(self) builder = QuicPacketBuilder( + host_cid=client._peer_cid.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=client._version, ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) crypto.encrypt_packet_real = crypto.encrypt_packet def encrypt_packet(plain_header, plain_payload, packet_number): # mess with reserved bits plain_header = bytes([plain_header[0] | 0x0C]) + plain_header[1:] return crypto.encrypt_packet_real( plain_header, plain_payload, packet_number ) crypto.encrypt_packet = encrypt_packet builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 1) self.assertEqual( client._close_event, events.ConnectionTerminated( error_code=QuicErrorCode.PROTOCOL_VIOLATION, frame_type=None, reason_phrase="Reserved bits must be zero", ), )
tests.test_connection/QuicConnectionTest.test_receive_datagram_retry
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<7>:<add> original_destination_cid=client._peer_cid.cid, <del> original_destination_cid=client._peer_cid,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): <0> client = create_standalone_client(self) <1> <2> client.receive_datagram( <3> encode_quic_retry( <4> version=client._version, <5> source_cid=binascii.unhexlify("85abb547bf28be97"), <6> destination_cid=client.host_cid, <7> original_destination_cid=client._peer_cid, <8> retry_token=bytes(16), <9> ), <10> SERVER_ADDR, <11> now=time.time(), <12> ) <13> self.assertEqual(drop(client), 1) <14>
===========unchanged ref 0=========== at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) drop(sender) at: time time() -> float at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_reserved_bits_non_zero(self): client = create_standalone_client(self) builder = QuicPacketBuilder( + host_cid=client._peer_cid.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=client._version, ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) crypto.encrypt_packet_real = crypto.encrypt_packet def encrypt_packet(plain_header, plain_payload, packet_number): # mess with reserved bits plain_header = bytes([plain_header[0] | 0x0C]) + plain_header[1:] return crypto.encrypt_packet_real( plain_header, plain_payload, packet_number ) crypto.encrypt_packet = encrypt_packet builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 1) self.assertEqual( client._close_event, events.ConnectionTerminated( error_code=QuicErrorCode.PROTOCOL_VIOLATION, frame_type=None, reason_phrase="Reserved bits must be zero", ), )
tests.test_connection/QuicConnectionTest.test_receive_datagram_retry_wrong_destination_cid
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<7>:<add> original_destination_cid=client._peer_cid.cid, <del> original_destination_cid=client._peer_cid,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): <0> client = create_standalone_client(self) <1> <2> client.receive_datagram( <3> encode_quic_retry( <4> version=client._version, <5> source_cid=binascii.unhexlify("85abb547bf28be97"), <6> destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), <7> original_destination_cid=client._peer_cid, <8> retry_token=bytes(16), <9> ), <10> SERVER_ADDR, <11> now=time.time(), <12> ) <13> self.assertEqual(drop(client), 0) <14>
===========unchanged ref 0=========== at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) drop(sender) at: time time() -> float at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 1=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_reserved_bits_non_zero(self): client = create_standalone_client(self) builder = QuicPacketBuilder( + host_cid=client._peer_cid.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=client._version, ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) crypto.encrypt_packet_real = crypto.encrypt_packet def encrypt_packet(plain_header, plain_payload, packet_number): # mess with reserved bits plain_header = bytes([plain_header[0] | 0x0C]) + plain_header[1:] return crypto.encrypt_packet_real( plain_header, plain_payload, packet_number ) crypto.encrypt_packet = encrypt_packet builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 1) self.assertEqual( client._close_event, events.ConnectionTerminated( error_code=QuicErrorCode.PROTOCOL_VIOLATION, frame_type=None, reason_phrase="Reserved bits must be zero", ), )
tests.test_connection/QuicConnectionTest.test_version_negotiation_fail
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<5>:<add> source_cid=client._peer_cid.cid, <del> source_cid=client._peer_cid,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): <0> client = create_standalone_client(self) <1> <2> # no common version, no retry <3> client.receive_datagram( <4> encode_quic_version_negotiation( <5> source_cid=client._peer_cid, <6> destination_cid=client.host_cid, <7> supported_versions=[0xFF000011], # DRAFT_16 <8> ), <9> SERVER_ADDR, <10> now=time.time(), <11> ) <12> self.assertEqual(drop(client), 0) <13> <14> event = client.next_event() <15> self.assertEqual(type(event), events.ConnectionTerminated) <16> self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) <17> self.assertEqual(event.frame_type, None) <18> self.assertEqual( <19> event.reason_phrase, "Could not find a common protocol version" <20> ) <21>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) drop(sender) at: time time() -> float at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_over_limit(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(0) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_new_connection_id_frame( + client_receive_context(client), + QuicFrameType.NEW_CONNECTION_ID, + buf, + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.CONNECTION_ID_LIMIT_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.NEW_CONNECTION_ID) + self.assertEqual( + cm.exception.reason_phrase, "Too many active connection IDs" + ) + ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_reserved_bits_non_zero(self): client = create_standalone_client(self) builder = QuicPacketBuilder( + host_cid=client._peer_cid.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=client._version, ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) crypto.encrypt_packet_real = crypto.encrypt_packet def encrypt_packet(plain_header, plain_payload, packet_number): # mess with reserved bits plain_header = bytes([plain_header[0] | 0x0C]) + plain_header[1:] return crypto.encrypt_packet_real( plain_header, plain_payload, packet_number ) crypto.encrypt_packet = encrypt_packet builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 1) self.assertEqual( client._close_event, events.ConnectionTerminated( error_code=QuicErrorCode.PROTOCOL_VIOLATION, frame_type=None, reason_phrase="Reserved bits must be zero", ), )
tests.test_connection/QuicConnectionTest.test_version_negotiation_ok
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<5>:<add> source_cid=client._peer_cid.cid, <del> source_cid=client._peer_cid,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): <0> client = create_standalone_client(self) <1> <2> # found a common version, retry <3> client.receive_datagram( <4> encode_quic_version_negotiation( <5> source_cid=client._peer_cid, <6> destination_cid=client.host_cid, <7> supported_versions=[client._version], <8> ), <9> SERVER_ADDR, <10> now=time.time(), <11> ) <12> self.assertEqual(drop(client), 1) <13>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) drop(sender) at: time time() -> float at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): client = create_standalone_client(self) # no common version, no retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[0xFF000011], # DRAFT_16 ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual( event.reason_phrase, "Could not find a common protocol version" ) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_over_limit(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(0) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_new_connection_id_frame( + client_receive_context(client), + QuicFrameType.NEW_CONNECTION_ID, + buf, + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.CONNECTION_ID_LIMIT_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.NEW_CONNECTION_ID) + self.assertEqual( + cm.exception.reason_phrase, "Too many active connection IDs" + ) + ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 5=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0)
tests.test_connection/QuicConnectionTest.test_write_connection_close_early
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<5>:<add> peer_cid=client._peer_cid.cid, <del> peer_cid=client._peer_cid,
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_write_connection_close_early(self): <0> client = create_standalone_client(self) <1> <2> builder = QuicPacketBuilder( <3> host_cid=client.host_cid, <4> is_client=True, <5> peer_cid=client._peer_cid, <6> version=client._version, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(client.host_cid, is_client=True, version=client._version) <10> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <11> client._write_connection_close_frame( <12> builder=builder, <13> epoch=tls.Epoch.INITIAL, <14> error_code=123, <15> frame_type=None, <16> reason_phrase="some reason", <17> ) <18> <19> self.assertEqual( <20> builder.quic_logger_frames, <21> [ <22> { <23> "error_code": QuicErrorCode.APPLICATION_ERROR, <24> "error_space": "transport", <25> "frame_type": "connection_close", <26> "raw_error_code": QuicErrorCode.APPLICATION_ERROR, <27> "reason": "", <28> "trigger_frame_type": QuicFrameType.PADDING, <29> } <30> ], <31> ) <32>
===========unchanged ref 0=========== at: tests.test_connection create_standalone_client(self, **client_options) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): client = create_standalone_client(self) # found a common version, retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[client._version], ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): client = create_standalone_client(self) # no common version, no retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[0xFF000011], # DRAFT_16 ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual( event.reason_phrase, "Could not find a common protocol version" ) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_over_limit(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(0) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_new_connection_id_frame( + client_receive_context(client), + QuicFrameType.NEW_CONNECTION_ID, + buf, + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.CONNECTION_ID_LIMIT_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.NEW_CONNECTION_ID) + self.assertEqual( + cm.exception.reason_phrase, "Too many active connection IDs" + ) + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 6=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0)
aioquic.quic.connection/QuicConnection.change_connection_id
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<9>:<del> self._logger.debug( <10>:<del> "Retiring CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq <11>:<del> ) <12>:<add> self._retire_peer_cid(self._peer_cid) <del> self._retire_connection_ids.append(self._peer_cid_seq) <15>:<del> connection_id = self._peer_cid_available.pop(0) <16>:<del> self._peer_cid_seq = connection_id.sequence_number <17>:<del> self._peer_cid = connection_id.cid <18>:<del> self._logger.debug( <19>:<del> "Switching to CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq <20>:<del> ) <21>:<add> self._consume_peer_cid()
# module: aioquic.quic.connection class QuicConnection: def change_connection_id(self) -> None: <0> """ <1> Switch to the next available connection ID and retire <2> the previous one. <3> <4> After calling this method call :meth:`datagrams_to_send` to retrieve data <5> which needs to be sent. <6> """ <7> if self._peer_cid_available: <8> # retire previous CID <9> self._logger.debug( <10> "Retiring CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq <11> ) <12> self._retire_connection_ids.append(self._peer_cid_seq) <13> <14> # assign new CID <15> connection_id = self._peer_cid_available.pop(0) <16> self._peer_cid_seq = connection_id.sequence_number <17> self._peer_cid = connection_id.cid <18> self._logger.debug( <19> "Switching to CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq <20> ) <21>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection _consume_peer_cid() -> None _retire_peer_cid(connection_id: QuicConnectionId) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._peer_cid = QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=None ) self._peer_cid_available: List[QuicConnectionId] = [] at: aioquic.quic.connection.QuicConnection._consume_peer_cid self._peer_cid = self._peer_cid_available.pop(0) at: aioquic.quic.connection.QuicConnection._handle_new_connection_id_frame self._peer_cid_available = list( filter( lambda c: c.sequence_number >= retire_prior_to, self._peer_cid_available ) ) + [ QuicConnectionId( cid=connection_id, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ] ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): client = create_standalone_client(self) # found a common version, retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[client._version], ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): client = create_standalone_client(self) # no common version, no retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[0xFF000011], # DRAFT_16 ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual( event.reason_phrase, "Could not find a common protocol version" ) ===========changed ref 5=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0) ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_over_limit(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(0) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_new_connection_id_frame( + client_receive_context(client), + QuicFrameType.NEW_CONNECTION_ID, + buf, + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.CONNECTION_ID_LIMIT_ERROR + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.NEW_CONNECTION_ID) + self.assertEqual( + cm.exception.reason_phrase, "Too many active connection IDs" + ) +
aioquic.quic.connection/QuicConnection.datagrams_to_send
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<19>:<add> peer_cid=self._peer_cid.cid, <del> peer_cid=self._peer_cid,
# 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> After calling this method call :meth:`get_timer` to know when the next <5> timer needs to be set. <6> <7> :param now: The current time. <8> """ <9> network_path = self._network_paths[0] <10> <11> if self._state in END_STATES: <12> return [] <13> <14> # build datagrams <15> builder = QuicPacketBuilder( <16> host_cid=self.host_cid, <17> is_client=self._is_client, <18> packet_number=self._packet_number, <19> peer_cid=self._peer_cid, <20> peer_token=self._peer_token, <21> quic_logger=self._quic_logger, <22> spin_bit=self._spin_bit, <23> version=self._version, <24> ) <25> if self._close_pending: <26> for epoch, packet_type in ( <27> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT), <28> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE), <29> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL), <30> ): <31> crypto = self._cryptos[epoch] <32> if crypto.send.is_valid(): <33> builder.start_packet(packet_type, crypto) <34> self._write_connection_close_frame( <35> builder=builder, <36> epoch=epoch, <37> error_code=self._close_event.error_code, <38> frame_type=self._close_event.frame_type, <39> reason_phrase=self._close_event.reason_phrase, <40> ) <41> self._close</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 1 break self._close_begin(is_initiator=True, now=now) 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, now) 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</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 2 <s>( packet.packet_type ), "header": { "packet_number": 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 dump_cid(cid: bytes) -> str 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, now: float) -> None _write_connection_close_frame(builder: QuicPacketBuilder, epoch: tls.Epoch, 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 = QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=None ) self._peer_token = b"" self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False ===========unchanged ref 1=========== self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._version: Optional[int] = None self._loss = QuicPacketRecovery( initial_rtt=configuration.initial_rtt, peer_completed_address_validation=not 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._consume_peer_cid self._peer_cid = self._peer_cid_available.pop(0) 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._handle_crypto_frame self._handshake_confirmed = True at: aioquic.quic.connection.QuicConnection._handle_handshake_done_frame self._handshake_confirmed = True at: aioquic.quic.connection.QuicConnection._initialize self._cryptos = dict( (epoch, create_crypto_pair(epoch)) for epoch in ( tls.Epoch.INITIAL, tls.Epoch.ZERO_RTT, tls.Epoch.HANDSHAKE, tls.Epoch.ONE_RTT, ) ) self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._packet_number = 0
aioquic.quic.connection/QuicConnection._connect
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<6>:<add> self._initialize(self._peer_cid.cid) <del> self._initialize(self._peer_cid)
# module: aioquic.quic.connection class QuicConnection: def _connect(self, now: float) -> None: <0> """ <1> Start the client handshake. <2> """ <3> assert self._is_client <4> <5> self._close_at = now + self._configuration.idle_timeout <6> self._initialize(self._peer_cid) <7> <8> self.tls.handle_message(b"", self._crypto_buffers) <9> self._push_crypto_data() <10>
===========unchanged ref 0=========== at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: + def _consume_peer_cid(self) -> None: + """ + Update the destination connection ID by taking the next + available connection ID provided by the peer. + """ + + self._peer_cid = self._peer_cid_available.pop(0) + self._logger.debug( + "Switching to CID %s (%d)", + dump_cid(self._peer_cid.cid), + self._peer_cid.sequence_number, + ) + ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def change_connection_id(self) -> None: """ Switch to the next available connection ID and retire the previous one. After calling this method call :meth:`datagrams_to_send` to retrieve data which needs to be sent. """ if self._peer_cid_available: # retire previous CID - self._logger.debug( - "Retiring CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq - ) + self._retire_peer_cid(self._peer_cid) - self._retire_connection_ids.append(self._peer_cid_seq) # assign new CID - connection_id = self._peer_cid_available.pop(0) - self._peer_cid_seq = connection_id.sequence_number - self._peer_cid = connection_id.cid - self._logger.debug( - "Switching to CID %s (%d)", dump_cid(self._peer_cid), self._peer_cid_seq - ) + self._consume_peer_cid() ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): client = create_standalone_client(self) # found a common version, retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[client._version], ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): client = create_standalone_client(self) # no common version, no retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[0xFF000011], # DRAFT_16 ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual( event.reason_phrase, "Could not find a common protocol version" ) ===========changed ref 7=========== # 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.cid, - host_cid=client._peer_cid, is_client=False, peer_cid=client.host_cid, version=0xFF000011, # DRAFT_16 ) crypto = CryptoPair() + crypto.setup_initial( + client._peer_cid.cid, is_client=False, version=client._version - crypto.setup_initial(client._peer_cid, is_client=False, version=client._version) + ) builder.start_packet(PACKET_TYPE_INITIAL, crypto) buf = builder.start_frame(QuicFrameType.PADDING) buf.push_bytes(bytes(builder.remaining_flight_space)) for datagram in builder.flush()[0]: client.receive_datagram(datagram, SERVER_ADDR, now=time.time()) self.assertEqual(drop(client), 0)
aioquic.quic.connection/QuicConnection._handle_new_connection_id_frame
Modified
aiortc~aioquic
7be069c1eaae0bbe776913b057b8d269d7c8c0de
[connection] handle NEW_CONNECTION_ID with "Retire Prior To"
<20>:<add> # determine which CIDs to retire <add> change_cid = False <add> retire = list( <add> filter( <add> lambda c: c.sequence_number < retire_prior_to, self._peer_cid_available <add> ) <add> ) <add> if self._peer_cid.sequence_number < retire_prior_to: <add> change_cid = True <add> retire.insert(0, self._peer_cid) <add> <add> # update available CIDs <add> self._peer_cid_available = list( <del> self._peer_cid_available.append( <21>:<add> filter( <add> lambda c: c.sequence_number >= retire_prior_to, self._peer_cid_available <add> ) <add> ) + [ <26>:<add> ] <del> )
# module: aioquic.quic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a NEW_CONNECTION_ID frame. <2> """ <3> sequence_number = buf.pull_uint_var() <4> retire_prior_to = buf.pull_uint_var() <5> length = buf.pull_uint8() <6> connection_id = buf.pull_bytes(length) <7> stateless_reset_token = buf.pull_bytes(16) <8> <9> # log frame <10> if self._quic_logger is not None: <11> context.quic_logger_frames.append( <12> self._quic_logger.encode_new_connection_id_frame( <13> connection_id=connection_id, <14> retire_prior_to=retire_prior_to, <15> sequence_number=sequence_number, <16> stateless_reset_token=stateless_reset_token, <17> ) <18> ) <19> <20> self._peer_cid_available.append( <21> QuicConnectionId( <22> cid=connection_id, <23> sequence_number=sequence_number, <24> stateless_reset_token=stateless_reset_token, <25> ) <26> ) <27>
===========unchanged ref 0=========== at: aioquic.quic.connection QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _unblock_streams(is_unidirectional: bool) -> 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=self._original_destination_connection_id, ) self._remote_max_streams_uni = 0 self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._handle_max_streams_uni_frame max_streams = buf.pull_uint_var() at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float 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 ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _connect(self, now: float) -> None: """ Start the client handshake. """ assert self._is_client self._close_at = now + self._configuration.idle_timeout + self._initialize(self._peer_cid.cid) - self._initialize(self._peer_cid) self.tls.handle_message(b"", self._crypto_buffers) self._push_crypto_data() ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: + def _consume_peer_cid(self) -> None: + """ + Update the destination connection ID by taking the next + available connection ID provided by the peer. + """ + + self._peer_cid = self._peer_cid_available.pop(0) + self._logger.debug( + "Switching to CID %s (%d)", + dump_cid(self._peer_cid.cid), + self._peer_cid.sequence_number, + ) + ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): client = create_standalone_client(self) # found a common version, retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[client._version], ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_receive_datagram_retry_wrong_destination_cid(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( version=client._version, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), + original_destination_cid=client._peer_cid.cid, - original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(2) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 2) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [3, 4, 5, 6, 7, 8] + ) + ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_fail(self): client = create_standalone_client(self) # no common version, no retry client.receive_datagram( encode_quic_version_negotiation( + source_cid=client._peer_cid.cid, - source_cid=client._peer_cid, destination_cid=client.host_cid, supported_versions=[0xFF000011], # DRAFT_16 ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual( event.reason_phrase, "Could not find a common protocol version" )
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
1bff1ea3e4ba7985b3e90e3d38a69bf9a064dab2
[connection] associate reset token with initial connection ID
<40>:<add> self.assertEqual(datagram_sizes(items), [1280, 1068]) <del> self.assertEqual(datagram_sizes(items),
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): <0> """ <1> Check connection is established even in the client's INITIAL is lost. <2> """ <3> <4> def datagram_sizes(items): <5> return [len(x[0]) for x in items] <6> <7> client_configuration = QuicConfiguration(is_client=True) <8> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <9> <10> client = QuicConnection(configuration=client_configuration) <11> client._ack_delay = 0 <12> <13> server_configuration = QuicConfiguration(is_client=False) <14> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <15> <16> server = QuicConnection( <17> configuration=server_configuration, <18> original_destination_connection_id=client.original_destination_connection_id, <19> ) <20> server._ack_delay = 0 <21> <22> # client sends INITIAL <23> now = 0.0 <24> client.connect(SERVER_ADDR, now=now) <25> items = client.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280]) <27> self.assertEqual(client.get_timer(), 0.2) <28> <29> # INITIAL is lost <30> now = client.get_timer() <31> client.handle_timer(now=now) <32> items = client.datagrams_to_send(now=now) <33> self.assertEqual(datagram_sizes(items), [1280]) <34> self.assertAlmostEqual(client.get_timer(), 0.6) <35> <36> # server receives INITIAL, sends INITIAL + HANDSHAKE <37> now += TICK <38> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <39> items = server.datagrams_to_send(now=now) <40> self.assertEqual(datagram_sizes(items),</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 self.assertAlmostEqual(server.get_timer(), 0.45) self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # handshake continues normally now += TICK client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 0.625) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 0.625) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now += TICK client.receive_datagram</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>(server.next_event()), events.ConnectionIdIssued) now += TICK client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 60.4) # idle timeout ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
1bff1ea3e4ba7985b3e90e3d38a69bf9a064dab2
[connection] associate reset token with initial connection ID
<29>:<add> self.assertEqual(datagram_sizes(items), [1280, 1068]) <del> self.assertEqual(datagram_sizes(items), [1280, 1050])
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 0.2) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <26> now += TICK <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 0.25) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client only receives first datagram and sends ACKS <35> now += TICK <36> client.receive_datagram(items[0][0</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [97]) self.assertAlmostEqual(client.get_timer(), 0.325) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertIsNone(client.next_event()) # client PTO - HANDSHAKE PING now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [45]) self.assertAlmostEqual(client.get_timer(), 0.975) # server receives PING, discards INITIAL and sends ACK now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [48]) self.assertAlmostEqual(server.get_timer(), 0.25) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertIsNone(server.next_event()) # ACKs are lost, server retransmits HANDSHAKE now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280, 874]) self.assertAlmostEqual(server.get_timer(), 0.65) self.assertEqual(len(server._loss.spaces[0</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s>AlmostEqual(server.get_timer(), 0.65) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 3) self.assertIsNone(server.next_event()) # handshake continues normally now += TICK client.receive_datagram(items[0][0], SERVER_ADDR, now=now) client.receive_datagram(items[1][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [329]) self.assertAlmostEqual(client.get_timer(), 0.95) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 0.675) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) now += TICK client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_ ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertEqual(client.get_timer(), 0.2) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 0.6) # server receives INITIAL, sends INITIAL + HANDSHAKE now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) + self.assertEqual(datagram_sizes(items), [1280, 1068]) - self.assertEqual(datagram_sizes(items), [1280, 1050]) self.assertAlmostEqual(server.</s>
tests.test_connection/QuicConnectionTest.test_connect_with_loss_3
Modified
aiortc~aioquic
1bff1ea3e4ba7985b3e90e3d38a69bf9a064dab2
[connection] associate reset token with initial connection ID
<29>:<add> self.assertEqual(datagram_sizes(items), [1280, 1068]) <del> self.assertEqual(datagram_sizes(items), [1280, 1050])
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): <0> def datagram_sizes(items): <1> return [len(x[0]) for x in items] <2> <3> client_configuration = QuicConfiguration(is_client=True) <4> client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) <5> <6> client = QuicConnection(configuration=client_configuration) <7> client._ack_delay = 0 <8> <9> server_configuration = QuicConfiguration(is_client=False) <10> server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) <11> <12> server = QuicConnection( <13> configuration=server_configuration, <14> original_destination_connection_id=client.original_destination_connection_id, <15> ) <16> server._ack_delay = 0 <17> <18> # client sends INITIAL <19> now = 0.0 <20> client.connect(SERVER_ADDR, now=now) <21> items = client.datagrams_to_send(now=now) <22> self.assertEqual(datagram_sizes(items), [1280]) <23> self.assertEqual(client.get_timer(), 0.2) <24> <25> # server receives INITIAL, sends INITIAL + HANDSHAKE <26> now += TICK <27> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <28> items = server.datagrams_to_send(now=now) <29> self.assertEqual(datagram_sizes(items), [1280, 1050]) <30> self.assertEqual(server.get_timer(), 0.25) <31> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <32> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <33> <34> # client receives INITIAL + HANDSHAKE <35> now += TICK <36> client.receive_datagram(items[0][0], SERVER_ADDR, now=now)</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 1 items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [376]) self.assertAlmostEqual(client.get_timer(), 0.425) self.assertEqual(type(client.next_event()), events.ProtocolNegotiated) self.assertEqual(type(client.next_event()), events.HandshakeCompleted) self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) # server completes handshake now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [229]) self.assertAlmostEqual(server.get_timer(), 0.425) self.assertEqual(len(server._loss.spaces[0].sent_packets), 0) self.assertEqual(len(server._loss.spaces[1].sent_packets), 0) self.assertEqual(type(server.next_event()), events.ProtocolNegotiated) self.assertEqual(type(server.next_event()), events.HandshakeCompleted) self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) # server PTO - 1-RTT PING now = server.get_timer() server.handle_timer(now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [29]) self.assertAlmostEqual(server.get_timer(), 0.975) # client receives PING, sends ACK now += TICK client.receive_datagram(items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_3(self): # offset: 2 <s>items[0][0], SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [32]) self.assertAlmostEqual(client.get_timer(), 0.425) # server receives ACK, retransmits HANDSHAKE_DONE now += TICK self.assertFalse(server._handshake_done_pending) server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) self.assertTrue(server._handshake_done_pending) items = server.datagrams_to_send(now=now) self.assertFalse(server._handshake_done_pending) self.assertEqual(datagram_sizes(items), [224]) ===========unchanged ref 0=========== at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) TICK = 0.05 # seconds at: tests.utils SERVER_CACERTFILE = os.path.join(os.path.dirname(__file__), "pycacert.pem") SERVER_CERTFILE = os.path.join(os.path.dirname(__file__), "ssl_cert.pem") SERVER_KEYFILE = os.path.join(os.path.dirname(__file__), "ssl_key.pem") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertEqual(client.get_timer(), 0.2) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 0.6) # server receives INITIAL, sends INITIAL + HANDSHAKE now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) + self.assertEqual(datagram_sizes(items), [1280, 1068]) - self.assertEqual(datagram_sizes(items), [1280, 1050]) self.assertAlmostEqual(server.</s>
aioquic.quic.connection/QuicConnection._parse_transport_parameters
Modified
aiortc~aioquic
1bff1ea3e4ba7985b3e90e3d38a69bf9a064dab2
[connection] associate reset token with initial connection ID
# module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: <0> """ <1> Parse and apply remote transport parameters. <2> <3> `from_session_ticket` is `True` when restoring saved transport parameters, <4> and `False` when handling received transport parameters. <5> """ <6> <7> quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) <8> <9> # log event <10> if self._quic_logger is not None and not from_session_ticket: <11> self._quic_logger.log_event( <12> category="transport", <13> event="parameters_set", <14> data=self._quic_logger.encode_transport_parameters( <15> owner="remote", parameters=quic_transport_parameters <16> ), <17> ) <18> <19> # validate remote parameters <20> if not self._is_client: <21> for attr in [ <22> "original_destination_connection_id", <23> "preferred_address", <24> "retry_source_connection_id", <25> "stateless_reset_token", <26> ]: <27> if getattr(quic_transport_parameters, attr) is not None: <28> raise QuicConnectionError( <29> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, <30> frame_type=QuicFrameType.CRYPTO, <31> reason_phrase="%s is not allowed for clients" % attr, <32> ) <33> <34> if not from_session_ticket: <35> if self._is_client and ( <36> quic_transport_parameters.original_destination_connection_id <37> != self._original_destination_connection_id <38> ): <39> raise QuicConnectionError( <40> error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, <41> frame_type=QuicFrameType.CRYPTO, <42> reason_phrase="original_destination_connection_id does not match", <43> ) </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 quic_transport_parameters.retry_source_connection_id != self._retry_source_connection_id ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="retry_source_connection_id does not match", ) if ( quic_transport_parameters.active_connection_id_limit is not None and quic_transport_parameters.active_connection_id_limit < 2 ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="active_connection_id_limit must be no less than 2", ) # store remote parameters if not from_session_ticket: if quic_transport_parameters.ack_delay_exponent is not None: self._remote_ack_delay_exponent = self._remote_ack_delay_exponent if quic_transport_parameters.max_ack_delay is not None: self._loss.max_ack_delay = ( quic_transport_parameters.max_ack_delay / 1000.0 ) 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.max_idle_timeout is not None: self._remote_max_idle_timeout = ( quic_transport_parameters.max_idle_timeout / 1000.0 ) self._remote_max_datagram_frame_size = ( quic_transport_parameters.max_datagram_frame_size ) for param in</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: # offset: 2 <s>frame_size = ( quic_transport_parameters.max_datagram_frame_size ) 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.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._peer_cid = QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=None ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._remote_ack_delay_exponent = 3 self._remote_active_connection_id_limit = 2 self._remote_max_idle_timeout = 0.0 # seconds self._remote_max_datagram_frame_size: Optional[int] = None self._retry_source_connection_id = retry_source_connection_id self._original_destination_connection_id = ( original_destination_connection_id ) self._original_destination_connection_id = self._peer_cid.cid self._loss = QuicPacketRecovery( initial_rtt=configuration.initial_rtt, peer_completed_address_validation=not 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._consume_peer_cid self._peer_cid = self._peer_cid_available.pop(0) at: aioquic.quic.connection.QuicConnection.receive_datagram self._retry_source_connection_id = header.source_cid ===========unchanged ref 1=========== at: aioquic.quic.connection.QuicConnectionId cid: bytes sequence_number: int stateless_reset_token: bytes = b"" was_sent: bool = False ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): """ Check connection is established even in the client's INITIAL is lost. """ def datagram_sizes(items): return [len(x[0]) for x in items] client_configuration = QuicConfiguration(is_client=True) client_configuration.load_verify_locations(cafile=SERVER_CACERTFILE) client = QuicConnection(configuration=client_configuration) client._ack_delay = 0 server_configuration = QuicConfiguration(is_client=False) server_configuration.load_cert_chain(SERVER_CERTFILE, SERVER_KEYFILE) server = QuicConnection( configuration=server_configuration, original_destination_connection_id=client.original_destination_connection_id, ) server._ack_delay = 0 # client sends INITIAL now = 0.0 client.connect(SERVER_ADDR, now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertEqual(client.get_timer(), 0.2) # INITIAL is lost now = client.get_timer() client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 0.6) # server receives INITIAL, sends INITIAL + HANDSHAKE now += TICK server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) + self.assertEqual(datagram_sizes(items), [1280, 1068]) - self.assertEqual(datagram_sizes(items), [1280, 1050]) self.assertAlmostEqual(server.</s>
aioquic.quic.connection/QuicConnection._serialize_transport_parameters
Modified
aiortc~aioquic
1bff1ea3e4ba7985b3e90e3d38a69bf9a064dab2
[connection] associate reset token with initial connection ID
<16>:<add> stateless_reset_token=self._host_cids[0].stateless_reset_token,
# 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> max_idle_timeout=int(self._configuration.idle_timeout * 1000), <4> initial_max_data=self._local_max_data.value, <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.value, <9> initial_max_streams_uni=self._local_max_streams_uni.value, <10> initial_source_connection_id=self._local_initial_source_connection_id, <11> max_ack_delay=25, <12> max_datagram_frame_size=self._configuration.max_datagram_frame_size, <13> quantum_readiness=b"Q" * 1200 <14> if self._configuration.quantum_readiness_test <15> else None, <16> ) <17> if not self._is_client and ( <18> self._version >= QuicProtocolVersion.DRAFT_28 <19> or self._retry_source_connection_id <20> ): <21> quic_transport_parameters.original_destination_connection_id = ( <22> self._original_destination_connection_id <23> ) <24> quic_transport_parameters.retry_source_connection_id = ( <25> self._retry_source_connection_id <26> ) <27> <28> # log event <29> if self._quic_logger is not None: <30> self._qu</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _serialize_transport_parameters(self) -> bytes: # offset: 1 category="transport", event="parameters_set", data=self._quic_logger.encode_transport_parameters( owner="local", parameters=quic_transport_parameters ), ) buf = Buffer(capacity=3 * PACKET_MAX_SIZE) push_quic_transport_parameters(buf, quic_transport_parameters) return buf.data ===========unchanged ref 0=========== at: aioquic.quic.connection.Limit.__init__ self.value = value at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration self._is_client = configuration.is_client self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os.urandom(16) if not self._is_client else None, was_sent=True, ) ] self._local_ack_delay_exponent = 3 self._local_active_connection_id_limit = 8 self._local_initial_source_connection_id = self._host_cids[0].cid self._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._local_max_stream_data_bidi_local = configuration.max_stream_data self._local_max_stream_data_bidi_remote = configuration.max_stream_data self._local_max_stream_data_uni = configuration.max_stream_data self._local_max_streams_bidi = Limit( frame_type=QuicFrameType.MAX_STREAMS_BIDI, name="max_streams_bidi", value=128, ) self._local_max_streams_uni = Limit( frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128 ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) ===========unchanged ref 1=========== self._retry_source_connection_id = retry_source_connection_id self._version: Optional[int] = None self._original_destination_connection_id = ( original_destination_connection_id ) self._original_destination_connection_id = self._peer_cid.cid at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._parse_transport_parameters quic_transport_parameters = pull_quic_transport_parameters(Buffer(data=data)) at: aioquic.quic.connection.QuicConnection.connect self._version = self._configuration.supported_versions[0] at: aioquic.quic.connection.QuicConnection.receive_datagram self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self._retry_source_connection_id = header.source_cid at: aioquic.quic.connection.QuicConnectionId stateless_reset_token: bytes = b"" ===========changed ref 0=========== # module: aioquic.quic.connection class QuicConnection: def _parse_transport_parameters( self, data: bytes, from_session_ticket: bool = False ) -> None: """ Parse and apply remote transport parameters. `from_session_ticket` is `True` when restoring saved transport parameters, and `False` when handling received transport parameters. """ 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", data=self._quic_logger.encode_transport_parameters( owner="remote", parameters=quic_transport_parameters ), ) # validate remote parameters if not self._is_client: for attr in [ "original_destination_connection_id", "preferred_address", "retry_source_connection_id", "stateless_reset_token", ]: if getattr(quic_transport_parameters, attr) is not None: raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="%s is not allowed for clients" % attr, ) if not from_session_ticket: if self._is_client and ( quic_transport_parameters.original_destination_connection_id != self._original_destination_connection_id ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="original_destination_connection_id does not match", ) if self._is_client and ( quic_transport_parameters.retry_source_connection_id != self._retry_source_connection_id ): raise</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.retry_source_connection_id != self._retry_source_connection_id ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="retry_source_connection_id does not match", ) if ( quic_transport_parameters.active_connection_id_limit is not None and quic_transport_parameters.active_connection_id_limit < 2 ): raise QuicConnectionError( error_code=QuicErrorCode.TRANSPORT_PARAMETER_ERROR, frame_type=QuicFrameType.CRYPTO, reason_phrase="active_connection_id_limit must be no less than 2", ) + if ( + self._is_client + and self._peer_cid.sequence_number == 0 + and quic_transport_parameters.stateless_reset_token is not None + ): + self._peer_cid.stateless_reset_token = ( + quic_transport_parameters.stateless_reset_token + ) # store remote parameters if not from_session_ticket: if quic_transport_parameters.ack_delay_exponent is not None: self._remote_ack_delay_exponent = self._remote_ack_delay_exponent if quic_transport_parameters.max_ack_delay is not None: self._loss.max_ack_delay = ( quic_transport_parameters.max_ack_delay / 1000.0 ) if quic_transport_parameters.active_connection_id_limit is not None: self._remote_active_connection</s>
aioquic.quic.connection/QuicConnection._handle_new_connection_id_frame
Modified
aiortc~aioquic
69fa25544ff7f328b0faf42831a793783b3d248a
[connection] add sanity check on Retire Prior To
<18>:<add> ) <add> <add> # sanity check <add> if retire_prior_to > sequence_number: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <add> frame_type=frame_type, <add> reason_phrase="retire_prior_to is greater than the sequence_number",
# module: aioquic.quic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a NEW_CONNECTION_ID frame. <2> """ <3> sequence_number = buf.pull_uint_var() <4> retire_prior_to = buf.pull_uint_var() <5> length = buf.pull_uint8() <6> connection_id = buf.pull_bytes(length) <7> stateless_reset_token = buf.pull_bytes(16) <8> <9> # log frame <10> if self._quic_logger is not None: <11> context.quic_logger_frames.append( <12> self._quic_logger.encode_new_connection_id_frame( <13> connection_id=connection_id, <14> retire_prior_to=retire_prior_to, <15> sequence_number=sequence_number, <16> stateless_reset_token=stateless_reset_token, <17> ) <18> ) <19> <20> # determine which CIDs to retire <21> change_cid = False <22> retire = list( <23> filter( <24> lambda c: c.sequence_number < retire_prior_to, self._peer_cid_available <25> ) <26> ) <27> if self._peer_cid.sequence_number < retire_prior_to: <28> change_cid = True <29> retire.insert(0, self._peer_cid) <30> <31> # update available CIDs <32> self._peer_cid_available = list( <33> filter( <34> lambda c: c.sequence_number >= retire_prior_to, self._peer_cid_available <35> ) <36> ) + [ <37> QuicConnectionId( <38> cid=connection_id, <39> sequence_number=sequence_number, <40> stateless_reset_token=stateless_reset_token, <41> ) <42> ] <43> <44> #</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 for quic_connection_id in retire: self._retire_peer_cid(quic_connection_id) # assign new CID if we retired the active one if change_cid: self._consume_peer_cid() # check number of active connection IDs, including the selected one if 1 + len(self._peer_cid_available) > self._local_active_connection_id_limit: raise QuicConnectionError( error_code=QuicErrorCode.CONNECTION_ID_LIMIT_ERROR, frame_type=frame_type, reason_phrase="Too many active connection IDs", ) ===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _consume_peer_cid() -> None _retire_peer_cid(connection_id: QuicConnectionId) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._peer_cid = QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=None ) self._peer_cid_available: List[QuicConnectionId] = [] self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._consume_peer_cid self._peer_cid = self._peer_cid_available.pop(0) at: aioquic.quic.connection.QuicConnectionId cid: bytes sequence_number: int stateless_reset_token: bytes = b"" was_sent: bool = False at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_with_retire_prior_to_invalid(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(8) # sequence_number + buf.push_uint_var(9) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_new_connection_id_frame( + client_receive_context(client), + QuicFrameType.NEW_CONNECTION_ID, + buf, + ) + self.assertEqual( + cm.exception.error_code, QuicErrorCode.PROTOCOL_VIOLATION, + ) + self.assertEqual(cm.exception.frame_type, QuicFrameType.NEW_CONNECTION_ID) + self.assertEqual( + cm.exception.reason_phrase, + "retire_prior_to is greater than the sequence_number", + ) +
aioquic.quic.connection/QuicConnection._handle_new_connection_id_frame
Modified
aiortc~aioquic
87e488adee1ecd6e9657a38ac9b3292ff463fcb7
[connection] don't add a connection ID twice
# module: aioquic.quic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a NEW_CONNECTION_ID frame. <2> """ <3> sequence_number = buf.pull_uint_var() <4> retire_prior_to = buf.pull_uint_var() <5> length = buf.pull_uint8() <6> connection_id = buf.pull_bytes(length) <7> stateless_reset_token = buf.pull_bytes(16) <8> <9> # log frame <10> if self._quic_logger is not None: <11> context.quic_logger_frames.append( <12> self._quic_logger.encode_new_connection_id_frame( <13> connection_id=connection_id, <14> retire_prior_to=retire_prior_to, <15> sequence_number=sequence_number, <16> stateless_reset_token=stateless_reset_token, <17> ) <18> ) <19> <20> # sanity check <21> if retire_prior_to > sequence_number: <22> raise QuicConnectionError( <23> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <24> frame_type=frame_type, <25> reason_phrase="retire_prior_to is greater than the sequence_number", <26> ) <27> <28> # determine which CIDs to retire <29> change_cid = False <30> retire = list( <31> filter( <32> lambda c: c.sequence_number < retire_prior_to, self._peer_cid_available <33> ) <34> ) <35> if self._peer_cid.sequence_number < retire_prior_to: <36> change_cid = True <37> retire.insert(0, self._peer_cid) <38> <39> # update available CIDs <40> self._peer_cid_available = list( <41> filter( <42> lambda c: c.sequence_number</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_new_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 ) ) + [ QuicConnectionId( cid=connection_id, sequence_number=sequence_number, stateless_reset_token=stateless_reset_token, ) ] # retire previous CIDs for quic_connection_id in retire: self._retire_peer_cid(quic_connection_id) # assign new CID if we retired the active one if change_cid: self._consume_peer_cid() # check number of active connection IDs, including the selected one if 1 + len(self._peer_cid_available) > self._local_active_connection_id_limit: raise QuicConnectionError( error_code=QuicErrorCode.CONNECTION_ID_LIMIT_ERROR, frame_type=frame_type, reason_phrase="Too many active connection IDs", ) ===========unchanged ref 0=========== at: aioquic.quic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False) QuicReceiveContext(epoch: tls.Epoch, host_cid: bytes, network_path: QuicNetworkPath, quic_logger_frames: Optional[List[Any]], time: float) at: aioquic.quic.connection.QuicConnection _consume_peer_cid() -> None _retire_peer_cid(connection_id: QuicConnectionId) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._local_active_connection_id_limit = 8 self._peer_cid = QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=None ) self._peer_cid_available: List[QuicConnectionId] = [] self._peer_cid_sequence_numbers: Set[int] = set([0]) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._consume_peer_cid self._peer_cid = self._peer_cid_available.pop(0) at: aioquic.quic.connection.QuicConnectionId cid: bytes sequence_number: int stateless_reset_token: bytes = b"" was_sent: bool = False at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch ===========unchanged ref 1=========== host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_new_connection_id_duplicate(self): + with client_and_server() as (client, server): + buf = Buffer(capacity=100) + buf.push_uint_var(7) # sequence_number + buf.push_uint_var(0) # retire_prior_to + buf.push_uint_var(8) + buf.push_bytes(bytes(8)) + buf.push_bytes(bytes(16)) + buf.seek(0) + + # client receives NEW_CONNECTION_ID + client._handle_new_connection_id_frame( + client_receive_context(client), QuicFrameType.NEW_CONNECTION_ID, buf, + ) + + self.assertEqual(client._peer_cid.sequence_number, 0) + self.assertEqual( + sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_destination_connection_id: Optional[bytes] = None, retry_source_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: if configuration.is_client: assert ( original_destination_connection_id is None ), "Cannot set original_destination_connection_id for a client" assert ( retry_source_connection_id is None ), "Cannot set retry_source_connection_id for a client" else: assert ( configuration.certificate is not None ), "SSL certificate is required for a server" assert ( configuration.private_key is not None ), "SSL private key is required for a server" assert ( original_destination_connection_id is not None ), "original_destination_connection_id is required for a server" # configuration self._configuration = configuration self._is_client = configuration.is_client self._ack_delay = K_GRANULARITY self._close_at: Optional[float] = None self._close_event: Optional[events.ConnectionTerminated] = None self._connect_called = False self._cryptos: Dict[tls.Epoch, CryptoPair] = {} 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._handshake_confirmed = False self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os</s>
aioquic.quic.connection/QuicConnection._handle_retire_connection_id_frame
Modified
aiortc~aioquic
b9b8846fa3fd7c7256d46ae3cb826e81e0abe156
[connection] check RETIRE_CONNECTION_ID sequence number is sane
<9>:<add> ) <add> <add> if sequence_number >= self._host_cid_seq: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <add> frame_type=frame_type, <add> reason_phrase="Cannot retire unknown connection ID",
# module: aioquic.quic.connection class QuicConnection: def _handle_retire_connection_id_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a RETIRE_CONNECTION_ID frame. <2> """ <3> sequence_number = buf.pull_uint_var() <4> <5> # log frame <6> if self._quic_logger is not None: <7> context.quic_logger_frames.append( <8> self._quic_logger.encode_retire_connection_id_frame(sequence_number) <9> ) <10> <11> # find the connection ID by sequence number <12> for index, connection_id in enumerate(self._host_cids): <13> if connection_id.sequence_number == sequence_number: <14> if connection_id.cid == context.host_cid: <15> raise QuicConnectionError( <16> error_code=QuicErrorCode.PROTOCOL_VIOLATION, <17> frame_type=frame_type, <18> reason_phrase="Cannot retire current connection ID", <19> ) <20> self._logger.debug( <21> "Peer retiring CID %s (%d)", <22> dump_cid(connection_id.cid), <23> connection_id.sequence_number, <24> ) <25> del self._host_cids[index] <26> self._events.append( <27> events.ConnectionIdRetired(connection_id=connection_id.cid) <28> ) <29> break <30> <31> # issue a new connection ID <32> self._replenish_connection_ids() <33>
===========unchanged ref 0=========== at: aioquic.quic.connection dump_cid(cid: bytes) -> str 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.__init__ self._host_cids = [ QuicConnectionId( cid=os.urandom(configuration.connection_id_length), sequence_number=0, stateless_reset_token=os.urandom(16) if not self._is_client else None, was_sent=True, ) ] self._host_cid_seq = 1 self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicConnection._replenish_connection_ids self._host_cid_seq += 1 at: aioquic.quic.connection.QuicConnectionId cid: bytes sequence_number: int stateless_reset_token: bytes = b"" was_sent: bool = False at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float at: logging.LoggerAdapter logger: Logger ===========unchanged ref 1=========== extra: Mapping[str, Any] debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_retire_connection_id_frame_invalid_sequence_number(self): + with client_and_server() as (client, server): + self.assertEqual( + sequence_numbers(client._host_cids), [0, 1, 2, 3, 4, 5, 6, 7] + ) + + # client receives RETIRE_CONNECTION_ID + with self.assertRaises(QuicConnectionError) as cm: + client._handle_retire_connection_id_frame( + client_receive_context(client), + QuicFrameType.RETIRE_CONNECTION_ID, + Buffer(data=b"\x08"), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.PROTOCOL_VIOLATION) + self.assertEqual( + cm.exception.frame_type, QuicFrameType.RETIRE_CONNECTION_ID + ) + self.assertEqual( + cm.exception.reason_phrase, "Cannot retire unknown connection ID" + ) + self.assertEqual( + sequence_numbers(client._host_cids), [0, 1, 2, 3, 4, 5, 6, 7] + ) +
aioquic.asyncio.server/QuicServer.__init__
Modified
aiortc~aioquic
dcb4f64124decb2a41e4cff645a25c3c989c6906
Do not use "stateless retry" terminology
<10>:<add> if retry: <del> if stateless_retry:
<s>class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, + retry: bool = False, - stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: <0> self._configuration = configuration <1> self._create_protocol = create_protocol <2> self._loop = asyncio.get_event_loop() <3> self._protocols: Dict[bytes, QuicConnectionProtocol] = {} <4> self._session_ticket_fetcher = session_ticket_fetcher <5> self._session_ticket_handler = session_ticket_handler <6> self._transport: Optional[asyncio.DatagramTransport] = None <7> <8> self._stream_handler = stream_handler <9> <10> if stateless_retry: <11> self._retry = QuicRetryTokenHandler() <12> else: <13> self._retry = None <14>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.server.QuicServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: asyncio.events get_event_loop() -> 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') ===========changed ref 0=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry(self): - run(self.run_server()) - response = run(self.run_client()) - self.assertEqual(response, b"gnip") - ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry(self): - run(self.run_server()) - response = run(self.run_client()) - self.assertEqual(response, b"gnip") - ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") + def test_connect_and_serve_with_retry_bad_token(self, mock_validate): + mock_validate.side_effect = ValueError("Decryption failed.") + + run(self.run_server(retry=True)) + with self.assertRaises(ConnectionError): + run( + self.run_client( + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) + ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") - def test_connect_and_serve_with_stateless_retry_bad_token(self, mock_validate): - mock_validate.side_effect = ValueError("Decryption failed.") - - run(self.run_server(stateless_retry=True)) - with self.assertRaises(ConnectionError): - run( - self.run_client( - configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), - ) - ) - ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_with_retry_bad_retry_source_connection_id(self): + """ + If the server's transport parameters do not have the correct + retry_source_connection_id the connection must fail. + """ + + def create_protocol(*args, **kwargs): + protocol = QuicConnectionProtocol(*args, **kwargs) + protocol._quic._retry_source_connection_id = None + return protocol + + run(self.run_server(create_protocol=create_protocol, retry=True)) + with self.assertRaises(ConnectionError): + run(self.run_client()) + ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_with_retry_bad_original_destination_connection_id(self): + """ + If the server's transport parameters do not have the correct + original_destination_connection_id the connection must fail. + """ + + def create_protocol(*args, **kwargs): + protocol = QuicConnectionProtocol(*args, **kwargs) + protocol._quic._original_destination_connection_id = None + return protocol + + run(self.run_server(create_protocol=create_protocol, retry=True)) + with self.assertRaises(ConnectionError): + run(self.run_client()) + ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry_bad_retry_source_connection_id( - self, - ): - """ - If the server's transport parameters do not have the correct - retry_source_connection_id the connection must fail. - """ - - def create_protocol(*args, **kwargs): - protocol = QuicConnectionProtocol(*args, **kwargs) - protocol._quic._retry_source_connection_id = None - return protocol - - run(self.run_server(create_protocol=create_protocol, stateless_retry=True)) - with self.assertRaises(ConnectionError): - run(self.run_client()) - ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry_bad_original_destination_connection_id( - self, - ): - """ - If the server's transport parameters do not have the correct - original_destination_connection_id the connection must fail. - """ - - def create_protocol(*args, **kwargs): - protocol = QuicConnectionProtocol(*args, **kwargs) - protocol._quic._original_destination_connection_id = None - return protocol - - run(self.run_server(create_protocol=create_protocol, stateless_retry=True)) - with self.assertRaises(ConnectionError): - run(self.run_client()) - ===========changed ref 8=========== # module: examples.interop - def test_stateless_retry(server: Server, configuration: QuicConfiguration): - # skip test if there is not retry port - if server.retry_port is None: - return - - async with connect( - server.host, server.retry_port, configuration=configuration - ) as protocol: - await protocol.ping() - - # check log - for stamp, category, event, data in configuration.quic_logger.to_dict()[ - "traces" - ][0]["events"]: - if ( - category == "transport" - and event == "packet_received" - and data["packet_type"] == "retry" - ): - server.result |= Result.S - ===========changed ref 9=========== # module: examples.interop - def test_stateless_retry(server: Server, configuration: QuicConfiguration): - # skip test if there is not retry port - if server.retry_port is None: - return - - async with connect( - server.host, server.retry_port, configuration=configuration - ) as protocol: - await protocol.ping() - - # check log - for stamp, category, event, data in configuration.quic_logger.to_dict()[ - "traces" - ][0]["events"]: - if ( - category == "transport" - and event == "packet_received" - and data["packet_type"] == "retry" - ): - server.result |= Result.S -
aioquic.asyncio.server/serve
Modified
aiortc~aioquic
dcb4f64124decb2a41e4cff645a25c3c989c6906
Do not use "stateless retry" terminology
<18>:<add> * ``retry`` specifies whether client addresses should be validated prior to <add> the cryptographic handshake using a retry packet. <del> * ``stateless_retry`` specifies whether a stateless retry should be <19>:<del> performed prior to handling new connections.
<s>: aioquic.asyncio.server def serve( host: str, port: int, *, configuration: QuicConfiguration, create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, + retry: bool = False, - stateless_retry: bool = False, stream_handler: QuicStreamHandler = None, ) -> QuicServer: <0> """ <1> Start a QUIC server at the given `host` and `port`. <2> <3> :func:`serve` requires a :class:`~aioquic.quic.configuration.QuicConfiguration` <4> containing TLS certificate and private key as the ``configuration`` argument. <5> <6> :func:`serve` also accepts the following optional arguments: <7> <8> * ``create_protocol`` allows customizing the :class:`~asyncio.Protocol` that <9> manages the connection. It should be a callable or class accepting the same <10> arguments as :class:`~aioquic.asyncio.QuicConnectionProtocol` and returning <11> an instance of :class:`~aioquic.asyncio.QuicConnectionProtocol` or a subclass. <12> * ``session_ticket_fetcher`` is a callback which is invoked by the TLS <13> engine when a session ticket is presented by the peer. It should return <14> the session ticket with the specified ID or `None` if it is not found. <15> * ``session_ticket_handler`` is a callback which is invoked by the TLS <16> engine when a new session ticket is issued. It should store the session <17> ticket for future lookup. <18> * ``stateless_retry`` specifies whether a stateless retry should be <19> performed prior to handling new connections. <20> * ``stream_handler`` is a callback which is invoked whenever a stream is <21> created. It must accept two arguments: a :class:`asyncio.StreamReader` <22> and a :class:`asyncio.StreamWriter`. <23> """ <24> <25> loop = asyncio.get_event_loop() <26> </s>
===========below chunk 0=========== <s>asyncio.server def serve( host: str, port: int, *, configuration: QuicConfiguration, create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, + retry: bool = False, - stateless_retry: bool = False, stream_handler: QuicStreamHandler = None, ) -> QuicServer: # offset: 1 lambda: QuicServer( configuration=configuration, create_protocol=create_protocol, session_ticket_fetcher=session_ticket_fetcher, session_ticket_handler=session_ticket_handler, stateless_retry=stateless_retry, stream_handler=stream_handler, ), local_addr=(host, port), ) return cast(QuicServer, protocol) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.asyncio.server QuicServer(*, configuration: QuicConfiguration, create_protocol: Callable=QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, retry: bool=False, stream_handler: Optional[QuicStreamHandler]=None) at: asyncio.events get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop create_datagram_endpoint(protocol_factory: _ProtocolFactory, local_addr: Optional[Tuple[str, int]]=..., remote_addr: Optional[Tuple[str, int]]=..., *, family: int=..., proto: int=..., flags: int=..., reuse_address: Optional[bool]=..., reuse_port: Optional[bool]=..., allow_broadcast: Optional[bool]=..., sock: Optional[socket]=...) -> _TransProtPair at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any Callable = _CallableType(collections.abc.Callable, 2) ===========changed ref 0=========== <s>class QuicServer(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, create_protocol: Callable = QuicConnectionProtocol, session_ticket_fetcher: Optional[SessionTicketFetcher] = None, session_ticket_handler: Optional[SessionTicketHandler] = None, + retry: bool = False, - stateless_retry: bool = False, stream_handler: Optional[QuicStreamHandler] = None, ) -> None: self._configuration = configuration self._create_protocol = create_protocol self._loop = asyncio.get_event_loop() self._protocols: Dict[bytes, QuicConnectionProtocol] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler self._transport: Optional[asyncio.DatagramTransport] = None self._stream_handler = stream_handler + if retry: - if stateless_retry: self._retry = QuicRetryTokenHandler() else: self._retry = None ===========changed ref 1=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry(self): - run(self.run_server()) - response = run(self.run_client()) - self.assertEqual(response, b"gnip") - ===========changed ref 2=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry(self): - run(self.run_server()) - response = run(self.run_client()) - self.assertEqual(response, b"gnip") - ===========changed ref 3=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") + def test_connect_and_serve_with_retry_bad_token(self, mock_validate): + mock_validate.side_effect = ValueError("Decryption failed.") + + run(self.run_server(retry=True)) + with self.assertRaises(ConnectionError): + run( + self.run_client( + configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), + ) + ) + ===========changed ref 4=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - @patch("aioquic.quic.retry.QuicRetryTokenHandler.validate_token") - def test_connect_and_serve_with_stateless_retry_bad_token(self, mock_validate): - mock_validate.side_effect = ValueError("Decryption failed.") - - run(self.run_server(stateless_retry=True)) - with self.assertRaises(ConnectionError): - run( - self.run_client( - configuration=QuicConfiguration(is_client=True, idle_timeout=4.0), - ) - ) - ===========changed ref 5=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_with_retry_bad_retry_source_connection_id(self): + """ + If the server's transport parameters do not have the correct + retry_source_connection_id the connection must fail. + """ + + def create_protocol(*args, **kwargs): + protocol = QuicConnectionProtocol(*args, **kwargs) + protocol._quic._retry_source_connection_id = None + return protocol + + run(self.run_server(create_protocol=create_protocol, retry=True)) + with self.assertRaises(ConnectionError): + run(self.run_client()) + ===========changed ref 6=========== # module: tests.test_asyncio class HighLevelTest(TestCase): + def test_connect_and_serve_with_retry_bad_original_destination_connection_id(self): + """ + If the server's transport parameters do not have the correct + original_destination_connection_id the connection must fail. + """ + + def create_protocol(*args, **kwargs): + protocol = QuicConnectionProtocol(*args, **kwargs) + protocol._quic._original_destination_connection_id = None + return protocol + + run(self.run_server(create_protocol=create_protocol, retry=True)) + with self.assertRaises(ConnectionError): + run(self.run_client()) + ===========changed ref 7=========== # module: tests.test_asyncio class HighLevelTest(TestCase): - def test_connect_and_serve_with_stateless_retry_bad_retry_source_connection_id( - self, - ): - """ - If the server's transport parameters do not have the correct - retry_source_connection_id the connection must fail. - """ - - def create_protocol(*args, **kwargs): - protocol = QuicConnectionProtocol(*args, **kwargs) - protocol._quic._retry_source_connection_id = None - return protocol - - run(self.run_server(create_protocol=create_protocol, stateless_retry=True)) - with self.assertRaises(ConnectionError): - run(self.run_client()) -
examples.interop/test_http_3
Modified
aiortc~aioquic
8b0b746542277bf796cc1376fef107a249de6dd5
[interop] use different port for HTTP/3 against quicly
<0>:<add> port = server.http3_port or server.port <5>:<del> server.host, <6>:<del> server.port, <7>:<del> configuration=configuration, <8>:<del> create_protocol=HttpClient, <9>:<add> server.host, port, configuration=configuration, create_protocol=HttpClient,
# 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 server.push_path is not None: <47> protocol.pushes.clear() <48> await protocol.get( <49> "https://{}:{}{}".format(server</s>
===========below chunk 0=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): # offset: 1 ) await asyncio.sleep(0.5) for push_id, events in protocol.pushes.items(): if ( len(events) >= 3 and isinstance(events[0], PushPromiseReceived) and isinstance(events[1], HeadersReceived) and isinstance(events[2], DataReceived) ): protocol._quic._logger.info( "Push promise %d for %s received (status %s)", push_id, dict(events[0].headers)[b":path"].decode("ascii"), int(dict(events[1].headers)[b":status"]), ) server.result |= Result.p ===========unchanged ref 0=========== at: asyncio.tasks sleep(delay: float, result: _T=..., *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, http3_port: Optional[int]=None, 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_path: Optional[str]="/%(size)d", verify_mode: Optional[int]=None) at: examples.interop.Server name: str host: str port: int = 4433 http3: bool = True http3_port: Optional[int] = None 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_path: Optional[str] = "/%(size)d" verify_mode: Optional[int] = None at: examples.interop.test_http_0 events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) 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 + http3_port: Optional[int] = None 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: bool = True throughput_path: Optional[str] = "/%(size)d" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433, throughput_path=None), Server( "haskell", "mew.org", structured_logging=True, throughput_path="/num/%(size)s" ), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", structured_logging=True, + throughput_path=None, # "/%(size)d.txt", - throughput_path="/%(size)d.txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", retry_port=None, structured_logging=True, ), + Server( + "ngtcp2", + "nghttp2.org", + push_path="/?push=/100", + structured_logging=True, + throughput_path=None, + ), - Server("ngtcp2", "nghttp2.org", push_path="/?push=/100"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=None), Server("pandora", "pandora.cm.in.tum.de", verify_mode</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s>_port=None), 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, structured_logging=True), - Server("quant", "quant.eggert.org", http3=False), Server("quic-go", "interop.seemann.io", port=443, retry_port=443), Server("quiche", "quic.tech", port=8443, retry_port=8444), + Server("quicly", "quic.examp1e.net", http3_port=443), - Server("quicly", "quic.examp1e.net"), Server("quinn", "h3.stammw.eu", port=443), ]
examples.interop/test_throughput
Modified
aiortc~aioquic
8b0b746542277bf796cc1376fef107a249de6dd5
[interop] use different port for HTTP/3 against quicly
<18>:<add> port = server.http3_port or server.port <20>:<add> port = server.port <22>:<del> server.host, <23>:<del> server.port, <24>:<del> configuration=configuration, <25>:<del> create_protocol=HttpClient, <26>:<add> server.host, port, configuration=configuration, create_protocol=HttpClient,
# module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): <0> failures = 0 <1> if server.throughput_path is None: <2> return <3> <4> for size in [5000000, 10000000]: <5> path = server.throughput_path % {"size": size} <6> print("Testing %d bytes download: %s" % (size, path)) <7> <8> # perform HTTP request over TCP <9> start = time.time() <10> response = httpx.get("https://" + server.host + path, verify=False) <11> tcp_octets = len(response.content) <12> tcp_elapsed = time.time() - start <13> assert tcp_octets == size, "HTTP/TCP response size mismatch" <14> <15> # perform HTTP request over QUIC <16> if server.http3: <17> configuration.alpn_protocols = H3_ALPN <18> else: <19> configuration.alpn_protocols = H0_ALPN <20> start = time.time() <21> async with connect( <22> server.host, <23> server.port, <24> configuration=configuration, <25> create_protocol=HttpClient, <26> ) as protocol: <27> protocol = cast(HttpClient, protocol) <28> <29> http_events = await protocol.get( <30> "https://{}:{}{}".format(server.host, server.port, path) <31> ) <32> quic_elapsed = time.time() - start <33> quic_octets = 0 <34> for http_event in http_events: <35> if isinstance(http_event, DataReceived): <36> quic_octets += len(http_event.data) <37> assert quic_octets == size, "HTTP/QUIC response size mismatch" <38> <39> print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) <40> print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) <41> <42> if quic_elapsed > 1.1 * tcp_elapsed: <43> failures += 1 <44> print("</s>
===========below chunk 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 else: print(" => PASS") if failures == 0: server.result |= Result.T ===========unchanged ref 0=========== at: examples.interop Result() Server(name: str, host: str, port: int=4433, http3: bool=True, http3_port: Optional[int]=None, 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_path: Optional[str]="/%(size)d", verify_mode: Optional[int]=None) at: examples.interop.Server host: str port: int = 4433 http3: bool = True http3_port: Optional[int] = None result: Result = field(default_factory=lambda: Result(0)) throughput_path: Optional[str] = "/%(size)d" at: examples.interop.test_spin_bit spin_bits = set() at: http3_client HttpClient(*args, **kwargs) at: httpx._api get(url: URL | str, *, params: QueryParamTypes | None=None, headers: HeaderTypes | None=None, cookies: CookieTypes | None=None, auth: AuthTypes | None=None, proxy: ProxyTypes | None=None, proxies: ProxiesTypes | None=None, follow_redirects: bool=False, cert: CertTypes | None=None, verify: VerifyTypes=True, timeout: TimeoutTypes=DEFAULT_TIMEOUT_CONFIG, trust_env: bool=True) -> Response 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 + http3_port: Optional[int] = None 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: bool = True throughput_path: Optional[str] = "/%(size)d" verify_mode: Optional[int] = None ===========changed ref 1=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): + port = server.http3_port or server.port if server.path is None: return configuration.alpn_protocols = H3_ALPN async with connect( - server.host, - server.port, - configuration=configuration, - create_protocol=HttpClient, + server.host, port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three # perform more HTTP requests to use QPACK dynamic tables for i in range(2): events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): http = cast(H3Connection, protocol._http) protocol._quic._logger.info( "QPACK decoder bytes RX %d TX %d", http._decoder_bytes_received, http._decoder_bytes_sent, ) protocol._quic._logger.info( "QPACK encoder bytes RX %d TX %d", http._encoder_bytes_received, http._encoder_bytes_sent, ) if ( http._decoder_bytes_received and http._decoder_bytes_sent and http._encoder_bytes_received and http._encoder_bytes_sent ): server.result |= Result.d # check push support if server.push_path is not None: protocol.pushes.clear() await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.push_path</s> ===========changed ref 2=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): # offset: 1 <s> await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.push_path) ) await asyncio.sleep(0.5) for push_id, events in protocol.pushes.items(): if ( len(events) >= 3 and isinstance(events[0], PushPromiseReceived) and isinstance(events[1], HeadersReceived) and isinstance(events[2], DataReceived) ): protocol._quic._logger.info( "Push promise %d for %s received (status %s)", push_id, dict(events[0].headers)[b":path"].decode("ascii"), int(dict(events[1].headers)[b":status"]), ) server.result |= Result.p ===========changed ref 3=========== # module: examples.interop SERVERS = [ Server("akamaiquic", "ietf.akaquic.com", port=443, verify_mode=ssl.CERT_NONE), Server( "aioquic", "quic.aiortc.org", port=443, push_path="/", structured_logging=True ), Server("ats", "quic.ogre.com"), Server("f5", "f5quic.com", retry_port=4433, throughput_path=None), Server( "haskell", "mew.org", structured_logging=True, throughput_path="/num/%(size)s" ), Server("gquic", "quic.rocks", retry_port=None), Server("lsquic", "http3-test.litespeedtech.com", push_path="/200?push=/100"), Server( "msquic", "quic.westus.cloudapp.azure.com", structured_logging=True, + throughput_path=None, # "/%(size)d.txt", - throughput_path="/%(size)d.txt", verify_mode=ssl.CERT_NONE, ), Server( "mvfst", "fb.mvfst.net", port=443, push_path="/push", retry_port=None, structured_logging=True, ), + Server( + "ngtcp2", + "nghttp2.org", + push_path="/?push=/100", + structured_logging=True, + throughput_path=None, + ), - Server("ngtcp2", "nghttp2.org", push_path="/?push=/100"), Server("ngx_quic", "cloudflare-quic.com", port=443, retry_port=None), Server("pandora", "pandora.cm.in.tum.de", verify_mode</s>
examples.interop/run
Modified
aiortc~aioquic
8b0b746542277bf796cc1376fef107a249de6dd5
[interop] use different port for HTTP/3 against quicly
<13>:<add> timeout = 120 <del> timeout = 60
# module: examples.interop def run(servers, tests, quic_log=False, secrets_log_file=None) -> None: <0> for server in servers: <1> if server.structured_logging: <2> server.result |= Result.L <3> for test_name, test_func in tests: <4> print("\n=== %s %s ===\n" % (server.name, test_name)) <5> configuration = QuicConfiguration( <6> alpn_protocols=H3_ALPN + H0_ALPN, <7> is_client=True, <8> quic_logger=QuicDirectoryLogger(quic_log) if quic_log else QuicLogger(), <9> secrets_log_file=secrets_log_file, <10> verify_mode=server.verify_mode, <11> ) <12> if test_name == "test_throughput": <13> timeout = 60 <14> else: <15> timeout = 10 <16> try: <17> await asyncio.wait_for( <18> test_func(server, configuration), timeout=timeout <19> ) <20> except Exception as exc: <21> print(exc) <22> <23> print("") <24> print_result(server) <25> <26> # print summary <27> if len(servers) > 1: <28> print("SUMMARY") <29> for server in servers: <30> print_result(server) <31>
===========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 result: Result = field(default_factory=lambda: Result(0)) structured_logging: bool = False verify_mode: Optional[int] = None at: examples.interop.print_result result = result[0:8] + " " + result[8:16] + " " + result[16:] at: quic_logger QuicDirectoryLogger(path: str) ===========changed ref 0=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): failures = 0 if server.throughput_path is None: return for size in [5000000, 10000000]: path = server.throughput_path % {"size": size} print("Testing %d bytes download: %s" % (size, path)) # perform HTTP request over TCP start = time.time() response = httpx.get("https://" + server.host + path, verify=False) tcp_octets = len(response.content) tcp_elapsed = time.time() - start assert tcp_octets == size, "HTTP/TCP response size mismatch" # perform HTTP request over QUIC if server.http3: configuration.alpn_protocols = H3_ALPN + port = server.http3_port or server.port else: configuration.alpn_protocols = H0_ALPN + port = server.port start = time.time() async with connect( - server.host, - server.port, - configuration=configuration, - create_protocol=HttpClient, + server.host, port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) http_events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, path) ) quic_elapsed = time.time() - start quic_octets = 0 for http_event in http_events: if isinstance(http_event, DataReceived): quic_octets += len(http_event.data) assert quic_octets == size, "HTTP/QUIC response size mismatch" print(" - HTTP/TCP completed in %.3f s" % tcp_elapsed) print(" - HTTP/QUIC completed in %.3f s" % quic_elapsed) if quic_elapsed > 1.1 * tcp_elapsed: failures += 1 print</s> ===========changed ref 1=========== # module: examples.interop def test_throughput(server: Server, configuration: QuicConfiguration): # offset: 1 <s> quic_elapsed) if quic_elapsed > 1.1 * tcp_elapsed: failures += 1 print(" => FAIL") else: print(" => PASS") if failures == 0: server.result |= Result.T ===========changed ref 2=========== # module: examples.interop @dataclass class Server: name: str host: str port: int = 4433 http3: bool = True + http3_port: Optional[int] = None 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: bool = True throughput_path: Optional[str] = "/%(size)d" verify_mode: Optional[int] = None ===========changed ref 3=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): + port = server.http3_port or server.port if server.path is None: return configuration.alpn_protocols = H3_ALPN async with connect( - server.host, - server.port, - configuration=configuration, - create_protocol=HttpClient, + server.host, port, configuration=configuration, create_protocol=HttpClient, ) as protocol: protocol = cast(HttpClient, protocol) # perform HTTP request events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): server.result |= Result.D server.result |= Result.three # perform more HTTP requests to use QPACK dynamic tables for i in range(2): events = await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.path) ) if events and isinstance(events[0], HeadersReceived): http = cast(H3Connection, protocol._http) protocol._quic._logger.info( "QPACK decoder bytes RX %d TX %d", http._decoder_bytes_received, http._decoder_bytes_sent, ) protocol._quic._logger.info( "QPACK encoder bytes RX %d TX %d", http._encoder_bytes_received, http._encoder_bytes_sent, ) if ( http._decoder_bytes_received and http._decoder_bytes_sent and http._encoder_bytes_received and http._encoder_bytes_sent ): server.result |= Result.d # check push support if server.push_path is not None: protocol.pushes.clear() await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.push_path</s> ===========changed ref 4=========== # module: examples.interop def test_http_3(server: Server, configuration: QuicConfiguration): # offset: 1 <s> await protocol.get( "https://{}:{}{}".format(server.host, server.port, server.push_path) ) await asyncio.sleep(0.5) for push_id, events in protocol.pushes.items(): if ( len(events) >= 3 and isinstance(events[0], PushPromiseReceived) and isinstance(events[1], HeadersReceived) and isinstance(events[2], DataReceived) ): protocol._quic._logger.info( "Push promise %d for %s received (status %s)", push_id, dict(events[0].headers)[b":path"].decode("ascii"), int(dict(events[1].headers)[b":status"]), ) server.result |= Result.p
tests.test_connection/QuicConnectionTest.test_version_negotiation_ok
Modified
aiortc~aioquic
50ca2d0a57d8906c62d7fc3c6bc2d4939adf2c81
[connection] ignore version negotiation packet with current version
<7>:<add> supported_versions=[QuicProtocolVersion.DRAFT_28], <del> supported_versions=[client._version],
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_version_negotiation_ok(self): <0> client = create_standalone_client(self) <1> <2> # found a common version, retry <3> client.receive_datagram( <4> encode_quic_version_negotiation( <5> source_cid=client._peer_cid.cid, <6> destination_cid=client.host_cid, <7> supported_versions=[client._version], <8> ), <9> SERVER_ADDR, <10> now=time.time(), <11> ) <12> self.assertEqual(drop(client), 1) <13>
===========unchanged ref 0=========== at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self, **client_options) at: time time() -> float
tests.test_connection/QuicConnectionTest.test_handle_reset_stream_frame
Modified
aiortc~aioquic
a8dc07b5f101a680bcf5edbdd5dbce3002ac54ff
[stream] check final size vs flow control limits
<0>:<add> stream_id = 0 <1>:<add> # client creates bidirectional stream <del> # client creates bidirectional stream 0 <2>:<add> client.send_stream_data(stream_id=stream_id, data=b"hello") <del> client.send_stream_data(stream_id=0, data=b"hello") <9>:<add> Buffer( <add> data=encode_uint_var(stream_id) <add> + encode_uint_var(QuicErrorCode.INTERNAL_ERROR) <add> + encode_uint_var(0) <add> ), <del> Buffer(data=binascii.unhexlify("000100")), <15>:<add> self.assertEqual(event.stream_id, stream_id) <del> self.assertEqual(event.stream_id, 0)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): <0> with client_and_server() as (client, server): <1> # client creates bidirectional stream 0 <2> client.send_stream_data(stream_id=0, data=b"hello") <3> consume_events(client) <4> <5> # client receives RESET_STREAM <6> client._handle_reset_stream_frame( <7> client_receive_context(client), <8> QuicFrameType.RESET_STREAM, <9> Buffer(data=binascii.unhexlify("000100")), <10> ) <11> <12> event = client.next_event() <13> self.assertEqual(type(event), events.StreamReset) <14> self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) <15> self.assertEqual(event.stream_id, 0) <16>
===========unchanged ref 0=========== at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) consume_events(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) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None
aioquic.quic.connection/QuicConnection._handle_reset_stream_frame
Modified
aiortc~aioquic
a8dc07b5f101a680bcf5edbdd5dbce3002ac54ff
[stream] check final size vs flow control limits
<18>:<add> # check flow-control limits <add> stream = self._get_or_create_stream(frame_type, stream_id) <add> if final_size > stream.max_stream_data_local: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <add> frame_type=frame_type, <add> reason_phrase="Over stream data limit", <add> ) <add> newly_received = max(0, final_size - stream._recv_highest) <add> if self._local_max_data.used + newly_received > self._local_max_data.value: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <add> frame_type=frame_type, <add> reason_phrase="Over connection data limit", <add> ) <add> <add> # process reset <24>:<add> stream.handle_reset(final_size=final_size) <del> # stream = self._get_or_create_stream(frame_type, stream_id)
# module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a RESET_STREAM frame. <2> """ <3> stream_id = buf.pull_uint_var() <4> error_code = buf.pull_uint_var() <5> final_size = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_reset_stream_frame( <11> error_code=error_code, final_size=final_size, stream_id=stream_id <12> ) <13> ) <14> <15> # check stream direction <16> self._assert_stream_can_receive(frame_type, stream_id) <17> <18> self._logger.info( <19> "Stream %d reset by peer (error code %d, final size %d)", <20> stream_id, <21> error_code, <22> final_size, <23> ) <24> # stream = self._get_or_create_stream(frame_type, stream_id) <25> self._events.append( <26> events.StreamReset(error_code=error_code, stream_id=stream_id) <27> ) <28>
===========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.Limit.__init__ self.used = 0 self.value = value at: aioquic.quic.connection.QuicConnection _assert_stream_can_receive(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._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_reset_stream_frame_over_max_stream_data(self): + stream_id = 0 + with client_and_server() as (client, server): + # client creates bidirectional stream + client.send_stream_data(stream_id=stream_id, data=b"hello") + consume_events(client) + + # client receives STREAM frame + with self.assertRaises(QuicConnectionError) as cm: + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(client._local_max_stream_data_bidi_local + 1) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) + self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) + self.assertEqual(cm.exception.reason_phrase, "Over stream data limit") + ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_reset_stream_frame_over_max_data(self): + stream_id = 0 + with client_and_server() as (client, server): + # client creates bidirectional stream + client.send_stream_data(stream_id=stream_id, data=b"hello") + consume_events(client) + + # artificially raise received data counter + client._local_max_data.used = client._local_max_data.value + + # client receives RESET_STREAM frame + with self.assertRaises(QuicConnectionError) as cm: + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(1) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FLOW_CONTROL_ERROR) + self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) + self.assertEqual(cm.exception.reason_phrase, "Over connection data limit") + ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): + stream_id = 0 with client_and_server() as (client, server): + # client creates bidirectional stream - # client creates bidirectional stream 0 + client.send_stream_data(stream_id=stream_id, data=b"hello") - client.send_stream_data(stream_id=0, data=b"hello") consume_events(client) # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.INTERNAL_ERROR) + + encode_uint_var(0) + ), - Buffer(data=binascii.unhexlify("000100")), ) event = client.next_event() self.assertEqual(type(event), events.StreamReset) self.assertEqual(event.error_code, QuicErrorCode.INTERNAL_ERROR) + self.assertEqual(event.stream_id, stream_id) - self.assertEqual(event.stream_id, 0)
aioquic.quic.connection/QuicConnection._handle_reset_stream_frame
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
<41>:<add> try: <add> event = stream.handle_reset(error_code=error_code, final_size=final_size) <add> except FinalSizeError as exc: <add> raise QuicConnectionError( <add> error_code=QuicErrorCode.FINAL_SIZE_ERROR, <add> frame_type=frame_type, <add> reason_phrase=str(exc), <add> ) <add> if event is not None: <del> stream.
# module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: <0> """ <1> Handle a RESET_STREAM frame. <2> """ <3> stream_id = buf.pull_uint_var() <4> error_code = buf.pull_uint_var() <5> final_size = buf.pull_uint_var() <6> <7> # log frame <8> if self._quic_logger is not None: <9> context.quic_logger_frames.append( <10> self._quic_logger.encode_reset_stream_frame( <11> error_code=error_code, final_size=final_size, stream_id=stream_id <12> ) <13> ) <14> <15> # check stream direction <16> self._assert_stream_can_receive(frame_type, stream_id) <17> <18> # check flow-control limits <19> stream = self._get_or_create_stream(frame_type, stream_id) <20> if final_size > stream.max_stream_data_local: <21> raise QuicConnectionError( <22> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <23> frame_type=frame_type, <24> reason_phrase="Over stream data limit", <25> ) <26> newly_received = max(0, final_size - stream._recv_highest) <27> if self._local_max_data.used + newly_received > self._local_max_data.value: <28> raise QuicConnectionError( <29> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <30> frame_type=frame_type, <31> reason_phrase="Over connection data limit", <32> ) <33> <34> # process reset <35> self._logger.info( <36> "Stream %d reset by peer (error code %d, final size %d)", <37> stream_id, <38> error_code, <39> final_size, <40> ) <41> stream.</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 self._events.append( events.StreamReset(error_code=error_code, stream_id=stream_id) ) 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.Limit.__init__ self.used = 0 self.value = value at: aioquic.quic.connection.QuicConnection _assert_stream_can_receive(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._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_connection_id, ) self._logger = QuicConnectionAdapter( logger, {"id": dump_cid(self._original_destination_connection_id)} ) at: aioquic.quic.connection.QuicConnection._close_end self._quic_logger = None at: aioquic.quic.connection.QuicReceiveContext epoch: tls.Epoch host_cid: bytes network_path: QuicNetworkPath quic_logger_frames: Optional[List[Any]] time: float at: logging.LoggerAdapter logger: Logger extra: Mapping[str, Any] ===========unchanged ref 1=========== info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_final_size_error(self): + with client_and_server() as (client, server): + frame_type = QuicFrameType.STREAM_BASE | 7 + stream_id = 1 + + # client receives FIN at offset 8 + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(8) + + encode_uint_var(0) + ), + ) + + # client receives FIN at offset 5 + 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(5) + + encode_uint_var(0) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") + ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_reset_stream_frame_final_size_error(self): + stream_id = 0 + with client_and_server() as (client, server): + # client creates bidirectional stream + client.send_stream_data(stream_id=stream_id, data=b"hello") + consume_events(client) + + # client receives RESET_STREAM at offset 8 + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(8) + ), + ) + + event = client.next_event() + self.assertEqual(type(event), events.StreamReset) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.stream_id, stream_id) + + # client receives RESET_STREAM at offset 5 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(5) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") +
aioquic.quic.connection/QuicConnection._handle_stream_frame
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
# 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> if offset + length > UINT_VAR_MAX: <13> raise QuicConnectionError( <14> error_code=QuicErrorCode.FRAME_ENCODING_ERROR, <15> frame_type=frame_type, <16> reason_phrase="offset + length cannot exceed 2^62 - 1", <17> ) <18> frame = QuicStreamFrame( <19> offset=offset, data=buf.pull_bytes(length), fin=bool(frame_type & 1) <20> ) <21> <22> # log frame <23> if self._quic_logger is not None: <24> context.quic_logger_frames.append( <25> self._quic_logger.encode_stream_frame(frame, stream_id=stream_id) <26> ) <27> <28> # check stream direction <29> self._assert_stream_can_receive(frame_type, stream_id) <30> <31> # check flow-control limits <32> stream = self._get_or_create_stream(frame_type, stream_id) <33> if offset + length > stream.max_stream_data_local: <34> raise QuicConnectionError( <35> error_code=QuicErrorCode.FLOW_CONTROL_ERROR, <36> frame_type=frame_type, <37> reason_phrase="Over stream data limit", <38> ) <39> newly_received = max(0, offset + length - stream._recv_highest) <40> if self._local_max_data.used + newly_</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 raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over connection data limit", ) # process data event = stream.add_frame(frame) 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.Limit.__init__ self.used = 0 self.value = value 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._local_max_data = Limit( frame_type=QuicFrameType.MAX_DATA, name="max_data", value=configuration.max_data, ) self._quic_logger: Optional[QuicLoggerTrace] = None self._quic_logger = configuration.quic_logger.start_trace( is_client=configuration.is_client, odcid=self._original_destination_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_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() error_code = buf.pull_uint_var() final_size = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_reset_stream_frame( error_code=error_code, final_size=final_size, stream_id=stream_id ) ) # check stream direction self._assert_stream_can_receive(frame_type, stream_id) # check flow-control limits stream = self._get_or_create_stream(frame_type, stream_id) if final_size > stream.max_stream_data_local: raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over stream data limit", ) newly_received = max(0, final_size - stream._recv_highest) if self._local_max_data.used + newly_received > self._local_max_data.value: raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over connection data limit", ) # process reset self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) + try: + event = stream.handle_reset(error_code=error_code, final_size=final_size) + except FinalSizeError as exc: + raise</s> ===========changed ref 1=========== # module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>error_code=error_code, final_size=final_size) + except FinalSizeError as exc: + raise QuicConnectionError( + error_code=QuicErrorCode.FINAL_SIZE_ERROR, + frame_type=frame_type, + reason_phrase=str(exc), + ) + if event is not None: - stream.handle_reset(final_size=final_size) + self._events.append(event) - self._events.append( - events.StreamReset(error_code=error_code, stream_id=stream_id) - ) self._local_max_data.used += newly_received ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_final_size_error(self): + with client_and_server() as (client, server): + frame_type = QuicFrameType.STREAM_BASE | 7 + stream_id = 1 + + # client receives FIN at offset 8 + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(8) + + encode_uint_var(0) + ), + ) + + # client receives FIN at offset 5 + 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(5) + + encode_uint_var(0) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") +
tests.test_stream/QuicStreamTest.test_recv_fin_then_data
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
<1>:<add> stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)) <del> stream.add_frame(QuicStreamFrame(offset=0, data=b"", fin=True)) <2>:<add> <add> # data beyond final size <add> with self.assertRaises(FinalSizeError) as cm: <del> with self.assertRaises(Exception) as cm: <4>:<add> self.assertEqual(str(cm.exception), "Data received beyond final size") <del> self.assertEqual(str(cm.exception), "Data received beyond FIN")
# module: tests.test_stream class QuicStreamTest(TestCase): def test_recv_fin_then_data(self): <0> stream = QuicStream(stream_id=0) <1> stream.add_frame(QuicStreamFrame(offset=0, data=b"", fin=True)) <2> with self.assertRaises(Exception) as cm: <3> stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567")) <4> self.assertEqual(str(cm.exception), "Data received beyond FIN") <5>
===========unchanged ref 0=========== at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str 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_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_final_size_error(self): + with client_and_server() as (client, server): + frame_type = QuicFrameType.STREAM_BASE | 7 + stream_id = 1 + + # client receives FIN at offset 8 + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(8) + + encode_uint_var(0) + ), + ) + + # client receives FIN at offset 5 + 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(5) + + encode_uint_var(0) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") + ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_reset_stream_frame_final_size_error(self): + stream_id = 0 + with client_and_server() as (client, server): + # client creates bidirectional stream + client.send_stream_data(stream_id=stream_id, data=b"hello") + consume_events(client) + + # client receives RESET_STREAM at offset 8 + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(8) + ), + ) + + event = client.next_event() + self.assertEqual(type(event), events.StreamReset) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.stream_id, stream_id) + + # client receives RESET_STREAM at offset 5 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(5) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") + ===========changed ref 2=========== # module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a RESET_STREAM frame. """ stream_id = buf.pull_uint_var() error_code = buf.pull_uint_var() final_size = buf.pull_uint_var() # log frame if self._quic_logger is not None: context.quic_logger_frames.append( self._quic_logger.encode_reset_stream_frame( error_code=error_code, final_size=final_size, stream_id=stream_id ) ) # check stream direction self._assert_stream_can_receive(frame_type, stream_id) # check flow-control limits stream = self._get_or_create_stream(frame_type, stream_id) if final_size > stream.max_stream_data_local: raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over stream data limit", ) newly_received = max(0, final_size - stream._recv_highest) if self._local_max_data.used + newly_received > self._local_max_data.value: raise QuicConnectionError( error_code=QuicErrorCode.FLOW_CONTROL_ERROR, frame_type=frame_type, reason_phrase="Over connection data limit", ) # process reset self._logger.info( "Stream %d reset by peer (error code %d, final size %d)", stream_id, error_code, final_size, ) + try: + event = stream.handle_reset(error_code=error_code, final_size=final_size) + except FinalSizeError as exc: + raise</s> ===========changed ref 3=========== # module: aioquic.quic.connection class QuicConnection: def _handle_reset_stream_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: # offset: 1 <s>error_code=error_code, final_size=final_size) + except FinalSizeError as exc: + raise QuicConnectionError( + error_code=QuicErrorCode.FINAL_SIZE_ERROR, + frame_type=frame_type, + reason_phrase=str(exc), + ) + if event is not None: - stream.handle_reset(final_size=final_size) + self._events.append(event) - self._events.append( - events.StreamReset(error_code=error_code, stream_id=stream_id) - ) self._local_max_data.used += newly_received
aioquic.quic.stream/QuicStream.__init__
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
<7>:<del> self._recv_buffer_fin: Optional[int] = None <9>:<add> self._recv_final_size: Optional[int] = None
# module: aioquic.quic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: <0> self.is_blocked = False <1> self.max_stream_data_local = max_stream_data_local <2> self.max_stream_data_local_sent = max_stream_data_local <3> self.max_stream_data_remote = max_stream_data_remote <4> self.send_buffer_is_empty = True <5> <6> self._recv_buffer = bytearray() <7> self._recv_buffer_fin: Optional[int] = None <8> self._recv_buffer_start = 0 # the offset for the start of the buffer <9> self._recv_highest = 0 # the highest offset ever seen <10> self._recv_ranges = RangeSet() <11> <12> self._send_acked = RangeSet() <13> self._send_buffer = bytearray() <14> self._send_buffer_fin: Optional[int] = None <15> self._send_buffer_start = 0 # the offset for the start of the buffer <16> self._send_buffer_stop = 0 # the offset for the stop of the buffer <17> self._send_highest = 0 <18> self._send_pending = RangeSet() <19> self._send_pending_eof = False <20> self._send_reset_error_code: Optional[int] = None <21> self._send_reset_pending = False <22> <23> self.__stream_id = stream_id <24>
===========unchanged ref 0=========== at: aioquic.quic.stream.QuicStream._pull_data self._recv_buffer_start = r.stop at: aioquic.quic.stream.QuicStream.add_frame self._recv_final_size = frame_end self._recv_highest = frame_end self._recv_buffer_start += count self._recv_buffer += bytearray(gap) at: aioquic.quic.stream.QuicStream.get_frame self._send_pending_eof = False self.send_buffer_is_empty = True self._send_highest = stop at: aioquic.quic.stream.QuicStream.handle_reset self._recv_final_size = final_size at: aioquic.quic.stream.QuicStream.on_data_delivery self.send_buffer_is_empty = False self._send_buffer_start += size self._send_pending_eof = True at: aioquic.quic.stream.QuicStream.write self.send_buffer_is_empty = False self._send_buffer += data self._send_buffer_stop += size self._send_buffer_fin = self._send_buffer_stop self._send_pending_eof = True ===========changed ref 0=========== # module: aioquic.quic.stream + class FinalSizeError(Exception): + pass + ===========changed ref 1=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 2=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_after_fin(self): + stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)), + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 3=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 4=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice_final_size_error(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + + with self.assertRaises(FinalSizeError) as cm: + stream.handle_reset(final_size=5) + self.assertEqual(str(cm.exception), "Cannot change final size") + ===========changed ref 5=========== # module: tests.test_stream class QuicStreamTest(TestCase): def test_recv_fin_then_data(self): stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)) - stream.add_frame(QuicStreamFrame(offset=0, data=b"", fin=True)) + + # data beyond final size + with self.assertRaises(FinalSizeError) as cm: - with self.assertRaises(Exception) as cm: stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567")) + self.assertEqual(str(cm.exception), "Data received beyond final size") - self.assertEqual(str(cm.exception), "Data received beyond FIN") ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_final_size_error(self): + with client_and_server() as (client, server): + frame_type = QuicFrameType.STREAM_BASE | 7 + stream_id = 1 + + # client receives FIN at offset 8 + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(8) + + encode_uint_var(0) + ), + ) + + # client receives FIN at offset 5 + 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(5) + + encode_uint_var(0) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") + ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_reset_stream_frame_final_size_error(self): + stream_id = 0 + with client_and_server() as (client, server): + # client creates bidirectional stream + client.send_stream_data(stream_id=stream_id, data=b"hello") + consume_events(client) + + # client receives RESET_STREAM at offset 8 + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(8) + ), + ) + + event = client.next_event() + self.assertEqual(type(event), events.StreamReset) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.stream_id, stream_id) + + # client receives RESET_STREAM at offset 5 + with self.assertRaises(QuicConnectionError) as cm: + client._handle_reset_stream_frame( + client_receive_context(client), + QuicFrameType.RESET_STREAM, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(QuicErrorCode.NO_ERROR) + + encode_uint_var(5) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") +
aioquic.quic.stream/QuicStream.add_frame
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
<8>:<add> if self._recv_final_size is not None: <add> if frame_end > self._recv_final_size: <add> raise FinalSizeError("Data received beyond final size") <add> elif frame.fin and frame_end != self._recv_final_size: <add> raise FinalSizeError("Cannot change final size") <del> if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin: <9>:<del> raise Exception("Data received beyond FIN") <11>:<add> self._recv_final_size = frame_end <del> self._recv_buffer_fin = frame_end <40>:<add> end_stream = self._recv_buffer_start == self._recv_final_size <del> end_stream = self._recv_buffer_start == self._recv_buffer_fin
# module: aioquic.quic.stream class QuicStream: # reader def add_frame(self, frame: QuicStreamFrame) -> Optional[events.StreamDataReceived]: <0> """ <1> Add a frame of received data. <2> """ <3> pos = frame.offset - self._recv_buffer_start <4> count = len(frame.data) <5> frame_end = frame.offset + count <6> <7> # we should receive no more data beyond FIN! <8> if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin: <9> raise Exception("Data received beyond FIN") <10> if frame.fin: <11> self._recv_buffer_fin = frame_end <12> if frame_end > self._recv_highest: <13> self._recv_highest = frame_end <14> <15> # fast path: new in-order chunk <16> if pos == 0 and count and not self._recv_buffer: <17> self._recv_buffer_start += count <18> return events.StreamDataReceived( <19> data=frame.data, end_stream=frame.fin, stream_id=self.__stream_id <20> ) <21> <22> # discard duplicate data <23> if pos < 0: <24> frame.data = frame.data[-pos:] <25> frame.offset -= pos <26> pos = 0 <27> <28> # marked received range <29> if frame_end > frame.offset: <30> self._recv_ranges.add(frame.offset, frame_end) <31> <32> # add new data <33> gap = pos - len(self._recv_buffer) <34> if gap > 0: <35> self._recv_buffer += bytearray(gap) <36> self._recv_buffer[pos : pos + count] = frame.data <37> <38> # return data from the front of the buffer <39> data = self._pull_data() <40> end_stream = self._recv_buffer_start == self._recv_buffer_fin <41> if data or end_stream: <42> return events.StreamDataReceived( <43> data=data</s>
===========below chunk 0=========== # module: aioquic.quic.stream class QuicStream: # reader def add_frame(self, frame: QuicStreamFrame) -> Optional[events.StreamDataReceived]: # offset: 1 ) else: return None ===========unchanged ref 0=========== at: aioquic.quic.stream FinalSizeError(*args: object) at: aioquic.quic.stream.QuicStream _pull_data() -> bytes at: aioquic.quic.stream.QuicStream.__init__ self._recv_buffer = bytearray() self._recv_buffer_start = 0 # the offset for the start of the buffer self._recv_final_size: Optional[int] = None self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self.__stream_id = stream_id at: aioquic.quic.stream.QuicStream._pull_data self._recv_buffer_start = r.stop at: aioquic.quic.stream.QuicStream.handle_reset self._recv_final_size = final_size ===========changed ref 0=========== # module: aioquic.quic.stream + class FinalSizeError(Exception): + pass + ===========changed ref 1=========== # module: aioquic.quic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: self.is_blocked = False self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self.max_stream_data_remote = max_stream_data_remote self.send_buffer_is_empty = True self._recv_buffer = bytearray() - self._recv_buffer_fin: Optional[int] = None self._recv_buffer_start = 0 # the offset for the start of the buffer + self._recv_final_size: Optional[int] = None self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self._send_acked = RangeSet() self._send_buffer = bytearray() self._send_buffer_fin: Optional[int] = None self._send_buffer_start = 0 # the offset for the start of the buffer self._send_buffer_stop = 0 # the offset for the stop of the buffer self._send_highest = 0 self._send_pending = RangeSet() self._send_pending_eof = False self._send_reset_error_code: Optional[int] = None self._send_reset_pending = False self.__stream_id = stream_id ===========changed ref 2=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 3=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_after_fin(self): + stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)), + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 4=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 5=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice_final_size_error(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + + with self.assertRaises(FinalSizeError) as cm: + stream.handle_reset(final_size=5) + self.assertEqual(str(cm.exception), "Cannot change final size") + ===========changed ref 6=========== # module: tests.test_stream class QuicStreamTest(TestCase): def test_recv_fin_then_data(self): stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)) - stream.add_frame(QuicStreamFrame(offset=0, data=b"", fin=True)) + + # data beyond final size + with self.assertRaises(FinalSizeError) as cm: - with self.assertRaises(Exception) as cm: stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567")) + self.assertEqual(str(cm.exception), "Data received beyond final size") - self.assertEqual(str(cm.exception), "Data received beyond FIN") ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_handle_stream_frame_final_size_error(self): + with client_and_server() as (client, server): + frame_type = QuicFrameType.STREAM_BASE | 7 + stream_id = 1 + + # client receives FIN at offset 8 + client._handle_stream_frame( + client_receive_context(client), + frame_type, + Buffer( + data=encode_uint_var(stream_id) + + encode_uint_var(8) + + encode_uint_var(0) + ), + ) + + # client receives FIN at offset 5 + 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(5) + + encode_uint_var(0) + ), + ) + self.assertEqual(cm.exception.error_code, QuicErrorCode.FINAL_SIZE_ERROR) + self.assertEqual(cm.exception.frame_type, frame_type) + self.assertEqual(cm.exception.reason_phrase, "Cannot change final size") +
aioquic.quic.stream/QuicStream.handle_reset
Modified
aiortc~aioquic
b6713bb72c4a3f87402489d0ae2a6469e5e9c402
[stream] check final size does not change
<3>:<add> if self._recv_final_size is not None and final_size != self._recv_final_size: <add> raise FinalSizeError("Cannot change final size") <add> self._recv_final_size = final_size <del> self._recv_buffer_fin = final_size <4>:<add> return events.StreamReset(error_code=error_code, stream_id=self.__stream_id)
# module: aioquic.quic.stream class QuicStream: + def handle_reset( + self, *, final_size: int, error_code: int = QuicErrorCode.NO_ERROR + ) -> Optional[events.StreamReset]: - def handle_reset(self, final_size: int) -> None: <0> """ <1> Handle an abrupt termination of the receiving part of the QUIC stream. <2> """ <3> self._recv_buffer_fin = final_size <4>
===========unchanged ref 0=========== at: aioquic.quic.stream.QuicStream.__init__ self._send_pending = RangeSet() ===========changed ref 0=========== # module: aioquic.quic.stream + class FinalSizeError(Exception): + pass + ===========changed ref 1=========== # module: aioquic.quic.stream class QuicStream: def __init__( self, stream_id: Optional[int] = None, max_stream_data_local: int = 0, max_stream_data_remote: int = 0, ) -> None: self.is_blocked = False self.max_stream_data_local = max_stream_data_local self.max_stream_data_local_sent = max_stream_data_local self.max_stream_data_remote = max_stream_data_remote self.send_buffer_is_empty = True self._recv_buffer = bytearray() - self._recv_buffer_fin: Optional[int] = None self._recv_buffer_start = 0 # the offset for the start of the buffer + self._recv_final_size: Optional[int] = None self._recv_highest = 0 # the highest offset ever seen self._recv_ranges = RangeSet() self._send_acked = RangeSet() self._send_buffer = bytearray() self._send_buffer_fin: Optional[int] = None self._send_buffer_start = 0 # the offset for the start of the buffer self._send_buffer_stop = 0 # the offset for the stop of the buffer self._send_highest = 0 self._send_pending = RangeSet() self._send_pending_eof = False self._send_reset_error_code: Optional[int] = None self._send_reset_pending = False self.__stream_id = stream_id ===========changed ref 2=========== # module: aioquic.quic.stream class QuicStream: # reader def add_frame(self, frame: QuicStreamFrame) -> Optional[events.StreamDataReceived]: """ Add a frame of received data. """ pos = frame.offset - self._recv_buffer_start count = len(frame.data) frame_end = frame.offset + count # we should receive no more data beyond FIN! + if self._recv_final_size is not None: + if frame_end > self._recv_final_size: + raise FinalSizeError("Data received beyond final size") + elif frame.fin and frame_end != self._recv_final_size: + raise FinalSizeError("Cannot change final size") - if self._recv_buffer_fin is not None and frame_end > self._recv_buffer_fin: - raise Exception("Data received beyond FIN") if frame.fin: + self._recv_final_size = frame_end - self._recv_buffer_fin = frame_end if frame_end > self._recv_highest: self._recv_highest = frame_end # fast path: new in-order chunk if pos == 0 and count and not self._recv_buffer: self._recv_buffer_start += count return events.StreamDataReceived( data=frame.data, end_stream=frame.fin, stream_id=self.__stream_id ) # discard duplicate data if pos < 0: frame.data = frame.data[-pos:] frame.offset -= pos pos = 0 # marked received range if frame_end > frame.offset: self._recv_ranges.add(frame.offset, frame_end) # add new data gap = pos - len(self._recv_buffer) if gap > 0: self._recv_buffer += bytearray(gap) self._recv_buffer[pos : pos + count] = frame.data # return data from the front of the buffer data</s> ===========changed ref 3=========== # module: aioquic.quic.stream class QuicStream: # reader def add_frame(self, frame: QuicStreamFrame) -> Optional[events.StreamDataReceived]: # offset: 1 <s>._recv_buffer[pos : pos + count] = frame.data # return data from the front of the buffer data = self._pull_data() + end_stream = self._recv_buffer_start == self._recv_final_size - end_stream = self._recv_buffer_start == self._recv_buffer_fin if data or end_stream: return events.StreamDataReceived( data=data, end_stream=end_stream, stream_id=self.__stream_id ) else: return None ===========changed ref 4=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 5=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_after_fin(self): + stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)), + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 6=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + ===========changed ref 7=========== # module: tests.test_stream class QuicStreamTest(TestCase): + def test_recv_reset_twice_final_size_error(self): + stream = QuicStream(stream_id=0) + self.assertEqual( + stream.handle_reset(final_size=4), + StreamReset(error_code=QuicErrorCode.NO_ERROR, stream_id=0), + ) + + with self.assertRaises(FinalSizeError) as cm: + stream.handle_reset(final_size=5) + self.assertEqual(str(cm.exception), "Cannot change final size") + ===========changed ref 8=========== # module: tests.test_stream class QuicStreamTest(TestCase): def test_recv_fin_then_data(self): stream = QuicStream(stream_id=0) + stream.add_frame(QuicStreamFrame(offset=0, data=b"0123", fin=True)) - stream.add_frame(QuicStreamFrame(offset=0, data=b"", fin=True)) + + # data beyond final size + with self.assertRaises(FinalSizeError) as cm: - with self.assertRaises(Exception) as cm: stream.add_frame(QuicStreamFrame(offset=0, data=b"01234567")) + self.assertEqual(str(cm.exception), "Data received beyond final size") - self.assertEqual(str(cm.exception), "Data received beyond FIN")
aioquic.quic.recovery/QuicPacketRecovery.discard_space
Modified
aiortc~aioquic
90284bd08d42e767e121cd059044f1bff8669cae
[recovery] reset PTO count when initial/handshake spaces are discarded
<11>:<add> # reset PTO count <add> self._pto_count = 0 <add>
# module: aioquic.quic.recovery class QuicPacketRecovery: def discard_space(self, space: QuicPacketSpace) -> None: <0> assert space in self.spaces <1> <2> self._cc.on_packets_expired( <3> filter(lambda x: x.in_flight, space.sent_packets.values()) <4> ) <5> space.sent_packets.clear() <6> <7> space.ack_at = None <8> space.ack_eliciting_in_flight = 0 <9> space.loss_time = None <10> <11> if self._quic_logger is not None: <12> self._log_metrics_updated() <13>
===========unchanged ref 0=========== at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicCongestionControl on_packets_expired(packets: Iterable[QuicSentPacket]) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] self._pto_count = 0 self._cc = QuicCongestionControl() at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_at: Optional[float] = None self.ack_eliciting_in_flight = 0 self.loss_time: Optional[float] = None self.sent_packets: Dict[int, QuicSentPacket] = {}