{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \",\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 1===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 2===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 3===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 4===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 5===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 6===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 7===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 8===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n \n===========changed ref 9===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 10===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_handle_stop_sending_frame(self):\n with client_and_server() as (client, server):\n # client creates bidirectional stream 0\n client.send_stream_data(stream_id=0, data=b\"hello\")\n \n # client receives STOP_SENDING\n client._handle_stop_sending_frame(\n client_receive_context(client),\n QuicFrameType.STOP_SENDING,\n + Buffer(data=b\"\\x00\\x11\"),\n - Buffer(data=b\"\\x00\\x11\\x22\"),\n )\n "}}},{"rowIdx":3010,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_uni_stream_type"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: client_options={\"alpn_protocols\": [\"h3-22\"]},\n client_options={\"alpn_protocols\": [\"h3-20\"]},\n <2>: server_options={\"alpn_protocols\": [\"h3-22\"]},\n server_options={\"alpn_protocols\": [\"h3-20\"]},\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-20\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-20\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_server = H3Connection(quic_server)\n <5> \n <6> # unknown stream type 9\n <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n <8> self.assertEqual(stream_id, 2)\n <9> quic_client.send_stream_data(stream_id, b\"\\x09\")\n<10> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<11> self.assertEqual(h3_server._stream_buffers, {2: b\"\"})\n<12> self.assertEqual(h3_server._stream_types, {2: 9})\n<13> \n<14> # unknown stream type 64, one byte at a time\n<15> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n<16> self.assertEqual(stream_id, 6)\n<17> \n<18> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<19> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<20> self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\\x40\"})\n<21> self.assertEqual(h3_server._stream_types, {2: 9})\n<22> \n<23> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<24> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<25> self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\"})\n<26> self.assertEqual"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n # offset: 1\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n with client_and_server(\n + client_options={\"alpn_protocols\": [\"h3-22\"]},\n - client_options={\"alpn_protocols\": [\"h3-20\"]},\n + server_options={\"alpn_protocols\": [\"h3-22\"]},\n - server_options={\"alpn_protocols\": [\"h3-20\"]},\n ) as (quic_client, quic_server):\n h3_client = H3Connection(quic_client)\n h3_server = H3Connection(quic_server)\n \n # send request\n stream_id = quic_client.get_next_available_stream_id()\n h3_client.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n )\n h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n \n # receive request\n events = h3_transfer(quic_client, h3_server)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], RequestReceived))\n self.assertEqual(\n events[0].headers,\n [\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n ],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_\n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n ))\n self.assertEqual(events[1].data, b\"\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n===========changed ref 2===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 3===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 4===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 5===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 6===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 7===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 8===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 9===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n "}}},{"rowIdx":3011,"cells":{"path":{"kind":"string","value":"examples.http3-server/HttpServer._consume_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<12>: if event.alpn_protocol == \"h3-22\":\n if event.alpn_protocol == \"h3-20\":\n<14>: elif event.alpn_protocol == \"hq-22\":\n elif event.alpn_protocol == \"hq-20\":\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n <0> # process events\n <1> event = connection.next_event()\n <2> while event is not None:\n <3> if isinstance(event, aioquic.events.ConnectionTerminated):\n <4> # remove the connection\n <5> for cid, conn in list(self._connections.items()):\n <6> if conn == connection:\n <7> del self._connections[cid]\n <8> self._http.pop(connection, None)\n <9> self._timer.pop(connection, None)\n<10> return\n<11> elif isinstance(event, aioquic.events.HandshakeCompleted):\n<12> if event.alpn_protocol == \"h3-20\":\n<13> self._http[connection] = H3Connection(connection)\n<14> elif event.alpn_protocol == \"hq-20\":\n<15> self._http[connection] = H0Connection(connection)\n<16> elif isinstance(event, aioquic.events.ConnectionIdIssued):\n<17> self._connections[event.connection_id] = connection\n<18> elif isinstance(event, aioquic.events.ConnectionIdRetired):\n<19> assert self._connections[event.connection_id] == connection\n<20> del self._connections[event.connection_id]\n<21> \n<22> #  pass event to the HTTP layer\n<23> http = self._http.get(connection)\n<24> if http is not None:\n<25> for http_event in http.handle_event(event):\n<26> handle_http_event(http, http_event)\n<27> \n<28> event = connection.next_event()\n<29> \n<30> # send datagrams\n<31> for data, addr in connection.datagrams_to_send(now=self._loop.time()):\n<32> self._transport.sendto(data, addr)\n<33> \n<34> # re-arm timer\n<35> next_timer_at = connection.get_timer()\n<36> (timer, timer_at) = self._timer.get(connection, (None, None))\n<37> if timer is not None and timer"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n # offset: 1\n timer.cancel()\n timer = None\n if timer is None and timer_at is not None:\n timer = self._loop.call_at(\n next_timer_at, partial(self._handle_timer, connection)\n )\n self._timer[connection] = (timer, next_timer_at)\n \n \n===========unchanged ref 0===========\n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n next_event() -> Optional[events.Event]\n \n at: aioquic.events\n ConnectionIdIssued(connection_id: bytes)\n \n ConnectionIdRetired(connection_id: bytes)\n \n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n at: asyncio.events.AbstractEventLoop\n call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle\n \n time() -> float\n \n at: asyncio.events.TimerHandle\n __slots__ = ['_scheduled', '_when']\n \n cancel() -> None\n \n at: asyncio.transports.DatagramTransport\n __slots__ = ()\n \n sendto(data: Any, addr: Optional[_Address]=...) -> None\n \n at: examples.http3-server\n H0Connection(quic: QuicConnection)\n \n handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None\n \n at: examples.http3-server.H0Connection\n handle_event(event: aioquic.events.Event)\n \n at: examples.http3-server.HttpServer\n _handle_timer(connection: QuicConnection) -> None\n \n \n===========unchanged ref 1===========\n at: examples.http3-server.HttpServer.__init__\n self._connections: Dict[bytes, QuicConnection] = {}\n \n self._http: Dict[QuicConnection, HttpConnection] = {}\n \n self._loop = asyncio.get_event_loop()\n \n self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n \n self._transport: Optional[asyncio.DatagramTransport] = None\n \n at: examples.http3-server.HttpServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 1===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 2===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 3===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 4===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 5===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 6===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 7===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 8===========\n # module: aioquic.connection\n class QuicConnection:\n def _handle_stop_sending_frame(\n self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n ) -> None:\n \"\"\"\n Handle a STOP_SENDING frame.\n \"\"\"\n stream_id = buf.pull_uint_var()\n + buf.pull_uint_var() # application error code\n - buf.pull_uint16() # application error code\n \n # check stream direction\n self._assert_stream_can_send(frame_type, stream_id)\n \n self._get_or_create_stream(frame_type, stream_id)\n "}}},{"rowIdx":3012,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_pull_initial_client"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <3>: self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n <5>: self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n <9>: self.assertEqual(header.rest_length, 1262)\n self.assertEqual(header.rest_length, 1263)\n<10>: self.assertEqual(buf.tell(), 18)\n self.assertEqual(buf.tell(), 17)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n <0> buf = Buffer(data=load(\"initial_client.bin\"))\n <1> header = pull_quic_header(buf, host_cid_length=8)\n <2> self.assertTrue(header.is_long_header)\n <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n <4> self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n <5> self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n <6> self.assertEqual(header.source_cid, b\"\")\n <7> self.assertEqual(header.original_destination_cid, b\"\")\n <8> self.assertEqual(header.token, b\"\")\n <9> self.assertEqual(header.rest_length, 1263)\n<10> self.assertEqual(buf.tell(), 17)\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader\n \n at: aioquic.packet.QuicHeader\n is_long_header: bool\n \n version: Optional[int]\n \n packet_type: int\n \n destination_cid: bytes\n \n source_cid: bytes\n \n original_destination_cid: bytes = b\"\"\n \n token: bytes = b\"\"\n \n rest_length: int = 0\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_\n===========changed ref 2===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n \n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_long_header=True,\n version=version,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n \n===========changed ref 3===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 4===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 5===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 6===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 7===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 8===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 9===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n "}}},{"rowIdx":3013,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_pull_initial_server"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <3>: self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n <6>: self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n <9>: self.assertEqual(header.rest_length, 184)\n self.assertEqual(header.rest_length, 182)\n<10>: self.assertEqual(buf.tell(), 18)\n self.assertEqual(buf.tell(), 17)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n <0> buf = Buffer(data=load(\"initial_server.bin\"))\n <1> header = pull_quic_header(buf, host_cid_length=8)\n <2> self.assertTrue(header.is_long_header)\n <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n <4> self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n <5> self.assertEqual(header.destination_cid, b\"\")\n <6> self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n <7> self.assertEqual(header.original_destination_cid, b\"\")\n <8> self.assertEqual(header.token, b\"\")\n <9> self.assertEqual(header.rest_length, 182)\n<10> self.assertEqual(buf.tell(), 17)\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_\n===========changed ref 2===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n \n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_long_header=True,\n version=version,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 4===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 5===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 6===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 7===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 8===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 9===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n "}}},{"rowIdx":3014,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_pull_retry"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <3>: self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19)\n <5>: self.assertEqual(header.destination_cid, binascii.unhexlify(\"fee746dfde699d61\"))\n self.assertEqual(header.destination_cid, binascii.unhexlify(\"c98343fe8f5f0ff4\"))\n <6>: self.assertEqual(header.source_cid, binascii.unhexlify(\"59aa0942fd2f11e9\"))\n <7>: header.source_cid,\n <8>: binascii.unhexlify(\"c17f7c0473e635351b85a17e9f3296d7246c\"),\n <9>: )\n<10>: self.assertEqual(\n<11>: header.original_destination_cid, binascii.unhexlify(\"d61e7448e0d63dff\")\n header.original_destination_cid, binascii.unhexlify(\"85abb547bf28be97\")\n<16>: \"5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764\"\n \"01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97\"\n<20>: self.assertEqual(buf.tell(), 73)\n self.assertEqual(buf.tell(), 69)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_retry(self):\n <0> buf = Buffer(data=load(\"retry.bin\"))\n <1> header = pull_quic_header(buf, host_cid_length=8)\n <2> self.assertTrue(header.is_long_header)\n <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19)\n <4> self.assertEqual(header.packet_type, PACKET_TYPE_RETRY)\n <5> self.assertEqual(header.destination_cid, binascii.unhexlify(\"c98343fe8f5f0ff4\"))\n <6> self.assertEqual(\n <7> header.source_cid,\n <8> binascii.unhexlify(\"c17f7c0473e635351b85a17e9f3296d7246c\"),\n <9> )\n<10> self.assertEqual(\n<11> header.original_destination_cid, binascii.unhexlify(\"85abb547bf28be97\")\n<12> )\n<13> self.assertEqual(\n<14> header.token,\n<15> binascii.unhexlify(\n<16> \"01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97\"\n<17> ),\n<18> )\n<19> self.assertEqual(header.rest_length, 0)\n<20> self.assertEqual(buf.tell(), 69)\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.packet\n PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_\n===========changed ref 2===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n \n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_long_header=True,\n version=version,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 5===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 6===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 7===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - "}}},{"rowIdx":3015,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_pull_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <5>: self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n <6>: self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n<10>: self.assertEqual(buf.tell(), 23)\n self.assertEqual(buf.tell(), 22)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n <0> buf = Buffer(data=load(\"version_negotiation.bin\"))\n <1> header = pull_quic_header(buf, host_cid_length=8)\n <2> self.assertTrue(header.is_long_header)\n <3> self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n <4> self.assertEqual(header.packet_type, None)\n <5> self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n <6> self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n <7> self.assertEqual(header.original_destination_cid, b\"\")\n <8> self.assertEqual(header.token, b\"\")\n <9> self.assertEqual(header.rest_length, 8)\n<10> self.assertEqual(buf.tell(), 22)\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.packet\n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.test_packet.PacketTest.test_pull_version_negotiation\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n \n header = pull_quic_header(buf, host_cid_length=8)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 2===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_retry(self):\n buf = Buffer(data=load(\"retry.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19)\n self.assertEqual(header.packet_type, PACKET_TYPE_RETRY)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"fee746dfde699d61\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"c98343fe8f5f0ff4\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"59aa0942fd2f11e9\"))\n self.assertEqual(\n - header.source_cid,\n - binascii.unhexlify(\"c17f7c0473e635351b85a17e9f3296d7246c\"),\n - )\n - self.assertEqual(\n + header.original_destination_cid, binascii.unhexlify(\"d61e7448e0d63dff\")\n - header.original_destination_cid, binascii.unhexlify(\"85abb547bf28be97\")\n )\n self.assertEqual(\n header.token,\n binascii.unhexlify(\n + \"5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764\"\n - \"01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97\"\n ),\n )\n self.assertEqual(header.rest_length, 0)\n + \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_retry(self):\n # offset: 1\n 7bf28be97\"\n ),\n )\n self.assertEqual(header.rest_length, 0)\n + self.assertEqual(buf.tell(), 73)\n - self.assertEqual(buf.tell(), 69)\n \n===========changed ref 5===========\n # module: aioquic.packet\n - def encode_cid_length(length: int) -> int:\n - return length - 3 if length else 0\n - \n===========changed ref 6===========\n # module: aioquic.packet\n - def decode_cid_length(length: int) -> int:\n - return length + 3 if length else 0\n - \n===========changed ref 7===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_20(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_20],\n - server_versions=[QuicProtocolVersion.DRAFT_20],\n - )\n - \n===========changed ref 8===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n - def test_connect_draft_19(self):\n - self._test_connect_with_version(\n - client_versions=[QuicProtocolVersion.DRAFT_19],\n - server_versions=[QuicProtocolVersion.DRAFT_19],\n - )\n - \n===========changed ref 9===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n "}}},{"rowIdx":3016,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_pull_long_header_no_fixed_bit"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n <0> buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n <1> with self.assertRaises(ValueError) as cm:\n <2> pull_quic_header(buf, host_cid_length=8)\n <3> self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n <4> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.packet\n pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader\n \n at: tests.test_packet.PacketTest.test_pull_long_header_no_fixed_bit\n buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n at: unittest.case._AssertRaisesContext.__exit__\n self.exception = exc_value.with_traceback(None)\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n first_byte = buf.pull_uint8()\n \n original_destination_cid = b\"\"\n token = b\"\"\n if is_long_header(first_byte):\n # long header packet\n version = buf.pull_uint32()\n - cid_lengths = buf.pull_uint8()\n \n + destination_cid_length = buf.pull_uint8()\n - destination_cid_length = decode_cid_length(cid_lengths // 16)\n destination_cid = buf.pull_bytes(destination_cid_length)\n \n + source_cid_length = buf.pull_uint8()\n - source_cid_length = decode_cid_length(cid_lengths % 16)\n source_cid = buf.pull_bytes(source_cid_length)\n \n if version == QuicProtocolVersion.NEGOTIATION:\n # version negotiation\n packet_type = None\n rest_length = buf.capacity - buf.tell()\n else:\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n if packet_type == PACKET_TYPE_INITIAL:\n token_length = buf.pull_uint_var()\n token = buf.pull_bytes(token_length)\n rest_length = buf.pull_uint_var()\n elif packet_type == PACKET_TYPE_RETRY:\n + original_destination_cid_length = buf.pull_uint8()\n - original_destination_cid_length = decode_cid_length(first_byte & 0xF)\n original_destination_cid = buf.pull_bytes(\n original_destination_cid_length\n )\n token = buf.pull_bytes(buf.capacity - buf.tell())\n rest_length = 0\n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_\n===========changed ref 1===========\n # module: aioquic.packet\n def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader:\n # offset: 1\n \n else:\n rest_length = buf.pull_uint_var()\n \n return QuicHeader(\n is_long_header=True,\n version=version,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=source_cid,\n original_destination_cid=original_destination_cid,\n token=token,\n rest_length=rest_length,\n )\n else:\n # short header packet\n if not (first_byte & PACKET_FIXED_BIT):\n raise ValueError(\"Packet fixed bit is zero\")\n \n packet_type = first_byte & PACKET_TYPE_MASK\n destination_cid = buf.pull_bytes(host_cid_length)\n return QuicHeader(\n is_long_header=False,\n version=None,\n packet_type=packet_type,\n destination_cid=destination_cid,\n source_cid=b\"\",\n token=b\"\",\n rest_length=buf.capacity - buf.tell(),\n )\n \n===========changed ref 2===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n "}}},{"rowIdx":3017,"cells":{"path":{"kind":"string","value":"tests.test_packet/PacketTest.test_encode_quic_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n <2>: source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n <3>: supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class PacketTest(TestCase):\n def test_encode_quic_version_negotiation(self):\n <0> data = encode_quic_version_negotiation(\n <1> destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n <2> source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n <3> supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n <4> )\n <5> self.assertEqual(data[1:], load(\"version_negotiation.bin\")[1:])\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet\n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.test_packet.PacketTest.test_encode_quic_version_negotiation\n data = encode_quic_version_negotiation(\n destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n )\n \n at: tests.utils\n load(name)\n \n at: unittest.case\n TestCase(methodName: str=...)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n + buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n - buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n with self.assertRaises(ValueError) as cm:\n pull_quic_header(buf, host_cid_length=8)\n self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n \n===========changed ref 2===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 5===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_retry(self):\n buf = Buffer(data=load(\"retry.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19)\n self.assertEqual(header.packet_type, PACKET_TYPE_RETRY)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"fee746dfde699d61\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"c98343fe8f5f0ff4\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"59aa0942fd2f11e9\"))\n self.assertEqual(\n - header.source_cid,\n - binascii.unhexlify(\"c17f7c0473e635351b85a17e9f3296d7246c\"),\n - )\n - self.assertEqual(\n + header.original_destination_cid, binascii.unhexlify(\"d61e7448e0d63dff\")\n - header.original_destination_cid, binascii.unhexlify(\"85abb547bf28be97\")\n )\n self.assertEqual(\n header.token,\n binascii.unhexlify(\n + \"5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764\"\n - \"01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97\"\n ),\n )\n self.assertEqual(header.rest_length, 0)\n + "}}},{"rowIdx":3018,"cells":{"path":{"kind":"string","value":"tests.test_packet/FrameTest.test_new_connection_id"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <1>: \"0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n \"02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n<11>: 0,\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class FrameTest(TestCase):\n def test_new_connection_id(self):\n <0> data = binascii.unhexlify(\n <1> \"02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n <2> )\n <3> \n <4> # parse\n <5> buf = Buffer(data=data)\n <6> frame = packet.pull_new_connection_id_frame(buf)\n <7> self.assertEqual(\n <8> frame,\n <9> (\n<10> 2,\n<11> binascii.unhexlify(\"7813f3d9e45e0cacbb491b4b66b039f204\"),\n<12> binascii.unhexlify(\"06f68fede38ec4c31aba8ab1245244e8\"),\n<13> ),\n<14> )\n<15> \n<16> # serialize\n<17> buf = Buffer(capacity=len(data))\n<18> packet.push_new_connection_id_frame(buf, *frame)\n<19> self.assertEqual(buf.data, data)\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.packet\n pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]\n \n push_new_connection_id_frame(buf: Buffer, sequence_number: int, retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes) -> None\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.test_packet.FrameTest.test_new_connection_id\n data = binascii.unhexlify(\n \"0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def push_new_connection_id_frame(\n buf: Buffer,\n sequence_number: int,\n + retire_prior_to: int,\n connection_id: bytes,\n stateless_reset_token: bytes,\n ) -> None:\n assert len(stateless_reset_token) == 16\n buf.push_uint_var(sequence_number)\n + buf.push_uint_var(retire_prior_to)\n buf.push_uint8(len(connection_id))\n buf.push_bytes(connection_id)\n buf.push_bytes(stateless_reset_token)\n \n===========changed ref 1===========\n # module: aioquic.packet\n + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]:\n - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]:\n sequence_number = buf.pull_uint_var()\n + retire_prior_to = buf.pull_uint_var()\n length = buf.pull_uint8()\n connection_id = buf.pull_bytes(length)\n stateless_reset_token = buf.pull_bytes(16)\n + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token)\n - return (sequence_number, connection_id, stateless_reset_token)\n \n===========changed ref 2===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n + buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n - buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n with self.assertRaises(ValueError) as cm:\n pull_quic_header(buf, host_cid_length=8)\n self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_encode_quic_version_negotiation(self):\n data = encode_quic_version_negotiation(\n + destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n - destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n + source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n - source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n )\n self.assertEqual(data[1:], load(\"version_negotiation.bin\")[1:])\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 5===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 6===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n "}}},{"rowIdx":3019,"cells":{"path":{"kind":"string","value":"tests.test_packet/FrameTest.test_transport_close"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: data = binascii.unhexlify(\"0a0212696c6c6567616c2041434b206672616d6500\")\n data = binascii.unhexlify(\"000a0212696c6c6567616c2041434b206672616d6500\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class FrameTest(TestCase):\n def test_transport_close(self):\n <0> data = binascii.unhexlify(\"000a0212696c6c6567616c2041434b206672616d6500\")\n <1> \n <2> # parse\n <3> buf = Buffer(data=data)\n <4> frame = packet.pull_transport_close_frame(buf)\n <5> self.assertEqual(frame, (10, 2, \"illegal ACK frame\\x00\"))\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.packet\n pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]\n \n at: tests.test_packet.FrameTest.test_transport_close\n data = binascii.unhexlify(\"0a0212696c6c6567616c2041434b206672616d6500\")\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n frame_type = buf.pull_uint_var()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, frame_type, reason_phrase)\n \n===========changed ref 1===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_new_connection_id(self):\n data = binascii.unhexlify(\n + \"0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n - \"02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n )\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_new_connection_id_frame(buf)\n self.assertEqual(\n frame,\n (\n 2,\n + 0,\n binascii.unhexlify(\"7813f3d9e45e0cacbb491b4b66b039f204\"),\n binascii.unhexlify(\"06f68fede38ec4c31aba8ab1245244e8\"),\n ),\n )\n \n # serialize\n buf = Buffer(capacity=len(data))\n packet.push_new_connection_id_frame(buf, *frame)\n self.assertEqual(buf.data, data)\n \n===========changed ref 2===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n + buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n - buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n with self.assertRaises(ValueError) as cm:\n pull_quic_header(buf, host_cid_length=8)\n self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_encode_quic_version_negotiation(self):\n data = encode_quic_version_negotiation(\n + destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n - destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n + source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n - source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n )\n self.assertEqual(data[1:], load(\"version_negotiation.bin\")[1:])\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 5===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n \n===========changed ref 6===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_client(self):\n buf = Buffer(data=load(\"initial_client.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"858b39368b8e3c6e\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"90ed1e1c7b04b5d3\"))\n self.assertEqual(header.source_cid, b\"\")\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 1262)\n - self.assertEqual(header.rest_length, 1263)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n "}}},{"rowIdx":3020,"cells":{"path":{"kind":"string","value":"tests.test_packet/FrameTest.test_application_close"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: data = binascii.unhexlify(\"0008676f6f6462796500\")\n data = binascii.unhexlify(\"000008676f6f6462796500\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class FrameTest(TestCase):\n def test_application_close(self):\n <0> data = binascii.unhexlify(\"000008676f6f6462796500\")\n <1> \n <2> # parse\n <3> buf = Buffer(data=data)\n <4> frame = packet.pull_application_close_frame(buf)\n <5> self.assertEqual(frame, (0, \"goodbye\\x00\"))\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.packet\n pull_application_close_frame(buf: Buffer) -> Tuple[int, str]\n \n at: tests.test_packet.FrameTest.test_application_close\n data = binascii.unhexlify(\"0008676f6f6462796500\")\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 1===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_transport_close(self):\n + data = binascii.unhexlify(\"0a0212696c6c6567616c2041434b206672616d6500\")\n - data = binascii.unhexlify(\"000a0212696c6c6567616c2041434b206672616d6500\")\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_transport_close_frame(buf)\n self.assertEqual(frame, (10, 2, \"illegal ACK frame\\x00\"))\n \n===========changed ref 2===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_new_connection_id(self):\n data = binascii.unhexlify(\n + \"0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n - \"02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n )\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_new_connection_id_frame(buf)\n self.assertEqual(\n frame,\n (\n 2,\n + 0,\n binascii.unhexlify(\"7813f3d9e45e0cacbb491b4b66b039f204\"),\n binascii.unhexlify(\"06f68fede38ec4c31aba8ab1245244e8\"),\n ),\n )\n \n # serialize\n buf = Buffer(capacity=len(data))\n packet.push_new_connection_id_frame(buf, *frame)\n self.assertEqual(buf.data, data)\n \n===========changed ref 3===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n + buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n - buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n with self.assertRaises(ValueError) as cm:\n pull_quic_header(buf, host_cid_length=8)\n self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_encode_quic_version_negotiation(self):\n data = encode_quic_version_negotiation(\n + destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n - destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n + source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n - source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n )\n self.assertEqual(data[1:], load(\"version_negotiation.bin\")[1:])\n \n===========changed ref 5===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 6===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n "}}},{"rowIdx":3021,"cells":{"path":{"kind":"string","value":"tests.test_packet/FrameTest.test_application_close_not_utf8"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":" <0>: data = binascii.unhexlify(\"0008676f6f6462798200\")\n data = binascii.unhexlify(\"000008676f6f6462798200\")\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet\n class FrameTest(TestCase):\n def test_application_close_not_utf8(self):\n <0> data = binascii.unhexlify(\"000008676f6f6462798200\")\n <1> \n <2> # parse\n <3> buf = Buffer(data=data)\n <4> frame = packet.pull_application_close_frame(buf)\n <5> self.assertEqual(frame, (0, \"\"))\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.packet\n pull_application_close_frame(buf: Buffer) -> Tuple[int, str]\n \n at: tests.test_packet.FrameTest.test_application_close_not_utf8\n data = binascii.unhexlify(\"0008676f6f6462798200\")\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]:\n + error_code = buf.pull_uint_var()\n - error_code = buf.pull_uint16()\n reason_length = buf.pull_uint_var()\n reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length))\n return (error_code, reason_phrase)\n \n===========changed ref 1===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_application_close(self):\n + data = binascii.unhexlify(\"0008676f6f6462796500\")\n - data = binascii.unhexlify(\"000008676f6f6462796500\")\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_application_close_frame(buf)\n self.assertEqual(frame, (0, \"goodbye\\x00\"))\n \n===========changed ref 2===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_transport_close(self):\n + data = binascii.unhexlify(\"0a0212696c6c6567616c2041434b206672616d6500\")\n - data = binascii.unhexlify(\"000a0212696c6c6567616c2041434b206672616d6500\")\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_transport_close_frame(buf)\n self.assertEqual(frame, (10, 2, \"illegal ACK frame\\x00\"))\n \n===========changed ref 3===========\n # module: tests.test_packet\n class FrameTest(TestCase):\n def test_new_connection_id(self):\n data = binascii.unhexlify(\n + \"0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n - \"02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8\"\n )\n \n # parse\n buf = Buffer(data=data)\n frame = packet.pull_new_connection_id_frame(buf)\n self.assertEqual(\n frame,\n (\n 2,\n + 0,\n binascii.unhexlify(\"7813f3d9e45e0cacbb491b4b66b039f204\"),\n binascii.unhexlify(\"06f68fede38ec4c31aba8ab1245244e8\"),\n ),\n )\n \n # serialize\n buf = Buffer(capacity=len(data))\n packet.push_new_connection_id_frame(buf, *frame)\n self.assertEqual(buf.data, data)\n \n===========changed ref 4===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_long_header_no_fixed_bit(self):\n + buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\\x00\")\n - buf = Buffer(data=b\"\\x80\\xff\\x00\\x00\\x11\\x00\")\n with self.assertRaises(ValueError) as cm:\n pull_quic_header(buf, host_cid_length=8)\n self.assertEqual(str(cm.exception), \"Packet fixed bit is zero\")\n \n===========changed ref 5===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_encode_quic_version_negotiation(self):\n data = encode_quic_version_negotiation(\n + destination_cid=binascii.unhexlify(\"9aac5a49ba87a849\"),\n - destination_cid=binascii.unhexlify(\"dae1889b81a91c26\"),\n + source_cid=binascii.unhexlify(\"f92f4336fa951ba1\"),\n - source_cid=binascii.unhexlify(\"f49243784f9bf3be\"),\n + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22],\n - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],\n )\n self.assertEqual(data[1:], load(\"version_negotiation.bin\")[1:])\n \n===========changed ref 6===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_version_negotiation(self):\n buf = Buffer(data=load(\"version_negotiation.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION)\n self.assertEqual(header.packet_type, None)\n + self.assertEqual(header.destination_cid, binascii.unhexlify(\"9aac5a49ba87a849\"))\n - self.assertEqual(header.destination_cid, binascii.unhexlify(\"dae1889b81a91c26\"))\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"f92f4336fa951ba1\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"f49243784f9bf3be\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n self.assertEqual(header.rest_length, 8)\n + self.assertEqual(buf.tell(), 23)\n - self.assertEqual(buf.tell(), 22)\n \n===========changed ref 7===========\n # module: tests.test_packet\n class PacketTest(TestCase):\n def test_pull_initial_server(self):\n buf = Buffer(data=load(\"initial_server.bin\"))\n header = pull_quic_header(buf, host_cid_length=8)\n self.assertTrue(header.is_long_header)\n + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22)\n - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17)\n self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL)\n self.assertEqual(header.destination_cid, b\"\")\n + self.assertEqual(header.source_cid, binascii.unhexlify(\"195c68344e28d479\"))\n - self.assertEqual(header.source_cid, binascii.unhexlify(\"0fcee9852fde8780\"))\n self.assertEqual(header.original_destination_cid, b\"\")\n self.assertEqual(header.token, b\"\")\n + self.assertEqual(header.rest_length, 184)\n - self.assertEqual(header.rest_length, 182)\n + self.assertEqual(buf.tell(), 18)\n - self.assertEqual(buf.tell(), 17)\n "}}},{"rowIdx":3022,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_empty"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<11>: self.assertEqual(builder.remaining_space, 1236)\n self.assertEqual(builder.remaining_space, 1237)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_empty(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> \n<10> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<11> self.assertEqual(builder.remaining_space, 1237)\n<12> \n<13> # nothing to write\n<14> \n<15> self.assertFalse(builder.end_packet())\n<16> self.assertEqual(builder.buffer.tell(), 0)\n<17> self.assertEqual(builder.packet_number, 0)\n<18> \n<19> datagrams, packets = builder.flush()\n<20> self.assertEqual(len(datagrams), 0)\n<21> self.assertEqual(packets, [])\n<22> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.packet_builder\n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertFalse(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n + header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n - header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n===========changed ref 3===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def end_packet(self) -> bool:\n \"\"\"\n Ends the current packet.\n \n Returns `True` if the packet contains data, `False` otherwise.\n \"\"\"\n buf = self.buffer\n empty = True\n packet_size = buf.tell() - self._packet_start\n if packet_size > self._header_size:\n empty = False\n \n # pad initial datagram\n if self._pad_first_datagram:\n buf.push_bytes(bytes(self.remaining_space))\n packet_size = buf.tell() - self._packet_start\n self._pad_first_datagram = False\n \n # write header\n if self._packet_long_header:\n length = (\n packet_size\n - self._header_size\n + PACKET_NUMBER_SEND_SIZE\n + self._packet_crypto.aead_tag_size\n )\n \n buf.seek(self._packet_start)\n buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1))\n buf.push_uint32(self._version)\n + buf.push_uint8(len(self._peer_cid))\n - buf.push_uint8(\n - (encode_cid_length(len(self._peer_cid)) << 4)\n - | encode_cid_length(len(self._host_cid))\n - )\n buf.push_bytes(self._peer_cid)\n + buf.push_uint8(len(self._host_cid))\n buf.push_bytes(self._host_cid)\n if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n buf.push_uint_var(len(self._peer_token))\n buf.push_bytes(self._peer_token)\n buf.push_uint16(length | 0x4000)\n buf.push_uint16(self._packet_number & 0xFFFF)\n else:\n buf.seek(self._packet"}}},{"rowIdx":3023,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<14>: self.assertEqual(builder.remaining_space, 1236)\n self.assertEqual(builder.remaining_space, 1237)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_padding(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> pad_first_datagram=True,\n <4> peer_cid=bytes(8),\n <5> peer_token=b\"\",\n <6> spin_bit=False,\n <7> version=QuicProtocolVersion.DRAFT_20,\n <8> )\n <9> crypto = CryptoPair()\n<10> crypto.setup_initial(bytes(8), is_client=True)\n<11> \n<12> # INITIAL, fully padded\n<13> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<14> self.assertEqual(builder.remaining_space, 1237)\n<15> builder.start_frame(QuicFrameType.CRYPTO)\n<16> builder.buffer.push_bytes(bytes(100))\n<17> self.assertTrue(builder.end_packet())\n<18> self.assertEqual(builder.buffer.tell(), 1280)\n<19> \n<20> # check datagrams\n<21> datagrams, packets = builder.flush()\n<22> self.assertEqual(len(datagrams), 1)\n<23> self.assertEqual(len(datagrams[0]), 1280)\n<24> self.assertEqual(\n<25> packets,\n<26> [\n<27> QuicSentPacket(\n<28> epoch=Epoch.INITIAL,\n<29> in_flight=True,\n<30> is_ack_eliciting=True,\n<31> is_crypto_packet=True,\n<32> packet_number=0,\n<33> sent_bytes=1280,\n<34> )\n<35> ],\n<36> )\n<37> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n + header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n - header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3024,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<13>: self.assertEqual(builder.remaining_space, 1236)\n self.assertEqual(builder.remaining_space, 1237)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_short_header(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> crypto.setup_initial(bytes(8), is_client=True)\n<10> \n<11> # INITIAL, fully padded\n<12> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<13> self.assertEqual(builder.remaining_space, 1237)\n<14> builder.start_frame(QuicFrameType.CRYPTO)\n<15> builder.buffer.push_bytes(bytes(builder.remaining_space))\n<16> self.assertTrue(builder.end_packet())\n<17> self.assertEqual(builder.buffer.tell(), 1280)\n<18> \n<19> # ONE_RTT, fully padded\n<20> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)\n<21> self.assertEqual(builder.remaining_space, 1253)\n<22> builder.start_frame(QuicFrameType.STREAM_BASE)\n<23> builder.buffer.push_bytes(bytes(builder.remaining_space))\n<24> self.assertTrue(builder.end_packet())\n<25> self.assertEqual(builder.buffer.tell(), 0)\n<26> \n<27> # check datagrams\n<28> datagrams, packets = builder.flush()\n<29> self.assertEqual(len(datagrams), 2)\n<30> self.assertEqual(len(datagrams[0]), 1280)\n<31> self.assertEqual(len(datagrams[1]), 1280)\n<32> self.assertEqual(\n<33> packets,\n<34> [\n<35> QuicSentPacket(\n<36> epoch=Epoch.INITIAL,\n<37> in_flight=True,\n<38> is_ack_eliciting=True,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_short_header(self):\n # offset: 1\n packet_number=0,\n sent_bytes=1280,\n ),\n QuicSentPacket(\n epoch=Epoch.ONE_RTT,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=False,\n packet_number=1,\n sent_bytes=1280,\n ),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n + header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n - header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3025,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8dcde337e514e95159d3cdfd6fe2c6f4860d0770"},"commit_message":{"kind":"string","value":"[draft-22] first round of updates for draft 22"},"ground_truth":{"kind":"string","value":"<13>: self.assertEqual(builder.remaining_space, 1236)\n self.assertEqual(builder.remaining_space, 1237)\n<16>: self.assertEqual(builder.buffer.tell(), 228)\n self.assertEqual(builder.buffer.tell(), 227)\n<18>: self.assertEqual(builder.buffer.tell(), 244)\n self.assertEqual(builder.buffer.tell(), 243)\n<22>: self.assertEqual(builder.buffer.tell(), 271)\n self.assertEqual(builder.buffer.tell(), 269)\n<23>: self.assertEqual(builder.remaining_space, 993)\n self.assertEqual(builder.remaining_space, 995)\n<26>: self.assertEqual(builder.buffer.tell(), 571)\n self.assertEqual(builder.buffer.tell(), 569)\n<28>: self.assertEqual(builder.buffer.tell(), 587)\n self.assertEqual(builder.buffer.tell(), 585)\n<32>: self.assertEqual(builder.remaining_space, 666)\n self.assertEqual(builder.remaining_space, 668)\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_long_header(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> crypto.setup_initial(bytes(8), is_client=True)\n<10> \n<11> # INITIAL\n<12> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<13> self.assertEqual(builder.remaining_space, 1237)\n<14> builder.start_frame(QuicFrameType.CRYPTO)\n<15> builder.buffer.push_bytes(bytes(199))\n<16> self.assertEqual(builder.buffer.tell(), 227)\n<17> self.assertTrue(builder.end_packet())\n<18> self.assertEqual(builder.buffer.tell(), 243)\n<19> \n<20> # HANDSHAKE\n<21> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto)\n<22> self.assertEqual(builder.buffer.tell(), 269)\n<23> self.assertEqual(builder.remaining_space, 995)\n<24> builder.start_frame(QuicFrameType.CRYPTO)\n<25> builder.buffer.push_bytes(bytes(299))\n<26> self.assertEqual(builder.buffer.tell(), 569)\n<27> self.assertTrue(builder.end_packet())\n<28> self.assertEqual(builder.buffer.tell(), 585)\n<29> \n<30> # ONE_RTT\n<31> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)\n<32> self.assertEqual(builder.remaining_space, 668)\n<33> builder.start_frame(QuicFrameType.CRYPTO)\n<34> builder.buffer.push_bytes(bytes(299))\n<35> self.assertTrue(builder.end_packet())\n<36> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_long_header(self):\n # offset: 1\n \n # check datagrams\n datagrams, packets = builder.flush()\n self.assertEqual(len(datagrams), 1)\n self.assertEqual(len(datagrams[0]), 912)\n self.assertEqual(\n packets,\n [\n QuicSentPacket(\n epoch=Epoch.INITIAL,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=0,\n sent_bytes=243,\n ),\n QuicSentPacket(\n epoch=Epoch.HANDSHAKE,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=1,\n sent_bytes=342,\n ),\n QuicSentPacket(\n epoch=Epoch.ONE_RTT,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=2,\n sent_bytes=327,\n ),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet\n class QuicProtocolVersion(IntEnum):\n NEGOTIATION = 0\n DRAFT_17 = 0xFF000011\n DRAFT_18 = 0xFF000012\n DRAFT_19 = 0xFF000013\n DRAFT_20 = 0xFF000014\n + DRAFT_21 = 0xFF000015\n + DRAFT_22 = 0xFF000016\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n + header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n - header_size = 10 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3026,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":"<14>: self.alpn_cb: Optional[AlpnHandler] = None\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.certificate: Optional[x509.Certificate] = None\n <3> self.certificate_private_key: Optional[\n <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <5> ] = None\n <6> self.early_data_accepted = False\n <7> self.handshake_extensions: List[Extension] = []\n <8> self.key_schedule: Optional[KeySchedule] = None\n <9> self.received_extensions: Optional[List[Extension]] = None\n<10> self.session_ticket: Optional[SessionTicket] = None\n<11> self.server_name: Optional[str] = None\n<12> \n<13> # callbacks\n<14> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<15> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<16> self.update_traffic_key_cb: Callable[\n<17> [Direction, Epoch, CipherSuite, bytes], None\n<18> ] = lambda d, e, c, s: None\n<19> \n<20> # supported parameters\n<21> self._cipher_suites = [\n<22> CipherSuite.AES_256_GCM_SHA384,\n<23> CipherSuite.AES_128_GCM_SHA256,\n<24> CipherSuite.CHACHA20_POLY1305_SHA256,\n<25> ]\n<26> self._compression_methods = [CompressionMethod.NULL]\n<27> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE]\n<28> self._signature_algorithms = [\n<29> SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n<30> SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n<31> SignatureAlgorithm.RSA_PKCS1_SHA256,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n # offset: 1\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n KeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n 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))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n 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))\n \n AlpnHandler = Callable[[str], None]\n \n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n \n \n===========unchanged ref 1===========\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.client_random = peer_hello.random\n \n \n===========unchanged ref 2===========\n self.session_id = peer_hello.session_id\n \n self.received_extensions = peer_hello.other_extensions\n \n self.key_schedule = KeySchedule(cipher_suite)\n \n self._session_resumed = True\n \n self.early_data_accepted = True\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[key_share[0]](), default_backend()\n )\n \n self._new_session_ticket = NewSessionTicket(\n ticket_lifetime=86400,\n ticket_age_add=struct.unpack(\"I\", os.urandom(4))[0],\n ticket_nonce=b\"\",\n ticket=os.urandom(64),\n max_early_data_size=0xFFFFFFFF,\n )\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: aioquic.tls.Context._setup_traffic_protection\n self._enc_key = key\n \n self._dec_key = key\n \n at: aioquic.tls.Context.handle_message\n self._receive_buffer += input_data\n self._receive_buffer = self._receive_buffer[message_length:]\n \n at: logging\n Logger(name: str, level: _Level=...)\n \n LoggerAdapter(logger: Logger, extra: Mapping[str, Any])\n \n at: os\n urandom(size: int, /) -> bytes\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n "}}},{"rowIdx":3027,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_handle_encrypted_extensions"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":" <5>: if self.alpn_cb:\n self.alpn_cb(self.alpn_negotiated)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None:\n <0> encrypted_extensions = pull_encrypted_extensions(input_buf)\n <1> \n <2> self.alpn_negotiated = encrypted_extensions.alpn_protocol\n <3> self.early_data_accepted = encrypted_extensions.early_data\n <4> self.received_extensions = encrypted_extensions.other_extensions\n <5> \n <6> self._setup_traffic_protection(\n <7> Direction.ENCRYPT, Epoch.HANDSHAKE, b\"c hs traffic\"\n <8> )\n <9> self.key_schedule.update_hash(input_buf.data)\n<10> \n<11> # if the server accepted our PSK we are done, other we want its certificate\n<12> if self._session_resumed:\n<13> self._set_state(State.CLIENT_EXPECT_FINISHED)\n<14> else:\n<15> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)\n<16> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.tls\n Direction()\n \n Epoch()\n \n State()\n \n pull_encrypted_extensions(buf: Buffer) -> EncryptedExtensions\n \n at: aioquic.tls.Context\n _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None\n \n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.alpn_negotiated: Optional[str] = None\n \n self.early_data_accepted = False\n \n self.key_schedule: Optional[KeySchedule] = None\n \n self.received_extensions: Optional[List[Extension]] = None\n \n self.alpn_cb: Optional[AlpnHandler] = None\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.received_extensions = peer_hello.other_extensions\n \n self.key_schedule = KeySchedule(cipher_suite)\n \n self.early_data_accepted = True\n \n at: aioquic.tls.EncryptedExtensions\n alpn_protocol: Optional[str] = None\n \n early_data: bool = False\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n at: aioquic.tls.KeySchedule\n update_hash(data: bytes) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n===========changed ref 1===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n self.alpn_negotiated: Optional[str] = None\n self.alpn_protocols: Optional[List[str]] = None\n self.certificate: Optional[x509.Certificate] = None\n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n self.early_data_accepted = False\n self.handshake_extensions: List[Extension] = []\n self.key_schedule: Optional[KeySchedule] = None\n self.received_extensions: Optional[List[Extension]] = None\n self.session_ticket: Optional[SessionTicket] = None\n self.server_name: Optional[str] = None\n \n # callbacks\n + self.alpn_cb: Optional[AlpnHandler] = None\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n # supported parameters\n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n self._compression_methods = [CompressionMethod.NULL]\n self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE]\n self._signature_algorithms = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n # offset: 1\n SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n "}}},{"rowIdx":3028,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._initialize"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":"<33>: self.tls.alpn_cb = self._alpn_handler\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n <0> # TLS\n <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n <2> self.tls.alpn_protocols = self._configuration.alpn_protocols\n <3> self.tls.certificate = self._configuration.certificate\n <4> self.tls.certificate_private_key = self._configuration.private_key\n <5> self.tls.handshake_extensions = [\n <6> (\n <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n <8> self._serialize_transport_parameters(),\n <9> )\n<10> ]\n<11> self.tls.server_name = self._configuration.server_name\n<12> \n<13> # TLS session resumption\n<14> session_ticket = self._configuration.session_ticket\n<15> if (\n<16> self._is_client\n<17> and session_ticket is not None\n<18> and session_ticket.is_valid\n<19> and session_ticket.server_name == self._configuration.server_name\n<20> ):\n<21> self.tls.session_ticket = self._configuration.session_ticket\n<22> \n<23> # parse saved QUIC transport parameters - for 0-RTT\n<24> if session_ticket.max_early_data_size == 0xFFFFFFFF:\n<25> for ext_type, ext_data in session_ticket.other_extensions:\n<26> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n<27> self._parse_transport_parameters(\n<28> ext_data, from_session_ticket=True\n<29> )\n<30> break\n<31> \n<32> # TLS callbacks\n<33> if self._session_ticket_fetcher is not None:\n<34> self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n<35> if self._session_ticket_handler is not None:\n<36> self.tls.new_session_ticket_cb = self._session_ticket_handler\n<37> self.tls.update_traffic_key_cb = self._update_traffic_key\n<38> \n<39> #"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection.QuicConnection\n _alpn_handler(alpn_protocol: str) -> None\n \n _parse_transport_parameters(data: bytes, from_session_ticket: bool=False) -> None\n \n _serialize_transport_parameters() -> bytes\n \n _update_traffic_key(direction: tls.Direction, epoch: tls.Epoch, cipher_suite: tls.CipherSuite, secret: bytes) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n \n self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n \n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n self._session_ticket_fetcher = session_ticket_fetcher\n \n self._session_ticket_handler = session_ticket_handler\n \n \n===========unchanged ref 1===========\n at: aioquic.connection.QuicConnection._get_or_create_stream\n stream = self._streams[stream_id] = QuicStream(\n connection=self,\n stream_id=stream_id,\n max_stream_data_local=max_stream_data_local,\n max_stream_data_remote=max_stream_data_remote,\n )\n stream = self._streams.get(stream_id, None)\n \n max_stream_data_local = self._local_max_stream_data_uni\n max_stream_data_local = self._local_max_stream_data_bidi_remote\n \n max_stream_data_remote = 0\n max_stream_data_remote = self._remote_max_stream_data_bidi_local\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.recovery\n QuicPacketSpace()\n \n at: aioquic.stream\n QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0)\n \n at: aioquic.tls\n Epoch()\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None)\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.certificate: Optional[x509.Certificate] = None\n \n self.certificate_private_key: Optional[\n Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n ] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n \n===========unchanged ref 2===========\n self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n at: aioquic.tls.SessionTicket\n age_add: int\n \n cipher_suite: CipherSuite\n \n not_valid_after: datetime.datetime\n \n not_valid_before: datetime.datetime\n \n resumption_secret: bytes\n \n server_name: str\n \n ticket: bytes\n \n max_early_data_size: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n \n===========changed ref 0===========\n # module: aioquic.connection\n class QuicConnection:\n + # Private\n + \n + def _alpn_handler(self, alpn_protocol: str) -> None:\n + \"\"\"\n + Callback which is invoked by the TLS engine when ALPN negotiation completes.\n + \"\"\"\n + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol))\n + \n===========changed ref 1===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None:\n encrypted_extensions = pull_encrypted_extensions(input_buf)\n \n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n self.early_data_accepted = encrypted_extensions.early_data\n self.received_extensions = encrypted_extensions.other_extensions\n + if self.alpn_cb:\n + self.alpn_cb(self.alpn_negotiated)\n \n self._setup_traffic_protection(\n Direction.ENCRYPT, Epoch.HANDSHAKE, b\"c hs traffic\"\n )\n self.key_schedule.update_hash(input_buf.data)\n \n # if the server accepted our PSK we are done, other we want its certificate\n if self._session_resumed:\n self._set_state(State.CLIENT_EXPECT_FINISHED)\n else:\n self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)\n "}}},{"rowIdx":3029,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":" <2>: event = client.next_event()\n self.assertEqual(type(event), events.ProtocolNegotiated)\n self.assertEqual(event.alpn_protocol, None)\n<11>: event = server.next_event()\n self.assertEqual(type(event), events.ProtocolNegotiated)\n self.assertEqual(event.alpn_protocol, None)\n"},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect(self):\n <0> with client_and_server() as (client, server):\n <1> # check handshake completed\n <2> event = client.next_event()\n <3> self.assertEqual(type(event), events.HandshakeCompleted)\n <4> self.assertEqual(event.alpn_protocol, None)\n <5> self.assertEqual(event.early_data_accepted, False)\n <6> self.assertEqual(event.session_resumed, False)\n <7> for i in range(7):\n <8> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n <9> self.assertIsNone(client.next_event())\n<10> \n<11> event = server.next_event()\n<12> self.assertEqual(type(event), events.HandshakeCompleted)\n<13> self.assertEqual(event.alpn_protocol, None)\n<14> self.assertEqual(event.early_data_accepted, False)\n<15> self.assertEqual(event.session_resumed, False)\n<16> for i in range(7):\n<17> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n<18> self.assertIsNone(server.next_event())\n<19> \n<20> # check each endpoint has available connection IDs for the peer\n<21> self.assertEqual(\n<22> sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n<23> )\n<24> self.assertEqual(\n<25> sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n<26> )\n<27> \n<28> # client closes the connection\n<29> client.close()\n<30> self.assertEqual(transfer(client, server), 1)\n<31> \n<32> # check connection closes on the client side\n<33> client.handle_timer(client.get_timer())\n<34> event = client.next_event()\n<35> self.assertEqual(type(event), events.ConnectionTerminated)\n<36> self.assertEqual("},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n self.assertEqual(event.frame_type, None)\n self.assertEqual(event.reason_phrase, \"\")\n self.assertIsNone(client.next_event())\n \n # check connection closes on the server side\n server.handle_timer(server.get_timer())\n event = server.next_event()\n self.assertEqual(type(event), events.ConnectionTerminated)\n self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR)\n self.assertEqual(event.frame_type, None)\n self.assertEqual(event.reason_phrase, \"\")\n self.assertIsNone(server.next_event())\n \n \n===========unchanged ref 0===========\n at: aioquic.events\n ConnectionIdIssued(connection_id: bytes)\n \n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n sequence_numbers(connection_ids)\n \n transfer(sender, receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n + # Private\n + \n + def _alpn_handler(self, alpn_protocol: str) -> None:\n + \"\"\"\n + Callback which is invoked by the TLS engine when ALPN negotiation completes.\n + \"\"\"\n + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol))\n + \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None:\n encrypted_extensions = pull_encrypted_extensions(input_buf)\n \n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n self.early_data_accepted = encrypted_extensions.early_data\n self.received_extensions = encrypted_extensions.other_extensions\n + if self.alpn_cb:\n + self.alpn_cb(self.alpn_negotiated)\n \n self._setup_traffic_protection(\n Direction.ENCRYPT, Epoch.HANDSHAKE, b\"c hs traffic\"\n )\n self.key_schedule.update_hash(input_buf.data)\n \n # if the server accepted our PSK we are done, other we want its certificate\n if self._session_resumed:\n self._set_state(State.CLIENT_EXPECT_FINISHED)\n else:\n self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # TLS\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n self.tls.alpn_protocols = self._configuration.alpn_protocols\n self.tls.certificate = self._configuration.certificate\n self.tls.certificate_private_key = self._configuration.private_key\n self.tls.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n self._serialize_transport_parameters(),\n )\n ]\n self.tls.server_name = self._configuration.server_name\n \n # TLS session resumption\n session_ticket = self._configuration.session_ticket\n if (\n self._is_client\n and session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.server_name == self._configuration.server_name\n ):\n self.tls.session_ticket = self._configuration.session_ticket\n \n # parse saved QUIC transport parameters - for 0-RTT\n if session_ticket.max_early_data_size == 0xFFFFFFFF:\n for ext_type, ext_data in session_ticket.other_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(\n ext_data, from_session_ticket=True\n )\n break\n \n # TLS callbacks\n + self.tls.alpn_cb = self._alpn_handler\n if self._session_ticket_fetcher is not None:\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._session_ticket_handler\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n \n===========changed ref 4===========\n # module: aioquic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # offset: 1\n _traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n self._crypto_buffers = {\n tls.Epoch.INITIAL: Buffer(capacity=4096),\n tls.Epoch.HANDSHAKE: Buffer(capacity=4096),\n tls.Epoch.ONE_RTT: Buffer(capacity=4096),\n }\n self._crypto_streams = {\n tls.Epoch.INITIAL: QuicStream(),\n tls.Epoch.HANDSHAKE: QuicStream(),\n tls.Epoch.ONE_RTT: QuicStream(),\n }\n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._cryptos[tls.Epoch.INITIAL].setup_initial(\n cid=peer_cid, is_client=self._is_client\n )\n \n self._loss.spaces = list(self._spaces.values())\n self._packet_number = 0\n "}}},{"rowIdx":3030,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_alpn"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":" <5>: event = client.next_event()\n self.assertEqual(type(event), events.ProtocolNegotiated)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n<13>: self.assertEqual(type(event), events.ProtocolNegotiated)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n event = server.next_event()\n"},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_alpn(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"hq-22\", \"h3-22\"]},\n <2> server_options={\"alpn_protocols\": [\"hq-22\"]},\n <3> ) as (client, server):\n <4> # check handshake completed\n <5> event = client.next_event()\n <6> self.assertEqual(type(event), events.HandshakeCompleted)\n <7> self.assertEqual(event.alpn_protocol, \"hq-22\")\n <8> for i in range(7):\n <9> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n<10> self.assertIsNone(client.next_event())\n<11> \n<12> event = server.next_event()\n<13> self.assertEqual(type(event), events.HandshakeCompleted)\n<14> self.assertEqual(event.alpn_protocol, \"hq-22\")\n<15> for i in range(7):\n<16> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n<17> self.assertIsNone(server.next_event())\n<18> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool)\n \n at: aioquic.packet\n QuicErrorCode(x: Union[str, bytes, bytearray], base: int)\n QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_connection.QuicConnectionTest.test_connect\n event = client.next_event()\n event = server.next_event()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertIsNone(obj: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect(self):\n with client_and_server() as (client, server):\n # check handshake completed\n + event = client.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, None)\n event = client.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, None)\n self.assertEqual(event.early_data_accepted, False)\n self.assertEqual(event.session_resumed, False)\n for i in range(7):\n self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(client.next_event())\n \n + event = server.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, None)\n event = server.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, None)\n self.assertEqual(event.early_data_accepted, False)\n self.assertEqual(event.session_resumed, False)\n for i in range(7):\n self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(server.next_event())\n \n # check each endpoint has available connection IDs for the peer\n self.assertEqual(\n sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n )\n self.assertEqual(\n sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7]\n )\n \n # client closes the connection\n client.close()\n self.assertEqual(transfer(client, server), 1)\n \n \n===========changed ref 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n # client closes the connection\n client.close()\n self.assertEqual(transfer(client, server), 1)\n \n # check connection closes on the client side\n client.handle_timer(client.get_timer())\n event = client.next_event()\n self.assertEqual(type(event), events.ConnectionTerminated)\n self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR)\n self.assertEqual(event.frame_type, None)\n self.assertEqual(event.reason_phrase, \"\")\n self.assertIsNone(client.next_event())\n \n # check connection closes on the server side\n server.handle_timer(server.get_timer())\n event = server.next_event()\n self.assertEqual(type(event), events.ConnectionTerminated)\n self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR)\n self.assertEqual(event.frame_type, None)\n self.assertEqual(event.reason_phrase, \"\")\n self.assertIsNone(server.next_event())\n \n===========changed ref 2===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n===========changed ref 3===========\n # module: aioquic.connection\n class QuicConnection:\n + # Private\n + \n + def _alpn_handler(self, alpn_protocol: str) -> None:\n + \"\"\"\n + Callback which is invoked by the TLS engine when ALPN negotiation completes.\n + \"\"\"\n + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol))\n + \n===========changed ref 4===========\n # module: aioquic.tls\n class Context:\n def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None:\n encrypted_extensions = pull_encrypted_extensions(input_buf)\n \n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n self.early_data_accepted = encrypted_extensions.early_data\n self.received_extensions = encrypted_extensions.other_extensions\n + if self.alpn_cb:\n + self.alpn_cb(self.alpn_negotiated)\n \n self._setup_traffic_protection(\n Direction.ENCRYPT, Epoch.HANDSHAKE, b\"c hs traffic\"\n )\n self.key_schedule.update_hash(input_buf.data)\n \n # if the server accepted our PSK we are done, other we want its certificate\n if self._session_resumed:\n self._set_state(State.CLIENT_EXPECT_FINISHED)\n else:\n self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)\n \n===========changed ref 5===========\n # module: aioquic.connection\n class QuicConnection:\n def _initialize(self, peer_cid: bytes) -> None:\n # TLS\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n self.tls.alpn_protocols = self._configuration.alpn_protocols\n self.tls.certificate = self._configuration.certificate\n self.tls.certificate_private_key = self._configuration.private_key\n self.tls.handshake_extensions = [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n self._serialize_transport_parameters(),\n )\n ]\n self.tls.server_name = self._configuration.server_name\n \n # TLS session resumption\n session_ticket = self._configuration.session_ticket\n if (\n self._is_client\n and session_ticket is not None\n and session_ticket.is_valid\n and session_ticket.server_name == self._configuration.server_name\n ):\n self.tls.session_ticket = self._configuration.session_ticket\n \n # parse saved QUIC transport parameters - for 0-RTT\n if session_ticket.max_early_data_size == 0xFFFFFFFF:\n for ext_type, ext_data in session_ticket.other_extensions:\n if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS:\n self._parse_transport_parameters(\n ext_data, from_session_ticket=True\n )\n break\n \n # TLS callbacks\n + self.tls.alpn_cb = self._alpn_handler\n if self._session_ticket_fetcher is not None:\n self.tls.get_session_ticket_cb = self._session_ticket_fetcher\n if self._session_ticket_handler is not None:\n self.tls.new_session_ticket_cb = self._session_ticket_handler\n self.tls.update_traffic_key_cb = self._update_traffic_key\n \n # packet spaces\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n "}}},{"rowIdx":3031,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_loss_1"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n <0> \"\"\"\n <1> Check connection is established even in the client's INITIAL is lost.\n <2> \"\"\"\n <3> \n <4> def datagram_sizes(items):\n <5> return [len(x[0]) for x in items]\n <6> \n <7> client = QuicConnection(configuration=QuicConfiguration(is_client=True))\n <8> client._ack_delay = 0\n <9> \n<10> server = QuicConnection(\n<11> configuration=QuicConfiguration(\n<12> is_client=False,\n<13> certificate=SERVER_CERTIFICATE,\n<14> private_key=SERVER_PRIVATE_KEY,\n<15> )\n<16> )\n<17> server._ack_delay = 0\n<18> \n<19> # client sends INITIAL\n<20> now = 0.0\n<21> client.connect(SERVER_ADDR, now=now)\n<22> items = client.datagrams_to_send(now=now)\n<23> self.assertEqual(datagram_sizes(items), [1280])\n<24> self.assertEqual(client.get_timer(), 1.0)\n<25> \n<26> # INITIAL is lost\n<27> now = 1.0\n<28> client.handle_timer(now=now)\n<29> items = client.datagrams_to_send(now=now)\n<30> self.assertEqual(datagram_sizes(items), [1280])\n<31> self.assertEqual(client.get_timer(), 3.0)\n<32> \n<33> # server receives INITIAL, sends INITIAL + HANDSHAKE\n<34> now = 1.1\n<35> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n<36> items = server.datagrams_to_send(now=now)\n<37> self.assertEqual(datagram_sizes(items), [1280, 1079])\n<38> self.assertEqual(server.get_timer(), 2.1)\n<39> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1)\n<40> self.assertEqual(len(server._loss.spaces[1"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n # offset: 1\n \n # handshake continues normally\n now = 1.2\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n client.receive_datagram(items[1][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [1280, 223])\n self.assertAlmostEqual(client.get_timer(), 1.825)\n \n now = 1.3\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n server.receive_datagram(items[1][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [276])\n self.assertAlmostEqual(server.get_timer(), 1.825)\n self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)\n self.assertEqual(len(server._loss.spaces[1].sent_packets), 1)\n \n now = 1.4\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [32])\n self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout\n self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted))\n \n now = 1.5\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [])\n self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout\n===========below chunk 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_1(self):\n # offset: 2\n _sizes(items), [])\n self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout\n self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted))\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n handle_timer(now: float) -> None\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._ack_delay = K_GRANULARITY\n \n \n===========unchanged ref 1===========\n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: tests.test_connection\n CLIENT_ADDR = (\"1.2.3.4\", 1234)\n \n SERVER_ADDR = (\"2.3.4.5\", 4433)\n \n at: tests.test_connection.QuicConnectionTest.test_connect_with_log\n client_log = client_log_file.getvalue()\n \n labels = []\n \n at: tests.utils\n SERVER_CERTIFICATE = x509.load_pem_x509_certificate(\n load(\"ssl_cert.pem\"), backend=default_backend()\n )\n \n SERVER_PRIVATE_KEY = serialization.load_pem_private_key(\n load(\"ssl_key.pem\"), password=None, backend=default_backend()\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None\n assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_alpn(self):\n with client_and_server(\n client_options={\"alpn_protocols\": [\"hq-22\", \"h3-22\"]},\n server_options={\"alpn_protocols\": [\"hq-22\"]},\n ) as (client, server):\n # check handshake completed\n + event = client.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, \"hq-22\")\n event = client.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n for i in range(7):\n self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(client.next_event())\n \n event = server.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, \"hq-22\")\n + event = server.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n for i in range(7):\n self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(server.next_event())\n "}}},{"rowIdx":3032,"cells":{"path":{"kind":"string","value":"tests.test_connection/QuicConnectionTest.test_connect_with_loss_2"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_2(self):\n <0> def datagram_sizes(items):\n <1> return [len(x[0]) for x in items]\n <2> \n <3> client = QuicConnection(configuration=QuicConfiguration(is_client=True))\n <4> client._ack_delay = 0\n <5> \n <6> server = QuicConnection(\n <7> configuration=QuicConfiguration(\n <8> is_client=False,\n <9> certificate=SERVER_CERTIFICATE,\n<10> private_key=SERVER_PRIVATE_KEY,\n<11> )\n<12> )\n<13> server._ack_delay = 0\n<14> \n<15> # client sends INITIAL\n<16> now = 0.0\n<17> client.connect(SERVER_ADDR, now=now)\n<18> items = client.datagrams_to_send(now=now)\n<19> self.assertEqual(datagram_sizes(items), [1280])\n<20> self.assertEqual(client.get_timer(), 1.0)\n<21> \n<22> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost\n<23> now = 0.1\n<24> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n<25> items = server.datagrams_to_send(now=now)\n<26> self.assertEqual(datagram_sizes(items), [1280, 1079])\n<27> self.assertEqual(server.get_timer(), 1.1)\n<28> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1)\n<29> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)\n<30> \n<31> #  client only receives first datagram and sends ACKS\n<32> now = 0.2\n<33> client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n<34> items = client.datagrams_to_send(now=now)\n<35> self.assertEqual(datagram_sizes(items), [97])\n<36> self.assertAlmostEqual(client"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_2(self):\n # offset: 1\n \n #  client PTO - padded HANDSHAKE\n now = client.get_timer() # ~0.625\n client.handle_timer(now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [1280])\n self.assertAlmostEqual(client.get_timer(), 1.25)\n \n # server receives padding, discards INITIAL\n now = 0.725\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [])\n self.assertAlmostEqual(server.get_timer(), 1.1)\n self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)\n self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)\n \n # ACKs are lost, server retransmits HANDSHAKE\n now = server.get_timer()\n server.handle_timer(now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [1280, 900])\n self.assertAlmostEqual(server.get_timer(), 3.1)\n self.assertEqual(len(server._loss.spaces[0].sent_packets), 0)\n self.assertEqual(len(server._loss.spaces[1].sent_packets), 2)\n \n # handshake continues normally\n now = 1.2\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n client.receive_datagram(items[1][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items\n===========below chunk 1===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_loss_2(self):\n # offset: 2\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [334])\n self.assertAlmostEqual(client.get_timer(), 2.45)\n self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted))\n \n now = 1.3\n server.receive_datagram(items[0][0], CLIENT_ADDR, now=now)\n items = server.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [228])\n self.assertAlmostEqual(server.get_timer(), 1.825)\n self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted))\n \n now = 1.4\n client.receive_datagram(items[0][0], SERVER_ADDR, now=now)\n items = client.datagrams_to_send(now=now)\n self.assertEqual(datagram_sizes(items), [32])\n self.assertAlmostEqual(client.get_timer(), 61.4) # idle timeout\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n handle_timer(now: float) -> None\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.connection.QuicConnection.__init__\n self._ack_delay = K_GRANULARITY\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n at: aioquic.recovery.QuicPacketSpace.__init__\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: tests.test_connection\n CLIENT_ADDR = (\"1.2.3.4\", 1234)\n \n SERVER_ADDR = (\"2.3.4.5\", 4433)\n \n \n===========unchanged ref 1===========\n at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_1\n datagram_sizes(items)\n \n client = QuicConnection(configuration=QuicConfiguration(is_client=True))\n \n server = QuicConnection(\n configuration=QuicConfiguration(\n is_client=False,\n certificate=SERVER_CERTIFICATE,\n private_key=SERVER_PRIVATE_KEY,\n )\n )\n \n at: tests.utils\n SERVER_CERTIFICATE = x509.load_pem_x509_certificate(\n load(\"ssl_cert.pem\"), backend=default_backend()\n )\n \n SERVER_PRIVATE_KEY = serialization.load_pem_private_key(\n load(\"ssl_key.pem\"), password=None, backend=default_backend()\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None\n assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None\n \n "}}},{"rowIdx":3033,"cells":{"path":{"kind":"string","value":"examples.http3-server/HttpServer._consume_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"53fbc57b0113e1eedf64954d577ca7c0515c5f01"},"commit_message":{"kind":"string","value":"[connection] add a ProtocolNegotiated event"},"ground_truth":{"kind":"string","value":"<11>: elif isinstance(event, aioquic.events.ProtocolNegotiated):\n elif isinstance(event, aioquic.events.HandshakeCompleted):\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n <0> # process events\n <1> event = connection.next_event()\n <2> while event is not None:\n <3> if isinstance(event, aioquic.events.ConnectionTerminated):\n <4> # remove the connection\n <5> for cid, conn in list(self._connections.items()):\n <6> if conn == connection:\n <7> del self._connections[cid]\n <8> self._http.pop(connection, None)\n <9> self._timer.pop(connection, None)\n<10> return\n<11> elif isinstance(event, aioquic.events.HandshakeCompleted):\n<12> if event.alpn_protocol == \"h3-22\":\n<13> self._http[connection] = H3Connection(connection)\n<14> elif event.alpn_protocol == \"hq-22\":\n<15> self._http[connection] = H0Connection(connection)\n<16> elif isinstance(event, aioquic.events.ConnectionIdIssued):\n<17> self._connections[event.connection_id] = connection\n<18> elif isinstance(event, aioquic.events.ConnectionIdRetired):\n<19> assert self._connections[event.connection_id] == connection\n<20> del self._connections[event.connection_id]\n<21> \n<22> #  pass event to the HTTP layer\n<23> http = self._http.get(connection)\n<24> if http is not None:\n<25> for http_event in http.handle_event(event):\n<26> handle_http_event(http, http_event)\n<27> \n<28> event = connection.next_event()\n<29> \n<30> # send datagrams\n<31> for data, addr in connection.datagrams_to_send(now=self._loop.time()):\n<32> self._transport.sendto(data, addr)\n<33> \n<34> # re-arm timer\n<35> next_timer_at = connection.get_timer()\n<36> (timer, timer_at) = self._timer.get(connection, (None, None))\n<37> if timer is not None and timer"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n # offset: 1\n timer.cancel()\n timer = None\n if timer is None and timer_at is not None:\n timer = self._loop.call_at(\n next_timer_at, partial(self._handle_timer, connection)\n )\n self._timer[connection] = (timer, next_timer_at)\n \n \n===========unchanged ref 0===========\n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n next_event() -> Optional[events.Event]\n \n at: aioquic.events\n ConnectionIdIssued(connection_id: bytes)\n \n ConnectionIdRetired(connection_id: bytes)\n \n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n at: asyncio.events.AbstractEventLoop\n call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle\n \n time() -> float\n \n at: asyncio.events.TimerHandle\n __slots__ = ['_scheduled', '_when']\n \n cancel() -> None\n \n at: asyncio.transports.DatagramTransport\n __slots__ = ()\n \n sendto(data: Any, addr: Optional[_Address]=...) -> None\n \n at: examples.http3-server\n H0Connection(quic: QuicConnection)\n \n handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None\n \n at: examples.http3-server.H0Connection\n handle_event(event: aioquic.events.Event)\n \n at: examples.http3-server.HttpServer\n _handle_timer(connection: QuicConnection) -> None\n \n \n===========unchanged ref 1===========\n at: examples.http3-server.HttpServer.__init__\n self._connections: Dict[bytes, QuicConnection] = {}\n \n self._http: Dict[QuicConnection, HttpConnection] = {}\n \n self._loop = asyncio.get_event_loop()\n \n self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n \n self._transport: Optional[asyncio.DatagramTransport] = None\n \n at: examples.http3-server.HttpServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + AlpnHandler = Callable[[str], None]\n SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]]\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n===========changed ref 1===========\n # module: aioquic.connection\n class QuicConnection:\n + # Private\n + \n + def _alpn_handler(self, alpn_protocol: str) -> None:\n + \"\"\"\n + Callback which is invoked by the TLS engine when ALPN negotiation completes.\n + \"\"\"\n + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol))\n + \n===========changed ref 2===========\n # module: aioquic.tls\n class Context:\n def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None:\n encrypted_extensions = pull_encrypted_extensions(input_buf)\n \n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n self.early_data_accepted = encrypted_extensions.early_data\n self.received_extensions = encrypted_extensions.other_extensions\n + if self.alpn_cb:\n + self.alpn_cb(self.alpn_negotiated)\n \n self._setup_traffic_protection(\n Direction.ENCRYPT, Epoch.HANDSHAKE, b\"c hs traffic\"\n )\n self.key_schedule.update_hash(input_buf.data)\n \n # if the server accepted our PSK we are done, other we want its certificate\n if self._session_resumed:\n self._set_state(State.CLIENT_EXPECT_FINISHED)\n else:\n self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)\n \n===========changed ref 3===========\n # module: tests.test_connection\n class QuicConnectionTest(TestCase):\n def test_connect_with_alpn(self):\n with client_and_server(\n client_options={\"alpn_protocols\": [\"hq-22\", \"h3-22\"]},\n server_options={\"alpn_protocols\": [\"hq-22\"]},\n ) as (client, server):\n # check handshake completed\n + event = client.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, \"hq-22\")\n event = client.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n for i in range(7):\n self.assertEqual(type(client.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(client.next_event())\n \n event = server.next_event()\n + self.assertEqual(type(event), events.ProtocolNegotiated)\n + self.assertEqual(event.alpn_protocol, \"hq-22\")\n + event = server.next_event()\n self.assertEqual(type(event), events.HandshakeCompleted)\n self.assertEqual(event.alpn_protocol, \"hq-22\")\n for i in range(7):\n self.assertEqual(type(server.next_event()), events.ConnectionIdIssued)\n self.assertIsNone(server.next_event())\n "}}},{"rowIdx":3034,"cells":{"path":{"kind":"string","value":"examples.server/SessionTicketStore.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"72fb62a0ad286f5876e7f725f754be59b6460a67"},"commit_message":{"kind":"string","value":"[examples] add type definitions for examples"},"ground_truth":{"kind":"string","value":" <0>: self.tickets: Dict[bytes, SessionTicket] = {}\n self.tickets = {}\n"},"main_code":{"kind":"string","value":" # module: examples.server\n class SessionTicketStore:\n + def __init__(self) -> None:\n - def __init__(self):\n <0> self.tickets = {}\n <1> \n "},"context":{"kind":"string","value":""}}},{"rowIdx":3035,"cells":{"path":{"kind":"string","value":"tests.test_h3/h3_transfer"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1d6ed5fe208f4987cf99d3ad14f74f73e9eb7d6e"},"commit_message":{"kind":"string","value":"[http3] remove H3Connection.handle_events"},"ground_truth":{"kind":"string","value":" <0>: quic_receiver = h3_receiver._quic\n transfer(quic_sender, quic_receiver)\n transfer(quic_sender, h3_receiver._quic)\n <1>: return h3_receiver.handle_events()\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n def h3_transfer(quic_sender, h3_receiver):\n <0> transfer(quic_sender, h3_receiver._quic)\n <1> return h3_receiver.handle_events()\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n at: tests.test_connection\n transfer(sender, receiver)\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def handle_events(self) -> List[Event]:\n - \"\"\"\n - Handle events from the QUIC connection and return HTTP events.\n - \"\"\"\n - http_events: List[Event] = []\n - \n - # process QUIC events\n - event = self._quic.next_event()\n - while event is not None:\n - http_events.extend(self.handle_event(event))\n - event = self._quic.next_event()\n - \n - return http_events\n - "}}},{"rowIdx":3036,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"1d6ed5fe208f4987cf99d3ad14f74f73e9eb7d6e"},"commit_message":{"kind":"string","value":"[http3] remove H3Connection.handle_events"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: examples.http3-client\n def run(url: str, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-22\"], is_client=True, server_name=server_name, **kwargs\n<18> ),\n<19> session_ticket_handler=save_session_ticket,\n<20> )\n<21> quic.connect(server_addr, now=time.time())\n<22> \n<23> # send request\n<24> http = H3Connection(quic)\n<25> stream_id = quic.get_next_available_stream_id()\n<26> http.send_headers(\n<27> stream_id=stream_id,\n<28> headers=[\n<29> (b\":method\", b\"GET\"),\n<30> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<31> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<32> (b\":path\", parsed.path.encode(\"utf8\")),\n<33> ],\n<34> )\n<35> http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<36> for data, addr in quic.datagrams_to_send(now=time.time()):\n<37> sock.sendto(data, addr)\n<38> \n<39> # handle events\n<40> stream_ended = False\n<41> while not stream_ended:\n<42> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n def run(url: str, **kwargs) -> None:\n # offset: 1\n quic.receive_datagram(data, addr, now=time.time())\n for event in http.handle_events():\n print(event)\n if isinstance(event, (DataReceived, ResponseReceived)):\n stream_ended = event.stream_ended\n \n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n save_session_ticket(ticket)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n def h3_transfer(quic_sender, h3_receiver):\n + quic_receiver = h3_receiver._quic\n + transfer(quic_sender, quic_receiver)\n - transfer(quic_sender, h3_receiver._quic)\n - return h3_receiver.handle_events()\n \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n - def handle_events(self) -> List[Event]:\n - \"\"\"\n - Handle events from the QUIC connection and return HTTP events.\n - \"\"\"\n - http_events: List[Event] = []\n - \n - # process QUIC events\n - event = self._quic.next_event()\n - while event is not None:\n - http_events.extend(self.handle_event(event))\n - event = self._quic.next_event()\n - \n - return http_events\n - "}}},{"rowIdx":3037,"cells":{"path":{"kind":"string","value":"aioquic.h0.connection/H0Connection.handle_event"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"e12e77d0cf5414b58a616305e4f7ad64211f5ec6"},"commit_message":{"kind":"string","value":"[http0] add support for client role"},"ground_truth":{"kind":"string","value":" <0>: http_events: List[Event] = []\n http_events = []\n <6>: method, path = event.data.rstrip().split(b\" \", 1)\n <7>: cls = ResponseReceived if self._is_client else RequestReceived\n <8>: if self._is_client:\n http_events.append(\n http_events.append(\n <9>: ResponseReceived(\n headers=[], stream_ended=False, stream_id=event.stream_id\n )\n cls(\n<10>: headers=[(b\":method\", method), (b\":path\", path)],\n<11>: stream_ended=event.end_stream,\n<12>: stream_id=event.stream_id,\n<14>: http_events.append(\n DataReceived(\n data=event.data,\n stream_ended=event.end_stream,\n stream_id=event.stream_id,\n )\n )\n )\n<15>: \n else:\n method, path = event.data.rstrip().split(b\" \", 1)\n http_events.append(\n RequestReceived(\n headers=[(b\":method\", method), (b\":path\", path)],\n stream_ended=event.end_stream,\n stream_id=event.stream_id,\n )\n )\n"},"main_code":{"kind":"string","value":" # module: aioquic.h0.connection\n class H0Connection:\n + def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event):\n <0> http_events = []\n <1> \n <2> if (\n <3> isinstance(event, aioquic.events.StreamDataReceived)\n <4> and (event.stream_id % 4) == 0\n <5> ):\n <6> method, path = event.data.rstrip().split(b\" \", 1)\n <7> cls = ResponseReceived if self._is_client else RequestReceived\n <8> http_events.append(\n <9> cls(\n<10> headers=[(b\":method\", method), (b\":path\", path)],\n<11> stream_ended=event.end_stream,\n<12> stream_id=event.stream_id,\n<13> )\n<14> )\n<15> \n<16> return http_events\n<17> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n Event()\n \n StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)\n \n at: aioquic.h0.connection.H0Connection.__init__\n self._is_client = quic.configuration.is_client\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n "}}},{"rowIdx":3038,"cells":{"path":{"kind":"string","value":"aioquic.h0.connection/H0Connection.send_headers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"e12e77d0cf5414b58a616305e4f7ad64211f5ec6"},"commit_message":{"kind":"string","value":"[http0] add support for client role"},"ground_truth":{"kind":"string","value":" <0>: if self._is_client:\n headers_dict = dict(headers)\n self._quic.send_stream_data(\n stream_id,\n headers_dict[b\":method\"] + b\" \" + headers_dict[b\":path\"] + b\"\\r\\n\",\n False,\n )\n # HTTP/0.9 has no concept of headers.\n <1>: pass\n"},"main_code":{"kind":"string","value":" # module: aioquic.h0.connection\n class H0Connection:\n def send_headers(self, stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None:\n <0> # HTTP/0.9 has no concept of headers.\n <1> pass\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h0.connection.H0Connection.handle_event\n http_events: List[Event] = []\n \n at: aioquic.h3.events\n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n \n===========changed ref 0===========\n # module: aioquic.h0.connection\n class H0Connection:\n + def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event):\n + http_events: List[Event] = []\n - http_events = []\n \n if (\n isinstance(event, aioquic.events.StreamDataReceived)\n and (event.stream_id % 4) == 0\n ):\n - method, path = event.data.rstrip().split(b\" \", 1)\n - cls = ResponseReceived if self._is_client else RequestReceived\n + if self._is_client:\n + http_events.append(\n - http_events.append(\n + ResponseReceived(\n + headers=[], stream_ended=False, stream_id=event.stream_id\n + )\n - cls(\n - headers=[(b\":method\", method), (b\":path\", path)],\n - stream_ended=event.end_stream,\n - stream_id=event.stream_id,\n )\n + http_events.append(\n + DataReceived(\n + data=event.data,\n + stream_ended=event.end_stream,\n + stream_id=event.stream_id,\n + )\n + )\n - )\n + \n + else:\n + method, path = event.data.rstrip().split(b\" \", 1)\n + http_events.append(\n + RequestReceived(\n + headers=[(b\":method\", method), (b\":path\", path)],\n + stream_ended=event.end_stream,\n + stream_id=event.stream_id,\n + )\n + )\n \n return http_events\n "}}},{"rowIdx":3039,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"17fd217f8ab3c56131db1e578537f441b7d96dfe"},"commit_message":{"kind":"string","value":"[examples] make HTTP/3 client also capable of making HTTP/0.9 requests"},"ground_truth":{"kind":"string","value":"<17>: alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n is_client=True,\n server_name=server_name,\n **kwargs\n alpn_protocols=[\"h3-22\"], is_client=True, server_name=server_name, **kwargs\n<24>: http: HttpConnection\n if legacy_http:\n http = H0Connection(quic)\n else:\n http = H3Connection(quic)\n http = H3Connection(quic)\n"},"main_code":{"kind":"string","value":" # module: examples.http3-client\n + def run(url: str, legacy_http: bool, **kwargs) -> None:\n - def run(url: str, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"h3-22\"], is_client=True, server_name=server_name, **kwargs\n<18> ),\n<19> session_ticket_handler=save_session_ticket,\n<20> )\n<21> quic.connect(server_addr, now=time.time())\n<22> \n<23> # send request\n<24> http = H3Connection(quic)\n<25> stream_id = quic.get_next_available_stream_id()\n<26> http.send_headers(\n<27> stream_id=stream_id,\n<28> headers=[\n<29> (b\":method\", b\"GET\"),\n<30> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<31> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<32> (b\":path\", parsed.path.encode(\"utf8\")),\n<33> ],\n<34> )\n<35> http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<36> for data, addr in quic.datagrams_to_send(now=time.time()):\n<37> sock.sendto(data, addr)\n<38> \n<39> #"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n + def run(url: str, legacy_http: bool, **kwargs) -> None:\n - def run(url: str, **kwargs) -> None:\n # offset: 1\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n print(http_event)\n if isinstance(http_event, (DataReceived, ResponseReceived)):\n stream_ended = http_event.stream_ended\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: _pickle\n dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)\n \n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n save_session_ticket(ticket)\n \n args = parser.parse_args()\n \n at: pickle\n dump, dumps, load, loads = _dump, _dumps, _load, _loads\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n \n===========unchanged ref 2===========\n at: time\n time() -> float\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: examples.http3-client\n logger = logging.getLogger(\"client\")\n \n + HttpConnection = Union[H0Connection, H3Connection]\n + "}}},{"rowIdx":3040,"cells":{"path":{"kind":"string","value":"aioquic.h0.connection/H0Connection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8acade9e4b7fa9e45ebb90a820f4fc09e0edcb3f"},"commit_message":{"kind":"string","value":"[http0] add some tests"},"ground_truth":{"kind":"string","value":" <0>: self._headers_received: Dict[int, bool] = {}\n"},"main_code":{"kind":"string","value":" # module: aioquic.h0.connection\n class H0Connection:\n def __init__(self, quic: QuicConnection):\n <0> self._is_client = quic.configuration.is_client\n <1> self._quic = quic\n <2> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: typing\n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":3041,"cells":{"path":{"kind":"string","value":"aioquic.h0.connection/H0Connection.handle_event"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"8acade9e4b7fa9e45ebb90a820f4fc09e0edcb3f"},"commit_message":{"kind":"string","value":"[http0] add some tests"},"ground_truth":{"kind":"string","value":" <6>: data = event.data\n if not self._headers_received.get(event.stream_id, False):\n if self._is_client:\n if self._is_client:\n <7>: http_events.append(\n http_events.append(\n <8>: ResponseReceived(\n ResponseReceived(\n <9>: headers=[], stream_ended=False, stream_id=event.stream_id\n headers=[], stream_ended=False, stream_id=event.stream_id\n<10>: )\n<11>: else:\n method, path = data.rstrip().split(b\" \", 1)\n http_events.append(\n RequestReceived(\n headers=[(b\":method\", method), (b\":path\", path)],\n stream_ended=False,\n stream_id=event.stream_id,\n )\n )\n data = b\"\"\n self._headers_received[event.stream_id] = True\n \n http_events.append(\n DataReceived(\n data=data, stream_ended=event.end_stream, stream_id=event.stream_id\n<12>: http_events.append(\n<13>: DataReceived(\n"},"main_code":{"kind":"string","value":" # module: aioquic.h0.connection\n class H0Connection:\n def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if (\n <3> isinstance(event, aioquic.events.StreamDataReceived)\n <4> and (event.stream_id % 4) == 0\n <5> ):\n <6> if self._is_client:\n <7> http_events.append(\n <8> ResponseReceived(\n <9> headers=[], stream_ended=False, stream_id=event.stream_id\n<10> )\n<11> )\n<12> http_events.append(\n<13> DataReceived(\n<14> data=event.data,\n<15> stream_ended=event.end_stream,\n<16> stream_id=event.stream_id,\n<17> )\n<18> )\n<19> \n<20> else:\n<21> method, path = event.data.rstrip().split(b\" \", 1)\n<22> http_events.append(\n<23> RequestReceived(\n<24> headers=[(b\":method\", method), (b\":path\", path)],\n<25> stream_ended=event.end_stream,\n<26> stream_id=event.stream_id,\n<27> )\n<28> )\n<29> \n<30> return http_events\n<31> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n Event()\n \n StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)\n \n at: aioquic.h0.connection.H0Connection.__init__\n self._headers_received: Dict[int, bool] = {}\n \n self._is_client = quic.configuration.is_client\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n \n===========changed ref 0===========\n # module: aioquic.h0.connection\n class H0Connection:\n def __init__(self, quic: QuicConnection):\n + self._headers_received: Dict[int, bool] = {}\n self._is_client = quic.configuration.is_client\n self._quic = quic\n "}}},{"rowIdx":3042,"cells":{"path":{"kind":"string","value":"aioquic.connection/QuicConnection._replenish_connection_ids"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"afd57a7cde06c503216d3a49f81311bcac784f11"},"commit_message":{"kind":"string","value":"[connection] cap the number of connection IDs we offer"},"ground_truth":{"kind":"string","value":" <3>: while len(self._host_cids) < min(8, self._remote_active_connection_id_limit):\n while len(self._host_cids) < self._remote_active_connection_id_limit:\n"},"main_code":{"kind":"string","value":" # module: aioquic.connection\n class QuicConnection:\n def _replenish_connection_ids(self) -> None:\n <0> \"\"\"\n <1> Generate new connection IDs.\n <2> \"\"\"\n <3> while len(self._host_cids) < self._remote_active_connection_id_limit:\n <4> self._host_cids.append(\n <5> QuicConnectionId(\n <6> cid=os.urandom(8),\n <7> sequence_number=self._host_cid_seq,\n <8> stateless_reset_token=os.urandom(16),\n <9> )\n<10> )\n<11> self._host_cid_seq += 1\n<12> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection\n QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b\"\", was_sent: bool=False)\n \n at: aioquic.connection.QuicConnection.__init__\n self._host_cids = [\n QuicConnectionId(\n cid=os.urandom(8),\n sequence_number=0,\n stateless_reset_token=os.urandom(16),\n was_sent=True,\n )\n ]\n \n self._host_cid_seq = 1\n \n self._remote_active_connection_id_limit = 0\n \n at: aioquic.connection.QuicConnection._parse_transport_parameters\n self._remote_active_connection_id_limit = (\n quic_transport_parameters.active_connection_id_limit\n )\n \n at: aioquic.connection.QuicConnectionId\n cid: bytes\n \n sequence_number: int\n \n stateless_reset_token: bytes = b\"\"\n \n was_sent: bool = False\n \n at: os\n urandom(size: int, /) -> bytes\n \n "}}},{"rowIdx":3043,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"278deb59892219d7495e4b6e3adbcadf8c291702"},"commit_message":{"kind":"string","value":"[http3] handle data on encoder / decoder streams"},"ground_truth":{"kind":"string","value":"<32>: if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n # fetch next frame\n # fetch next frame\n<33>: try:\n try:\n<34>: frame_type = buf.pull_uint_var()\n frame_type = buf.pull_uint_var()\n<35>: frame_length = buf.pull_uint_var()\n frame_length = buf.pull_uint_var()\n<36>: frame_data = buf.pull_bytes(frame_length)\n frame_data = buf.pull_bytes(frame_length)\n<37>: except BufferReadError:\n except BufferReadError:\n<38>: break\n break\n<39>: consumed = buf.tell()\n consumed = buf.tell()\n<41>: if (stream_id % 4) == 0:\n if (stream_id % 4) == 0:\n<42>: # client-initiated bidirectional streams carry requests and responses\n #\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> consumed = 0\n <7> \n <8> buf = Buffer(data=self._stream_buffers[stream_id])\n <9> while not buf.eof():\n<10> # fetch stream type for unidirectional streams\n<11> if (\n<12> stream_is_unidirectional(stream_id)\n<13> and stream_id not in self._stream_types\n<14> ):\n<15> try:\n<16> stream_type = buf.pull_uint_var()\n<17> except BufferReadError:\n<18> break\n<19> consumed = buf.tell()\n<20> \n<21> if stream_type == StreamType.CONTROL:\n<22> assert self._peer_control_stream_id is None\n<23> self._peer_control_stream_id = stream_id\n<24> elif stream_type == StreamType.QPACK_DECODER:\n<25> assert self._peer_decoder_stream_id is None\n<26> self._peer_decoder_stream_id = stream_id\n<27> elif stream_type == StreamType.QPACK_ENCODER:\n<28> assert self._peer_encoder_stream_id is None\n<29> self._peer_encoder_stream_id = stream_id\n<30> self._stream_types[stream_id] = stream_type\n<31> \n<32> # fetch next frame\n<33> try:\n<34> frame_type = buf.pull_uint_var()\n<35> frame_length = buf.pull_uint_var()\n<36> frame_data = buf.pull_bytes(frame_length)\n<37> except BufferReadError:\n<38> break\n<39> consumed = buf.tell()\n<40> \n<41> if (stream_id % 4) == 0:\n<42> #"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n control, headers = self._decoder.feed_header(stream_id, frame_data)\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(Setting.QPACK_BLOCKED_STREAMS, 0),\n )\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n self._peer_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n \n===========unchanged ref 1===========\n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n "}}},{"rowIdx":3044,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.send_headers"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"96099bc125790476e7fb26685a0c485fc3075163"},"commit_message":{"kind":"string","value":"[http3] send encoder and decoder stream data"},"ground_truth":{"kind":"string","value":" <7>: encoder, header = self._encoder.encode(stream_id, 0, headers)\n control, header = self._encoder.encode(stream_id, 0, headers)\n <8>: self._quic.send_stream_data(\n <9>: stream_id, encode_frame(FrameType.HEADERS, header), False\n<10>: )\n<11>: self._quic.send_stream_data(self._local_encoder_stream_id, encoder)\n self._quic.send_stream_data(stream_id, encode_frame(FrameType.HEADERS, header))\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def send_headers(self, stream_id: int, headers: Headers) -> None:\n <0> \"\"\"\n <1> Send headers on the given stream.\n <2> \n <3> To retrieve datagram which need to be sent over the network call the QUIC\n <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n <5> method.\n <6> \"\"\"\n <7> control, header = self._encoder.encode(stream_id, 0, headers)\n <8> self._quic.send_stream_data(\n <9> stream_id, encode_frame(FrameType.HEADERS, header), False\n<10> )\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n encode_frame(frame_type: int, frame_data: bytes) -> bytes\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n self._encoder = Encoder()\n \n self._local_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n at: aioquic.h3.events\n Headers = List[Tuple[bytes, bytes]]\n \n "}}},{"rowIdx":3045,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"96099bc125790476e7fb26685a0c485fc3075163"},"commit_message":{"kind":"string","value":"[http3] send encoder and decoder stream data"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> consumed = 0\n <7> \n <8> buf = Buffer(data=self._stream_buffers[stream_id])\n <9> while not buf.eof():\n<10> # fetch stream type for unidirectional streams\n<11> if (\n<12> stream_is_unidirectional(stream_id)\n<13> and stream_id not in self._stream_types\n<14> ):\n<15> try:\n<16> stream_type = buf.pull_uint_var()\n<17> except BufferReadError:\n<18> break\n<19> consumed = buf.tell()\n<20> \n<21> if stream_type == StreamType.CONTROL:\n<22> assert self._peer_control_stream_id is None\n<23> self._peer_control_stream_id = stream_id\n<24> elif stream_type == StreamType.QPACK_DECODER:\n<25> assert self._peer_decoder_stream_id is None\n<26> self._peer_decoder_stream_id = stream_id\n<27> elif stream_type == StreamType.QPACK_ENCODER:\n<28> assert self._peer_encoder_stream_id is None\n<29> self._peer_encoder_stream_id = stream_id\n<30> self._stream_types[stream_id] = stream_type\n<31> \n<32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n<33> # fetch next frame\n<34> try:\n<35> frame_type = buf.pull_uint_var()\n<36> frame_length = buf.pull_uint_var()\n<37> frame_data = buf.pull_bytes(frame_length)\n<38> except BufferReadError:\n<39> break\n<40> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n control, headers = self._decoder.feed_header(\n stream_id, frame_data\n )\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(\n Setting.QPACK_BLOCKED_STREAMS, 0\n ),\n )\n else:\n # fetch unframed data\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n \n if stream_id == self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id == self._peer_encoder_stream_id:\n self._decoder.feed_encoder(data)\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return\n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 2\n buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._quic = quic\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n self._peer_encoder_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def send_headers(self, stream_id: int, headers: Headers) -> None:\n \"\"\"\n Send headers on the given stream.\n \n To retrieve datagram which need to be sent over the network call the QUIC\n connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send`\n method.\n \"\"\"\n + encoder, header = self._encoder.encode(stream_id, 0, headers)\n - control, header = self._encoder.encode(stream_id, 0, headers)\n - self._quic.send_stream_data(\n - stream_id, encode_frame(FrameType.HEADERS, header), False\n - )\n + self._quic.send_stream_data(self._local_encoder_stream_id, encoder)\n + self._quic.send_stream_data(stream_id, encode_frame(FrameType.HEADERS, header))\n "}}},{"rowIdx":3046,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_connect"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"c1db156be227ef336f3233f50327ec0fa96faef1"},"commit_message":{"kind":"string","value":"[http3] test using dynamic tables"},"ground_truth":{"kind":"string","value":" <7>: # make first request\n # send request\n <8>: stream_id = quic_client.get_next_available_stream_id()\n <9>: h3_client.send_headers(\n<10>: stream_id=stream_id,\n<11>: headers=[\n<12>: (b\":method\", b\"GET\"),\n<13>: (b\":scheme\", b\"https\"),\n<14>: (b\":authority\", b\"localhost\"),\n<15>: (b\":path\", b\"/\"),\n<16>: ],\n<17>: )\n<18>: h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<19>: self._make_request(h3_client, h3_server)\n<20>: # make second request\n # receive request\n<21>: events = h3_transfer(quic_client, h3_server)\n<22>: self.assertEqual(len(events), 2)\n<23>: self._make_request(h3_client, h3_server)\n<24>: self.assertTrue(isinstance(events[0], RequestReceived))\n<25>: self.assertEqual(\n<26>: events[0].headers,\n<27>: [\n<28>: (b\":method\", b\"GET\"),\n<29>: (b\":scheme\", b\"https\"),\n<30>: (b\":authority\", b\"localhost\"),\n<31>: (b\":path\", b\"/\"),\n<32>: ],\n<33>: )\n<34>: self.assertEqual(events[0].stream_id, stream_id)\n<35>: self.assertEqual(events[0].stream_ended, False)\n<36>: # make third request -> dynamic table\n self._make_request(h3_client, h3_server)\n<37>: self.assertTrue(isinstance(events[1], DataReceived))\n<38>: self.assertEqual(events[1].data, b\"\")\n<39>: self.assertEqual(events[1].stream_id,\n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-22\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-22\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_client = H3Connection(quic_client)\n <5> h3_server = H3Connection(quic_server)\n <6> \n <7> # send request\n <8> stream_id = quic_client.get_next_available_stream_id()\n <9> h3_client.send_headers(\n<10> stream_id=stream_id,\n<11> headers=[\n<12> (b\":method\", b\"GET\"),\n<13> (b\":scheme\", b\"https\"),\n<14> (b\":authority\", b\"localhost\"),\n<15> (b\":path\", b\"/\"),\n<16> ],\n<17> )\n<18> h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<19> \n<20> # receive request\n<21> events = h3_transfer(quic_client, h3_server)\n<22> self.assertEqual(len(events), 2)\n<23> \n<24> self.assertTrue(isinstance(events[0], RequestReceived))\n<25> self.assertEqual(\n<26> events[0].headers,\n<27> [\n<28> (b\":method\", b\"GET\"),\n<29> (b\":scheme\", b\"https\"),\n<30> (b\":authority\", b\"localhost\"),\n<31> (b\":path\", b\"/\"),\n<32> ],\n<33> )\n<34> self.assertEqual(events[0].stream_id, stream_id)\n<35> self.assertEqual(events[0].stream_ended, False)\n<36> \n<37> self.assertTrue(isinstance(events[1], DataReceived))\n<38> self.assertEqual(events[1].data, b\"\")\n<39> self.assertEqual(events[1].stream_id,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_connect(self):\n # offset: 1\n self.assertEqual(events[1].stream_ended, True)\n \n # send response\n h3_server.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":status\", b\"200\"),\n (b\"content-type\", b\"text/html; charset=utf-8\"),\n ],\n )\n h3_server.send_data(\n stream_id=stream_id,\n data=b\"hello\",\n end_stream=True,\n )\n \n # receive response\n events = h3_transfer(quic_server, h3_client)\n self.assertEqual(len(events), 2)\n \n self.assertTrue(isinstance(events[0], ResponseReceived))\n self.assertEqual(\n events[0].headers,\n [(b\":status\", b\"200\"), (b\"content-type\", b\"text/html; charset=utf-8\")],\n )\n self.assertEqual(events[0].stream_id, stream_id)\n self.assertEqual(events[0].stream_ended, False)\n \n self.assertTrue(isinstance(events[1], DataReceived))\n self.assertEqual(events[1].data, b\"hello\")\n self.assertEqual(events[1].stream_id, stream_id)\n self.assertEqual(events[1].stream_ended, True)\n \n \n===========unchanged ref 0===========\n at: aioquic.connection.QuicConnection\n get_next_available_stream_id(is_unidirectional=False) -> int\n \n at: aioquic.h3.connection.H3Connection\n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._quic = quic\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n + def _make_request(self, h3_client, h3_server):\n + quic_client = h3_client._quic\n + quic_server = h3_server._quic\n + \n + # send request\n + stream_id = quic_client.get_next_available_stream_id()\n + h3_client.send_headers(\n + stream_id=stream_id,\n + headers=[\n + (b\":method\", b\"GET\"),\n + (b\":scheme\", b\"https\"),\n + (b\":authority\", b\"localhost\"),\n + (b\":path\", b\"/\"),\n + (b\"x-foo\", b\"client\"),\n + ],\n + )\n + h3_client.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n + \n + # receive request\n + events = h3_transfer(quic_client, h3_server)\n + self.assertEqual(len(events), 2)\n + \n + self.assertTrue(isinstance(events[0], RequestReceived))\n + self.assertEqual(\n + events[0].headers,\n + [\n + (b\":method\", b\"GET\"),\n + (b\":scheme\", b\"https\"),\n + (b\":authority\", b\"localhost\"),\n + (b\":path\", b\"/\"),\n + (b\"x-foo\", b\"client\"),\n + ],\n + )\n + self.assertEqual(events[0].stream_id, stream_id)\n + self.assertEqual(events[0].stream_ended, False)\n + \n + self.assertTrue(isinstance(events[1], DataReceived))\n + self.assertEqual(events[1].data, b\"\")\n + self.assertEqual(events[1].stream_id, stream_id)\n + self.assertEqual(events[1].stream_ended, True)\n + \n + #\n===========changed ref 1===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n + def _make_request(self, h3_client, h3_server):\n # offset: 1\n id, stream_id)\n + self.assertEqual(events[1].stream_ended, True)\n + \n + # send response\n + h3_server.send_headers(\n + stream_id=stream_id,\n + headers=[\n + (b\":status\", b\"200\"),\n + (b\"content-type\", b\"text/html; charset=utf-8\"),\n + (b\"x-foo\", b\"server\"),\n + ],\n + )\n + h3_server.send_data(\n + stream_id=stream_id,\n + data=b\"hello\",\n + end_stream=True,\n + )\n + \n + # receive response\n + events = h3_transfer(quic_server, h3_client)\n + self.assertEqual(len(events), 2)\n + \n + self.assertTrue(isinstance(events[0], ResponseReceived))\n + self.assertEqual(\n + events[0].headers,\n + [\n + (b\":status\", b\"200\"),\n + (b\"content-type\", b\"text/html; charset=utf-8\"),\n + (b\"x-foo\", b\"server\"),\n + ],\n + )\n + self.assertEqual(events[0].stream_id, stream_id)\n + self.assertEqual(events[0].stream_ended, False)\n + \n + self.assertTrue(isinstance(events[1], DataReceived))\n + self.assertEqual(events[1].data, b\"hello\")\n + self.assertEqual(events[1].stream_id, stream_id)\n + self.assertEqual(events"}}},{"rowIdx":3047,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"23e7979dafbd1b6383d909d9df1e704e6b4e8530"},"commit_message":{"kind":"string","value":"[examples] add server and user-agent headers"},"ground_truth":{"kind":"string","value":"<40>: (b\"user-agent\", b\"aioquic\"),\n"},"main_code":{"kind":"string","value":" # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n<18> is_client=True,\n<19> server_name=server_name,\n<20> **kwargs\n<21> ),\n<22> session_ticket_handler=save_session_ticket,\n<23> )\n<24> quic.connect(server_addr, now=time.time())\n<25> \n<26> # send request\n<27> http: HttpConnection\n<28> if legacy_http:\n<29> http = H0Connection(quic)\n<30> else:\n<31> http = H3Connection(quic)\n<32> stream_id = quic.get_next_available_stream_id()\n<33> http.send_headers(\n<34> stream_id=stream_id,\n<35> headers=[\n<36> (b\":method\", b\"GET\"),\n<37> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<38> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<39> (b\":path\", parsed.path.encode(\"utf8\")),\n<40> ],\n<41> )\n<42> http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n<43> for data, addr in"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n print(http_event)\n if isinstance(http_event, (DataReceived, ResponseReceived)):\n stream_ended = http_event.stream_ended\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str=\"\") -> None\n \n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n save_session_ticket(ticket)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: time\n time() -> float\n \n \n===========unchanged ref 2===========\n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n "}}},{"rowIdx":3048,"cells":{"path":{"kind":"string","value":"examples.http3-server/send_response"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"23e7979dafbd1b6383d909d9df1e704e6b4e8530"},"commit_message":{"kind":"string","value":"[examples] add server and user-agent headers"},"ground_truth":{"kind":"string","value":" <8>: (b\"server\", b\"aioquic\"),\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n def send_response(\n connection: HttpConnection,\n stream_id: int,\n data: bytes = b\"\",\n content_type: str = \"text/html\",\n status_code: int = 200,\n ) -> None:\n <0> \"\"\"\n <1> Send an HTTP response on a connection and stream.\n <2> \"\"\"\n <3> connection.send_headers(\n <4> stream_id=stream_id,\n <5> headers=[\n <6> (b\":status\", str(status_code).encode(\"ascii\")),\n <7> (b\"content-type\", content_type.encode(\"ascii\")),\n <8> ],\n <9> )\n<10> connection.send_data(stream_id=stream_id, data=data, end_stream=True)\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h0.connection.H0Connection\n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection.H3Connection\n send_headers(stream_id: int, headers: Headers) -> None\n \n at: examples.http3-server\n HttpConnection = Union[H0Connection, H3Connection]\n \n \n===========changed ref 0===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # parse URL\n parsed = urlparse(url)\n assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n if \":\" in parsed.netloc:\n server_name, port_str = parsed.netloc.split(\":\")\n port = int(port_str)\n else:\n server_name = parsed.netloc\n port = 443\n \n # prepare socket\n server_addr = (socket.gethostbyname(server_name), port)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n \n # prepare QUIC connection\n quic = QuicConnection(\n configuration=QuicConfiguration(\n alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n is_client=True,\n server_name=server_name,\n **kwargs\n ),\n session_ticket_handler=save_session_ticket,\n )\n quic.connect(server_addr, now=time.time())\n \n # send request\n http: HttpConnection\n if legacy_http:\n http = H0Connection(quic)\n else:\n http = H3Connection(quic)\n stream_id = quic.get_next_available_stream_id()\n http.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n (b\":authority\", parsed.netloc.encode(\"utf8\")),\n (b\":path\", parsed.path.encode(\"utf8\")),\n + (b\"user-agent\", b\"aioquic\"),\n ],\n )\n http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data\n===========changed ref 1===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n print(http_event)\n if isinstance(http_event, (DataReceived, ResponseReceived)):\n stream_ended = http_event.stream_ended\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n "}}},{"rowIdx":3049,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<35>: hello.psk_key_exchange_modes = pull_list(\n hello.key_exchange_modes = pull_list(\n<36>: buf, 1, partial(pull_psk_key_exchange_mode, buf)\n buf, 1, partial(pull_key_exchange_mode, buf)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> client_random = buf.pull_bytes(32)\n <4> \n <5> hello = ClientHello(\n <6> random=client_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n <9> compression_methods=pull_list(\n<10> buf, 1, partial(pull_compression_method, buf)\n<11> ),\n<12> )\n<13> \n<14> # extensions\n<15> after_psk = False\n<16> \n<17> def pull_extension() -> None:\n<18> # pre_shared_key MUST be last\n<19> nonlocal after_psk\n<20> assert not after_psk\n<21> \n<22> extension_type = buf.pull_uint16()\n<23> extension_length = buf.pull_uint16()\n<24> if extension_type == ExtensionType.KEY_SHARE:\n<25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n<26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n<28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n<29> hello.signature_algorithms = pull_list(\n<30> buf, 2, partial(pull_signature_algorithm, buf)\n<31> )\n<32> elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n<33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n<34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n<35> hello.key_exchange_modes = pull_list(\n<36> buf, 1, partial(pull_key_exchange_mode, buf)\n<37> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n pull_uint8() -> int\n \n pull_uint16() -> int\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n pull_cipher_suite(buf: Buffer) -> CipherSuite\n \n pull_compression_method(buf: Buffer) -> CompressionMethod\n \n pull_group(buf: Buffer) -> Group\n \n pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode\n \n pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm\n \n pull_block(buf: Buffer, capacity: int) -> Generator\n \n pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n pull_key_share(buf: Buffer) -> KeyShareEntry\n \n pull_alpn_protocol(buf: Buffer) -> str\n \n pull_psk_identity(buf: Buffer) -> PskIdentity\n \n pull_psk_binder(buf: Buffer) -> bytes\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n \n===========unchanged ref 1===========\n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[CipherSuite]\n \n compression_methods: List[CompressionMethod]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n \n supported_groups: Optional[List[Group]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: aioquic.tls.OfferedPsks\n identities: List[PskIdentity]\n \n binders: List[bytes]\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + \n===========changed ref 1===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 2===========\n # module: aioquic.tls\n - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:\n - return KeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 3===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - "}}},{"rowIdx":3050,"cells":{"path":{"kind":"string","value":"aioquic.tls/push_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<22>: if hello.psk_key_exchange_modes is not None:\n with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n<23>: push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n <0> buf.push_uint8(HandshakeType.CLIENT_HELLO)\n <1> with push_block(buf, 3):\n <2> buf.push_uint16(TLS_VERSION_1_2)\n <3> buf.push_bytes(hello.random)\n <4> push_opaque(buf, 1, hello.session_id)\n <5> push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n <6> push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n <7> \n <8> # extensions\n <9> with push_block(buf, 2):\n<10> with push_extension(buf, ExtensionType.KEY_SHARE):\n<11> push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n<12> \n<13> with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n<14> push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n<15> \n<16> with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n<17> push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n<18> \n<19> with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n<20> push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n<21> \n<22> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n<23> push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n<24> \n<25> if hello.server_name is not None:\n<26> with push_extension(buf, ExtensionType.SERVER_NAME):\n<27> with push_block(buf, 2):\n<28> buf.push_uint8(0)\n<29> push_opaque(buf, 2, hello.server_name.encode(\"ascii\"))\n<30> \n<31> if hello.alpn_protocols is not None:\n<32> with push_extension(buf, Extension"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n # offset: 1\n push_list(\n buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols\n )\n \n for extension_type, extension_value in hello.other_extensions:\n with push_extension(buf, extension_type):\n buf.push_bytes(extension_value)\n \n if hello.early_data:\n with push_extension(buf, ExtensionType.EARLY_DATA):\n pass\n \n # pre_shared_key MUST be last\n if hello.pre_shared_key is not None:\n with push_extension(buf, ExtensionType.PRE_SHARED_KEY):\n push_list(\n buf,\n 2,\n partial(push_psk_identity, buf),\n hello.pre_shared_key.identities,\n )\n push_list(\n buf,\n 2,\n partial(push_psk_binder, buf),\n hello.pre_shared_key.binders,\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n push_bytes(value: bytes) -> None\n \n push_uint8(value: int) -> None\n \n push_uint16(value: int) -> None\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n HandshakeType(x: Union[str, bytes, bytearray], base: int)\n \n push_block(buf: Buffer, capacity: int) -> Generator\n \n push_list(buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]) -> None\n \n push_opaque(buf: Buffer, capacity: int, value: bytes) -> None\n \n push_extension(buf: Buffer, extension_type: int) -> Generator\n \n push_key_share(buf: Buffer, value: KeyShareEntry) -> None\n \n push_alpn_protocol(buf: Buffer, protocol: str) -> None\n \n push_psk_identity(buf: Buffer, entry: PskIdentity) -> None\n \n push_psk_binder(buf: Buffer, binder: bytes) -> None\n \n \n===========unchanged ref 1===========\n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[CipherSuite]\n \n compression_methods: List[CompressionMethod]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n \n supported_groups: Optional[List[Group]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: aioquic.tls.OfferedPsks\n identities: List[PskIdentity]\n \n binders: List[bytes]\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + \n===========changed ref 2===========\n # module: aioquic.tls\n - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:\n - return KeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 3===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - "}}},{"rowIdx":3051,"cells":{"path":{"kind":"string","value":"aioquic.tls/negotiate"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":" <5>: if exc is not None:\n raise exc\n raise exc\n <6>: return None\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n + def negotiate(\n + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None\n - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T:\n + ) -> T:\n <0> if offered is not None:\n <1> for c in supported:\n <2> if c in offered:\n <3> return c\n <4> \n <5> raise exc\n <6> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n T = TypeVar(\"T\")\n \n Alert(*args: object)\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + \n===========changed ref 1===========\n # module: aioquic.tls\n - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:\n - return KeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 2===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 3===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 4===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 5===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n buf.push_uint8(HandshakeType.CLIENT_HELLO)\n with push_block(buf, 3):\n buf.push_uint16(TLS_VERSION_1_2)\n buf.push_bytes(hello.random)\n push_opaque(buf, 1, hello.session_id)\n push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n \n # extensions\n with push_block(buf, 2):\n with push_extension(buf, ExtensionType.KEY_SHARE):\n push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n \n with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n \n with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n \n with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n \n + if hello.psk_key_exchange_modes is not None:\n + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n \n if hello.server_name is not None:\n with push_extension(buf, ExtensionType.SERVER_NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque\n===========changed ref 6===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n # offset: 1\n NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque(buf, 2, hello.server_name.encode(\"ascii\"))\n \n if hello.alpn_protocols is not None:\n with push_extension(buf, ExtensionType.ALPN):\n push_list(\n buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols\n )\n \n for extension_type, extension_value in hello.other_extensions:\n with push_extension(buf, extension_type):\n buf.push_bytes(extension_value)\n \n if hello.early_data:\n with push_extension(buf, ExtensionType.EARLY_DATA):\n pass\n \n # pre_shared_key MUST be last\n if hello.pre_shared_key is not None:\n with push_extension(buf, ExtensionType.PRE_SHARED_KEY):\n push_list(\n buf,\n 2,\n partial(push_psk_identity, buf),\n hello.pre_shared_key.identities,\n )\n push_list(\n buf,\n 2,\n partial(push_psk_binder, buf),\n hello.pre_shared_key.binders,\n )\n \n===========changed ref 7===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n compression_methods=pull_list(\n buf, 1, partial(pull_compression_method, buf)\n ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n hello.signature_algorithms = pull_list(\n buf, 2, partial(pull_signature_algorithm, buf)\n )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n + hello.psk_key_exchange_modes = pull_list(\n - hello.key_exchange_modes = pull_list(\n + buf, 1, partial(pull_psk_key_exchange_mode, buf)\n - buf, 1, partial(pull_key_exchange_mode,"}}},{"rowIdx":3052,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<28>: self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE]\n self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE]\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n <0> self.alpn_negotiated: Optional[str] = None\n <1> self.alpn_protocols: Optional[List[str]] = None\n <2> self.certificate: Optional[x509.Certificate] = None\n <3> self.certificate_private_key: Optional[\n <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey]\n <5> ] = None\n <6> self.early_data_accepted = False\n <7> self.handshake_extensions: List[Extension] = []\n <8> self.key_schedule: Optional[KeySchedule] = None\n <9> self.received_extensions: Optional[List[Extension]] = None\n<10> self.session_ticket: Optional[SessionTicket] = None\n<11> self.server_name: Optional[str] = None\n<12> \n<13> # callbacks\n<14> self.alpn_cb: Optional[AlpnHandler] = None\n<15> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None\n<16> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n<17> self.update_traffic_key_cb: Callable[\n<18> [Direction, Epoch, CipherSuite, bytes], None\n<19> ] = lambda d, e, c, s: None\n<20> \n<21> # supported parameters\n<22> self._cipher_suites = [\n<23> CipherSuite.AES_256_GCM_SHA384,\n<24> CipherSuite.AES_128_GCM_SHA256,\n<25> CipherSuite.CHACHA20_POLY1305_SHA256,\n<26> ]\n<27> self._compression_methods = [CompressionMethod.NULL]\n<28> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE]\n<29> self._signature_algorithms = [\n<30> SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n<31> SignatureAlgorithm.ECDSA_SECP256R1"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def __init__(\n self,\n is_client: bool,\n logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None,\n ):\n # offset: 1\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n self._supported_groups = [Group.SECP256R1]\n self._supported_versions = [TLS_VERSION_1_3]\n \n # state\n self._key_schedule_psk: Optional[KeySchedule] = None\n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n self._new_session_ticket: Optional[NewSessionTicket] = None\n self._peer_certificate: Optional[x509.Certificate] = None\n self._receive_buffer = b\"\"\n self._session_resumed = False\n self._enc_key: Optional[bytes] = None\n self._dec_key: Optional[bytes] = None\n self.__logger = logger\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n if is_client:\n self.client_random = os.urandom(32)\n self.session_id = os.urandom(32)\n self.state = State.CLIENT_HANDSHAKE_START\n else:\n self.client_random = None\n self.session_id = None\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n Direction()\n \n Epoch()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Extension = Tuple[int, bytes]\n \n 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))\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n 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))\n \n AlpnHandler = Callable[[str], None]\n \n \n===========unchanged ref 1===========\n at: aioquic.tls.Context._client_handle_certificate\n self._peer_certificate = x509.load_der_x509_certificate(\n certificate.certificates[0][0], backend=default_backend()\n )\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.alpn_negotiated = encrypted_extensions.alpn_protocol\n \n self.early_data_accepted = encrypted_extensions.early_data\n \n self.received_extensions = encrypted_extensions.other_extensions\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n \n self._session_resumed = True\n \n self._key_schedule_psk = None\n \n self._key_schedule_proxy = None\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n at: aioquic.tls.Context._server_handle_hello\n self.alpn_negotiated = negotiate(\n self.alpn_protocols,\n peer_hello.alpn_protocols,\n AlertHandshakeFailure(\"No common ALPN protocols\"),\n )\n \n self.client_random = peer_hello.random\n \n \n===========unchanged ref 2===========\n self.session_id = peer_hello.session_id\n \n self.received_extensions = peer_hello.other_extensions\n \n self.key_schedule = KeySchedule(cipher_suite)\n \n self._session_resumed = True\n \n self.early_data_accepted = True\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[key_share[0]](), default_backend()\n )\n \n self._new_session_ticket = NewSessionTicket(\n ticket_lifetime=86400,\n ticket_age_add=struct.unpack(\"I\", os.urandom(4))[0],\n ticket_nonce=b\"\",\n ticket=os.urandom(64),\n max_early_data_size=0xFFFFFFFF,\n )\n \n at: aioquic.tls.Context._setup_traffic_protection\n self._enc_key = key\n \n self._dec_key = key\n \n at: aioquic.tls.Context.handle_message\n self._receive_buffer += input_data\n self._receive_buffer = self._receive_buffer[message_length:]\n \n at: logging\n Logger(name: str, level: _Level=...)\n \n LoggerAdapter(logger: Logger, extra: Mapping[str, Any])\n \n at: os\n urandom(size: int, /) -> bytes\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n + def negotiate(\n + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None\n - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T:\n + ) -> T:\n if offered is not None:\n for c in supported:\n if c in offered:\n return c\n \n + if exc is not None:\n + raise exc\n - raise exc\n + return None\n \n===========changed ref 1===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + "}}},{"rowIdx":3053,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_send_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<23>: key_exchange_modes=self._key_exchange_modes,\n<25>: psk_key_exchange_modes=self._psk_key_exchange_modes\n if (self.session_ticket or self.new_session_ticket_cb is not None)\n else None,\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n <0> key_share: List[KeyShareEntry] = []\n <1> supported_groups: List[Group] = []\n <2> \n <3> if Group.SECP256R1 in self._supported_groups:\n <4> self._ec_private_key = ec.generate_private_key(\n <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n <6> )\n <7> key_share.append(encode_public_key(self._ec_private_key.public_key()))\n <8> supported_groups.append(Group.SECP256R1)\n <9> \n<10> if Group.X25519 in self._supported_groups:\n<11> self._x25519_private_key = x25519.X25519PrivateKey.generate()\n<12> key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n<13> supported_groups.append(Group.X25519)\n<14> \n<15> assert len(key_share), \"no key share entries\"\n<16> \n<17> hello = ClientHello(\n<18> random=self.client_random,\n<19> session_id=self.session_id,\n<20> cipher_suites=self._cipher_suites,\n<21> compression_methods=self._compression_methods,\n<22> alpn_protocols=self.alpn_protocols,\n<23> key_exchange_modes=self._key_exchange_modes,\n<24> key_share=key_share,\n<25> server_name=self.server_name,\n<26> signature_algorithms=self._signature_algorithms,\n<27> supported_groups=supported_groups,\n<28> supported_versions=self._supported_versions,\n<29> other_extensions=self.handshake_extensions,\n<30> )\n<31> \n<32> # PSK\n<33> if self.session_ticket and self.session_ticket.is_valid:\n<34> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n<35> self._key_schedule_psk."},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 1\n binder_key = self._key_schedule_psk.derive_secret(b\"res binder\")\n binder_length = self._key_schedule_psk.algorithm.digest_size\n \n # update hello\n if self.session_ticket.max_early_data_size is not None:\n hello.early_data = True\n hello.pre_shared_key = OfferedPsks(\n identities=[\n (self.session_ticket.ticket, self.session_ticket.obfuscated_age)\n ],\n binders=[bytes(binder_length)],\n )\n \n # serialize hello without binder\n tmp_buf = Buffer(capacity=1024)\n push_client_hello(tmp_buf, hello)\n \n # calculate binder\n hash_offset = tmp_buf.tell() - binder_length - 3\n self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset))\n binder = self._key_schedule_psk.finished_verify_data(binder_key)\n hello.pre_shared_key.binders[0] = binder\n self._key_schedule_psk.update_hash(\n tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder\n )\n \n # calculate early data key\n if hello.early_data:\n early_key = self._key_schedule_psk.derive_secret(b\"c e traffic\")\n self.update_traffic_key_cb(\n Direction.ENCRYPT,\n Epoch.ZERO_RTT,\n self._key_schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites)\n self._key_schedule_proxy.extract(None)\n \n with push_message(self._key_schedule_proxy, output_buf):\n push_client\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 2\n .extract(None)\n \n with push_message(self._key_schedule_proxy, output_buf):\n push_client_hello(output_buf, hello)\n \n self._set_state(State.CLIENT_EXPECT_SERVER_HELLO)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n data_slice(start: int, end: int) -> bytes\n \n tell() -> int\n \n at: aioquic.tls\n Direction()\n \n Epoch()\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n KeyShareEntry = Tuple[Group, bytes]\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n KeySchedule(cipher_suite: CipherSuite)\n \n GROUP_TO_CURVE = {\n Group.SECP256R1: ec.SECP256R1,\n Group.SECP384R1: ec.SECP384R1,\n Group.SECP521R1: ec.SECP521R1,\n }\n \n encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry\n \n at: aioquic.tls.ClientHello\n early_data: bool = False\n \n \n===========unchanged ref 1===========\n pre_shared_key: Optional[OfferedPsks] = None\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n \n self._compression_methods = [CompressionMethod.NULL]\n \n self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE]\n \n self._signature_algorithms = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n \n self._supported_groups = [Group.SECP256R1]\n \n self._supported_versions = [TLS_VERSION_1_3]\n \n self._key_schedule_psk: Optional[KeySchedule] = None\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n \n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n self.client_random = None\n self.client_random = os.urandom(32)\n \n self.session_id = None\n self.session_id = os.urandom(32)\n \n "}}},{"rowIdx":3054,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest._handshake"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":" <5>: self.assertGreaterEqual(len(server_input), 213)\n self.assertGreaterEqual(len(server_input), 219)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n <0> # send client hello\n <1> client_buf = create_buffers()\n <2> client.handle_message(b\"\", client_buf)\n <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n <4> server_input = merge_buffers(client_buf)\n <5> self.assertGreaterEqual(len(server_input), 219)\n <6> self.assertLessEqual(len(server_input), 264)\n <7> reset_buffers(client_buf)\n <8> \n <9> # handle client hello\n<10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<11> server_buf = create_buffers()\n<12> server.handle_message(server_input, server_buf)\n<13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED)\n<14> client_input = merge_buffers(server_buf)\n<15> self.assertGreaterEqual(len(client_input), 600)\n<16> self.assertLessEqual(len(client_input), 2316)\n<17> \n<18> reset_buffers(server_buf)\n<19> \n<20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n<21> # send finished\n<22> client.handle_message(client_input, client_buf)\n<23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE)\n<24> server_input = merge_buffers(client_buf)\n<25> self.assertEqual(len(server_input), 52)\n<26> reset_buffers(client_buf)\n<27> \n<28> # handle finished\n<29> server.handle_message(server_input, server_buf)\n<30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE)\n<31> client_input = merge_buffers(server_buf)\n<32> self.assertEqual(len(client_input), 0)\n<33> \n<34> # check keys match\n<35> self.assertEqual(client._dec_key, server._enc_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # offset: 1\n self.assertEqual(client._enc_key, server._dec_key)\n \n # check cipher suite\n self.assertEqual(\n client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n self.assertEqual(\n server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n State()\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n at: aioquic.tls.Context\n handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None\n \n at: aioquic.tls.Context.__init__\n self.key_schedule: Optional[KeySchedule] = None\n \n self._enc_key: Optional[bytes] = None\n \n self._dec_key: Optional[bytes] = None\n \n self.state = State.CLIENT_HANDSHAKE_START\n self.state = State.SERVER_EXPECT_CLIENT_HELLO\n \n at: aioquic.tls.Context._client_handle_finished\n self._enc_key = next_enc_key\n \n at: aioquic.tls.Context._client_handle_hello\n self.key_schedule = self._key_schedule_psk\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n \n at: aioquic.tls.Context._server_handle_finished\n self._dec_key = self._next_dec_key\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n at: aioquic.tls.Context._set_state\n self.state = state\n \n at: aioquic.tls.Context._setup_traffic_protection\n self._enc_key = key\n \n self._dec_key = key\n \n at: aioquic.tls.KeySchedule.__init__\n self.cipher_suite = cipher_suite\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n \n===========unchanged ref 1===========\n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None\n \n assertLessEqual(a: Any, b: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:\n - return KeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 1===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + \n===========changed ref 2===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 3===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 4===========\n # module: aioquic.tls\n + def negotiate(\n + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None\n - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T:\n + ) -> T:\n if offered is not None:\n for c in supported:\n if c in offered:\n return c\n \n + if exc is not None:\n + raise exc\n - raise exc\n + return None\n \n===========changed ref 5===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 6===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n buf.push_uint8(HandshakeType.CLIENT_HELLO)\n with push_block(buf, 3):\n buf.push_uint16(TLS_VERSION_1_2)\n buf.push_bytes(hello.random)\n push_opaque(buf, 1, hello.session_id)\n push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n \n # extensions\n with push_block(buf, 2):\n with push_extension(buf, ExtensionType.KEY_SHARE):\n push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n \n with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n \n with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n \n with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n \n + if hello.psk_key_exchange_modes is not None:\n + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n \n if hello.server_name is not None:\n with push_extension(buf, ExtensionType.SERVER_NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque"}}},{"rowIdx":3055,"cells":{"path":{"kind":"string","value":"tests.test_tls/ContextTest.test_handshake_with_alpn_fail"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<11>: self.assertEqual(len(server_input), 258)\n self.assertEqual(len(server_input), 264)\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class ContextTest(TestCase):\n def test_handshake_with_alpn_fail(self):\n <0> client = self.create_client()\n <1> client.alpn_protocols = [\"hq-20\"]\n <2> \n <3> server = self.create_server()\n <4> server.alpn_protocols = [\"h3-20\"]\n <5> \n <6> # send client hello\n <7> client_buf = create_buffers()\n <8> client.handle_message(b\"\", client_buf)\n <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n<10> server_input = merge_buffers(client_buf)\n<11> self.assertEqual(len(server_input), 264)\n<12> reset_buffers(client_buf)\n<13> \n<14> # handle client hello\n<15> # send server hello, encrypted extensions, certificate, certificate verify, finished\n<16> server_buf = create_buffers()\n<17> with self.assertRaises(tls.AlertHandshakeFailure) as cm:\n<18> server.handle_message(server_input, server_buf)\n<19> self.assertEqual(str(cm.exception), \"No common ALPN protocols\")\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.tls\n AlertHandshakeFailure(*args: object)\n \n State()\n \n at: tests.test_tls\n create_buffers()\n \n merge_buffers(buffers)\n \n reset_buffers(buffers)\n \n at: tests.test_tls.ContextTest\n create_client()\n \n create_server()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E]\n assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None\n \n at: unittest.case._AssertRaisesContext.__exit__\n self.exception = exc_value.with_traceback(None)\n \n \n===========changed ref 0===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # send client hello\n client_buf = create_buffers()\n client.handle_message(b\"\", client_buf)\n self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO)\n server_input = merge_buffers(client_buf)\n + self.assertGreaterEqual(len(server_input), 213)\n - self.assertGreaterEqual(len(server_input), 219)\n self.assertLessEqual(len(server_input), 264)\n reset_buffers(client_buf)\n \n # handle client hello\n # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n server_buf = create_buffers()\n server.handle_message(server_input, server_buf)\n self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED)\n client_input = merge_buffers(server_buf)\n self.assertGreaterEqual(len(client_input), 600)\n self.assertLessEqual(len(client_input), 2316)\n \n reset_buffers(server_buf)\n \n # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket)\n # send finished\n client.handle_message(client_input, client_buf)\n self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE)\n server_input = merge_buffers(client_buf)\n self.assertEqual(len(server_input), 52)\n reset_buffers(client_buf)\n \n # handle finished\n server.handle_message(server_input, server_buf)\n self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE)\n client_input = merge_buffers(server_buf)\n self.assertEqual(len(client_input), 0)\n \n # check keys match\n self.assertEqual(client._dec_key, server._enc_key)\n self.assertEqual(client._enc_key, server._\n===========changed ref 1===========\n # module: tests.test_tls\n class ContextTest(TestCase):\n def _handshake(self, client, server):\n # offset: 1\n assertEqual(client._dec_key, server._enc_key)\n self.assertEqual(client._enc_key, server._dec_key)\n \n # check cipher suite\n self.assertEqual(\n client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n self.assertEqual(\n server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384\n )\n \n===========changed ref 2===========\n # module: aioquic.tls\n - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode:\n - return KeyExchangeMode(buf.pull_uint8())\n - \n===========changed ref 3===========\n # module: aioquic.tls\n + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode:\n + return PskKeyExchangeMode(buf.pull_uint8())\n + \n===========changed ref 4===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 5===========\n # module: aioquic.tls\n - class KeyExchangeMode(IntEnum):\n - PSK_KE = 0\n - PSK_DHE_KE = 1\n - \n===========changed ref 6===========\n # module: aioquic.tls\n + def negotiate(\n + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None\n - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T:\n + ) -> T:\n if offered is not None:\n for c in supported:\n if c in offered:\n return c\n \n + if exc is not None:\n + raise exc\n - raise exc\n + return None\n \n===========changed ref 7===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 8===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n buf.push_uint8(HandshakeType.CLIENT_HELLO)\n with push_block(buf, 3):\n buf.push_uint16(TLS_VERSION_1_2)\n buf.push_bytes(hello.random)\n push_opaque(buf, 1, hello.session_id)\n push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n \n # extensions\n with push_block(buf, 2):\n with push_extension(buf, ExtensionType.KEY_SHARE):\n push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n \n with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n \n with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n \n with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n \n + if hello.psk_key_exchange_modes is not None:\n + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n \n if hello.server_name is not None:\n with push_extension(buf, ExtensionType.SERVER_NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque"}}},{"rowIdx":3056,"cells":{"path":{"kind":"string","value":"tests.test_tls/TlsTest.test_pull_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<28>: self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello(self):\n <0> buf = Buffer(data=load(\"tls_client_hello.bin\"))\n <1> hello = pull_client_hello(buf)\n <2> self.assertTrue(buf.eof())\n <3> \n <4> self.assertEqual(\n <5> hello.random,\n <6> binascii.unhexlify(\n <7> \"18b2b23bf3e44b5d52ccfe7aecbc5ff14eadc3d349fabf804d71f165ae76e7d5\"\n <8> ),\n <9> )\n<10> self.assertEqual(\n<11> hello.session_id,\n<12> binascii.unhexlify(\n<13> \"9aee82a2d186c1cb32a329d9dcfe004a1a438ad0485a53c6bfcf55c132a23235\"\n<14> ),\n<15> )\n<16> self.assertEqual(\n<17> hello.cipher_suites,\n<18> [\n<19> tls.CipherSuite.AES_256_GCM_SHA384,\n<20> tls.CipherSuite.AES_128_GCM_SHA256,\n<21> tls.CipherSuite.CHACHA20_POLY1305_SHA256,\n<22> ],\n<23> )\n<24> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL])\n<25> \n<26> # extensions\n<27> self.assertEqual(hello.alpn_protocols, None)\n<28> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n<29> self.assertEqual(\n<30> hello.key_share,\n<31> [\n<32> (\n<33> tls.Group.SECP256R1,\n<34> binascii.unhexlify(\n<35> \"047bfea344467535054263b75def60cffa82405a211b68d1eb8d1d944e67aef8\"\n<36> \"93c7665a54"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello(self):\n # offset: 1\n \"b0\"\n ),\n )\n ],\n )\n self.assertEqual(hello.server_name, None)\n self.assertEqual(\n hello.signature_algorithms,\n [\n tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA256,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA1,\n ],\n )\n self.assertEqual(hello.supported_groups, [tls.Group.SECP256R1])\n self.assertEqual(\n hello.supported_versions,\n [\n tls.TLS_VERSION_1_3,\n tls.TLS_VERSION_1_3_DRAFT_28,\n tls.TLS_VERSION_1_3_DRAFT_27,\n tls.TLS_VERSION_1_3_DRAFT_26,\n ],\n )\n \n self.assertEqual(\n hello.other_extensions,\n [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n TLS_VERSION_1_3_DRAFT_28 = 0x7F1C\n \n TLS_VERSION_1_3_DRAFT_27 = 0x7F1B\n \n TLS_VERSION_1_3_DRAFT_26 = 0x7F1A\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_client_hello(buf: Buffer) -> ClientHello\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n \n===========unchanged ref 1===========\n at: tests.test_tls\n CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff0000110031000500048010000000060004801000000007000480100000000\"\n b\"4000481000000000100024258000800024064000a00010a\"\n )\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n compression_methods=pull_list(\n buf, 1, partial(pull_compression_method, buf)\n ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n hello.signature_algorithms = pull_list(\n buf, 2, partial(pull_signature_algorithm, buf)\n )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n + hello.psk_key_exchange_modes = pull_list(\n - hello.key_exchange_modes = pull_list(\n + buf, 1, partial(pull_psk_key_exchange_mode, buf)\n - buf, 1, partial(pull_key_exchange_mode,\n===========changed ref 1===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n pull_psk_key_exchange_mode, buf)\n - buf, 1, partial(pull_key_exchange_mode, buf)\n )\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n "}}},{"rowIdx":3057,"cells":{"path":{"kind":"string","value":"tests.test_tls/TlsTest.test_pull_client_hello_with_alpn"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<25>: self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello_with_alpn(self):\n <0> buf = Buffer(data=load(\"tls_client_hello_with_alpn.bin\"))\n <1> hello = pull_client_hello(buf)\n <2> self.assertTrue(buf.eof())\n <3> \n <4> self.assertEqual(\n <5> hello.random,\n <6> binascii.unhexlify(\n <7> \"ed575c6fbd599c4dfaabd003dca6e860ccdb0e1782c1af02e57bf27cb6479b76\"\n <8> ),\n <9> )\n<10> self.assertEqual(hello.session_id, b\"\")\n<11> self.assertEqual(\n<12> hello.cipher_suites,\n<13> [\n<14> tls.CipherSuite.AES_128_GCM_SHA256,\n<15> tls.CipherSuite.AES_256_GCM_SHA384,\n<16> tls.CipherSuite.CHACHA20_POLY1305_SHA256,\n<17> tls.CipherSuite.EMPTY_RENEGOTIATION_INFO_SCSV,\n<18> ],\n<19> )\n<20> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL])\n<21> \n<22> # extensions\n<23> self.assertEqual(hello.alpn_protocols, [\"h3-19\"])\n<24> self.assertEqual(hello.early_data, False)\n<25> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n<26> self.assertEqual(\n<27> hello.key_share,\n<28> [\n<29> (\n<30> tls.Group.SECP256R1,\n<31> binascii.unhexlify(\n<32> \"048842315c437bb0ce2929c816fee4e942ec5cb6db6a6b9bf622680188ebb0d4\"\n<33> \"b652e69033f71686aa01cbc79155866e264c9"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello_with_alpn(self):\n # offset: 1\n \"22\"\n ),\n )\n ],\n )\n self.assertEqual(hello.server_name, \"cloudflare-quic.com\")\n self.assertEqual(\n hello.signature_algorithms,\n [\n tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n tls.SignatureAlgorithm.ECDSA_SECP384R1_SHA384,\n tls.SignatureAlgorithm.ECDSA_SECP521R1_SHA512,\n tls.SignatureAlgorithm.ED25519,\n tls.SignatureAlgorithm.ED448,\n tls.SignatureAlgorithm.RSA_PSS_PSS_SHA256,\n tls.SignatureAlgorithm.RSA_PSS_PSS_SHA384,\n tls.SignatureAlgorithm.RSA_PSS_PSS_SHA512,\n tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA384,\n tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA256,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA384,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA512,\n ],\n )\n self.assertEqual(\n hello.supported_groups,\n [\n tls.Group.SECP256R1,\n tls.Group.X25519,\n tls.Group.SECP384R1,\n tls.Group.SECP521R1,\n ],\n )\n self.assertEqual(hello.supported_versions, [tls.TLS_VERSION_1_3])\n \n # serialize\n buf = Buffer(1000)\n push_client_hello(buf, hello)\n self.assertEqual(len(buf.data), len(load(\"tls_client_hello_with_alpn.bin\")))\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_client_hello(buf: Buffer) -> ClientHello\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n compression_methods=pull_list(\n buf, 1, partial(pull_compression_method, buf)\n ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n hello.signature_algorithms = pull_list(\n buf, 2, partial(pull_signature_algorithm, buf)\n )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n + hello.psk_key_exchange_modes = pull_list(\n - hello.key_exchange_modes = pull_list(\n + buf, 1, partial(pull_psk_key_exchange_mode, buf)\n - buf, 1, partial(pull_key_exchange_mode,\n===========changed ref 1===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n pull_psk_key_exchange_mode, buf)\n - buf, 1, partial(pull_key_exchange_mode, buf)\n )\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n "}}},{"rowIdx":3058,"cells":{"path":{"kind":"string","value":"tests.test_tls/TlsTest.test_pull_client_hello_with_sni"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<28>: self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello_with_sni(self):\n <0> buf = Buffer(data=load(\"tls_client_hello_with_sni.bin\"))\n <1> hello = pull_client_hello(buf)\n <2> self.assertTrue(buf.eof())\n <3> \n <4> self.assertEqual(\n <5> hello.random,\n <6> binascii.unhexlify(\n <7> \"987d8934140b0a42cc5545071f3f9f7f61963d7b6404eb674c8dbe513604346b\"\n <8> ),\n <9> )\n<10> self.assertEqual(\n<11> hello.session_id,\n<12> binascii.unhexlify(\n<13> \"26b19bdd30dbf751015a3a16e13bd59002dfe420b799d2a5cd5e11b8fa7bcb66\"\n<14> ),\n<15> )\n<16> self.assertEqual(\n<17> hello.cipher_suites,\n<18> [\n<19> tls.CipherSuite.AES_256_GCM_SHA384,\n<20> tls.CipherSuite.AES_128_GCM_SHA256,\n<21> tls.CipherSuite.CHACHA20_POLY1305_SHA256,\n<22> ],\n<23> )\n<24> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL])\n<25> \n<26> # extensions\n<27> self.assertEqual(hello.alpn_protocols, None)\n<28> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])\n<29> self.assertEqual(\n<30> hello.key_share,\n<31> [\n<32> (\n<33> tls.Group.SECP256R1,\n<34> binascii.unhexlify(\n<35> \"04b62d70f907c814cd65d0f73b8b991f06b70c77153f548410a191d2b19764a2\"\n<36> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class TlsTest(TestCase):\n def test_pull_client_hello_with_sni(self):\n # offset: 1\n \"40\"\n ),\n )\n ],\n )\n self.assertEqual(hello.server_name, \"cloudflare-quic.com\")\n self.assertEqual(\n hello.signature_algorithms,\n [\n tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA256,\n tls.SignatureAlgorithm.RSA_PKCS1_SHA1,\n ],\n )\n self.assertEqual(hello.supported_groups, [tls.Group.SECP256R1])\n self.assertEqual(\n hello.supported_versions,\n [\n tls.TLS_VERSION_1_3,\n tls.TLS_VERSION_1_3_DRAFT_28,\n tls.TLS_VERSION_1_3_DRAFT_27,\n tls.TLS_VERSION_1_3_DRAFT_26,\n ],\n )\n \n self.assertEqual(\n hello.other_extensions,\n [\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ],\n )\n \n # serialize\n buf = Buffer(1000)\n push_client_hello(buf, hello)\n self.assertEqual(buf.data, load(\"tls_client_hello_with_sni.bin\"))\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n TLS_VERSION_1_3_DRAFT_28 = 0x7F1C\n \n TLS_VERSION_1_3_DRAFT_27 = 0x7F1B\n \n TLS_VERSION_1_3_DRAFT_26 = 0x7F1A\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_client_hello(buf: Buffer) -> ClientHello\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n \n===========unchanged ref 1===========\n at: tests.test_tls\n CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff0000110031000500048010000000060004801000000007000480100000000\"\n b\"4000481000000000100024258000800024064000a00010a\"\n )\n \n at: tests.test_tls.TlsTest.test_pull_client_hello_with_psk\n hello = pull_client_hello(buf)\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n buf.push_uint8(HandshakeType.CLIENT_HELLO)\n with push_block(buf, 3):\n buf.push_uint16(TLS_VERSION_1_2)\n buf.push_bytes(hello.random)\n push_opaque(buf, 1, hello.session_id)\n push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n \n # extensions\n with push_block(buf, 2):\n with push_extension(buf, ExtensionType.KEY_SHARE):\n push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n \n with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n \n with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n \n with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n \n + if hello.psk_key_exchange_modes is not None:\n + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n \n if hello.server_name is not None:\n with push_extension(buf, ExtensionType.SERVER_NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque\n===========changed ref 1===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n # offset: 1\n NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque(buf, 2, hello.server_name.encode(\"ascii\"))\n \n if hello.alpn_protocols is not None:\n with push_extension(buf, ExtensionType.ALPN):\n push_list(\n buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols\n )\n \n for extension_type, extension_value in hello.other_extensions:\n with push_extension(buf, extension_type):\n buf.push_bytes(extension_value)\n \n if hello.early_data:\n with push_extension(buf, ExtensionType.EARLY_DATA):\n pass\n \n # pre_shared_key MUST be last\n if hello.pre_shared_key is not None:\n with push_extension(buf, ExtensionType.PRE_SHARED_KEY):\n push_list(\n buf,\n 2,\n partial(push_psk_identity, buf),\n hello.pre_shared_key.identities,\n )\n push_list(\n buf,\n 2,\n partial(push_psk_binder, buf),\n hello.pre_shared_key.binders,\n )\n "}}},{"rowIdx":3059,"cells":{"path":{"kind":"string","value":"tests.test_tls/TlsTest.test_push_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"0ba9b1c08cda47da8e51f68e96caeae600658679"},"commit_message":{"kind":"string","value":"[tls] make PSK support optional"},"ground_truth":{"kind":"string","value":"<13>: key_exchange_modes=[tls.KeyExchangeMode.PSK_DHE_KE],\n<24>: psk_key_exchange_modes=[tls.PskKeyExchangeMode.PSK_DHE_KE],\n"},"main_code":{"kind":"string","value":" # module: tests.test_tls\n class TlsTest(TestCase):\n def test_push_client_hello(self):\n <0> hello = ClientHello(\n <1> random=binascii.unhexlify(\n <2> \"18b2b23bf3e44b5d52ccfe7aecbc5ff14eadc3d349fabf804d71f165ae76e7d5\"\n <3> ),\n <4> session_id=binascii.unhexlify(\n <5> \"9aee82a2d186c1cb32a329d9dcfe004a1a438ad0485a53c6bfcf55c132a23235\"\n <6> ),\n <7> cipher_suites=[\n <8> tls.CipherSuite.AES_256_GCM_SHA384,\n <9> tls.CipherSuite.AES_128_GCM_SHA256,\n<10> tls.CipherSuite.CHACHA20_POLY1305_SHA256,\n<11> ],\n<12> compression_methods=[tls.CompressionMethod.NULL],\n<13> key_exchange_modes=[tls.KeyExchangeMode.PSK_DHE_KE],\n<14> key_share=[\n<15> (\n<16> tls.Group.SECP256R1,\n<17> binascii.unhexlify(\n<18> \"047bfea344467535054263b75def60cffa82405a211b68d1eb8d1d944e67aef8\"\n<19> \"93c7665a5473d032cfaf22a73da28eb4aacae0017ed12557b5791f98a1e84f15\"\n<20> \"b0\"\n<21> ),\n<22> )\n<23> ],\n<24> signature_algorithms=[\n<25> tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n<26> tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n<27> tls.SignatureAlgorithm.RSA_PKCS1_SHA256,\n<28> tls.SignatureAlgorithm.RSA_PKCS1_SHA1,\n<29> ],\n<30> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_tls\n class TlsTest(TestCase):\n def test_push_client_hello(self):\n # offset: 1\n supported_versions=[\n tls.TLS_VERSION_1_3,\n tls.TLS_VERSION_1_3_DRAFT_28,\n tls.TLS_VERSION_1_3_DRAFT_27,\n tls.TLS_VERSION_1_3_DRAFT_26,\n ],\n other_extensions=[\n (\n tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS,\n CLIENT_QUIC_TRANSPORT_PARAMETERS,\n )\n ],\n )\n \n buf = Buffer(1000)\n push_client_hello(buf, hello)\n self.assertEqual(buf.data, load(\"tls_client_hello.bin\"))\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic.tls\n TLS_VERSION_1_3 = 0x0304\n \n TLS_VERSION_1_3_DRAFT_28 = 0x7F1C\n \n TLS_VERSION_1_3_DRAFT_27 = 0x7F1B\n \n TLS_VERSION_1_3_DRAFT_26 = 0x7F1A\n \n CipherSuite(x: Union[str, bytes, bytearray], base: int)\n CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n CompressionMethod(x: Union[str, bytes, bytearray], base: int)\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int)\n PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int)\n SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n \n===========unchanged ref 1===========\n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[CipherSuite]\n \n compression_methods: List[CompressionMethod]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n \n supported_groups: Optional[List[Group]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: binascii\n unhexlify(hexstr: _Ascii, /) -> bytes\n \n \n===========unchanged ref 2===========\n at: tests.test_tls\n CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify(\n b\"ff0000110031000500048010000000060004801000000007000480100000000\"\n b\"4000481000000000100024258000800024064000a00010a\"\n )\n \n at: tests.test_tls.TlsTest.test_pull_client_hello_with_sni\n hello = pull_client_hello(buf)\n \n at: tests.utils\n load(name)\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n - key_exchange_modes: Optional[List[KeyExchangeMode]] = None\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n def push_client_hello(buf: Buffer, hello: ClientHello) -> None:\n buf.push_uint8(HandshakeType.CLIENT_HELLO)\n with push_block(buf, 3):\n buf.push_uint16(TLS_VERSION_1_2)\n buf.push_bytes(hello.random)\n push_opaque(buf, 1, hello.session_id)\n push_list(buf, 2, buf.push_uint16, hello.cipher_suites)\n push_list(buf, 1, buf.push_uint8, hello.compression_methods)\n \n # extensions\n with push_block(buf, 2):\n with push_extension(buf, ExtensionType.KEY_SHARE):\n push_list(buf, 2, partial(push_key_share, buf), hello.key_share)\n \n with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS):\n push_list(buf, 1, buf.push_uint16, hello.supported_versions)\n \n with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS):\n push_list(buf, 2, buf.push_uint16, hello.signature_algorithms)\n \n with push_extension(buf, ExtensionType.SUPPORTED_GROUPS):\n push_list(buf, 2, buf.push_uint16, hello.supported_groups)\n \n + if hello.psk_key_exchange_modes is not None:\n + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES):\n + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes)\n - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)\n \n if hello.server_name is not None:\n with push_extension(buf, ExtensionType.SERVER_NAME):\n with push_block(buf, 2):\n buf.push_uint8(0)\n push_opaque"}}},{"rowIdx":3060,"cells":{"path":{"kind":"string","value":"docs.http_client/http_client"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d9f0026d04752d629421b8fa9518f0b06a49980e"},"commit_message":{"kind":"string","value":"[examples] output HTTP response to stdout"},"ground_truth":{"kind":"string","value":" <6>: sys.stdout.buffer.write(response)\n print(response.decode(\"utf8\"))\n"},"main_code":{"kind":"string","value":" # module: docs.http_client\n def http_client(host, port):\n <0> async with connect(host, port) as connection:\n <1> reader, writer = await connection.create_stream()\n <2> writer.write(b\"GET /\\r\\n\")\n <3> writer.write_eof()\n <4> \n <5> response = await reader.read()\n <6> print(response.decode(\"utf8\"))\n <7> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]\n \n at: asyncio.streams.StreamReader\n _source_traceback = None\n \n read(n: int=...) -> bytes\n \n at: asyncio.streams.StreamWriter\n write(data: bytes) -> None\n \n write_eof() -> None\n \n "}}},{"rowIdx":3061,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d9f0026d04752d629421b8fa9518f0b06a49980e"},"commit_message":{"kind":"string","value":"[examples] output HTTP response to stdout"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n<18> is_client=True,\n<19> server_name=server_name,\n<20> **kwargs\n<21> ),\n<22> session_ticket_handler=save_session_ticket,\n<23> )\n<24> quic.connect(server_addr, now=time.time())\n<25> \n<26> # send request\n<27> http: HttpConnection\n<28> if legacy_http:\n<29> http = H0Connection(quic)\n<30> else:\n<31> http = H3Connection(quic)\n<32> stream_id = quic.get_next_available_stream_id()\n<33> http.send_headers(\n<34> stream_id=stream_id,\n<35> headers=[\n<36> (b\":method\", b\"GET\"),\n<37> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<38> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<39> (b\":path\", parsed.path.encode(\"utf8\")),\n<40> (b\"user-agent\", b\"aioquic\"),\n<41> ],\n<42> )\n<43> http.send_data(stream_id=stream_id, data"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n print(http_event)\n if isinstance(http_event, (DataReceived, ResponseReceived)):\n stream_ended = http_event.stream_ended\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n \n===========unchanged ref 1===========\n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n save_session_ticket(ticket)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: sys\n stdout: TextIO\n \n stderr: TextIO\n \n at: time\n time() -> float\n \n at: typing.BinaryIO\n __slots__ = ()\n \n write(s: AnyStr) -> int\n \n at: typing.TextIO\n __slots__ = ()\n \n \n===========unchanged ref 2===========\n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: docs.http_client\n def http_client(host, port):\n async with connect(host, port) as connection:\n reader, writer = await connection.create_stream()\n writer.write(b\"GET /\\r\\n\")\n writer.write_eof()\n \n response = await reader.read()\n + sys.stdout.buffer.write(response)\n - print(response.decode(\"utf8\"))\n "}}},{"rowIdx":3062,"cells":{"path":{"kind":"string","value":"examples.client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d9f0026d04752d629421b8fa9518f0b06a49980e"},"commit_message":{"kind":"string","value":"[examples] output HTTP response to stdout"},"ground_truth":{"kind":"string","value":"<19>: sys.stdout.buffer.write(response)\n print(response.decode(\"utf8\"))\n"},"main_code":{"kind":"string","value":" # module: examples.client\n def run(url, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> async with connect(server_name, port, **kwargs) as connection:\n<11> # perform HTTP/0.9 request\n<12> reader, writer = await connection.create_stream()\n<13> writer.write((\"GET %s\\r\\n\" % parsed.path).encode(\"utf8\"))\n<14> writer.write_eof()\n<15> \n<16> start = time.time()\n<17> response = await reader.read()\n<18> elapsed = time.time() - start\n<19> print(response.decode(\"utf8\"))\n<20> \n<21> octets = len(response)\n<22> logger.info(\n<23> \"Received %d bytes in %.1f s (%.3f Mbps)\"\n<24> % (octets, elapsed, octets * 8 / elapsed / 1000000)\n<25> )\n<26> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]\n \n at: asyncio.streams.StreamReader\n _source_traceback = None\n \n read(n: int=...) -> bytes\n \n at: asyncio.streams.StreamWriter\n write(data: bytes) -> None\n \n write_eof() -> None\n \n at: examples.client\n logger = logging.getLogger(\"client\")\n \n at: logging.Logger\n info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None\n \n at: sys\n stdout: TextIO\n \n at: time\n time() -> float\n \n at: typing.BinaryIO\n __slots__ = ()\n \n write(s: AnyStr) -> int\n \n at: typing.TextIO\n __slots__ = ()\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: docs.http_client\n def http_client(host, port):\n async with connect(host, port) as connection:\n reader, writer = await connection.create_stream()\n writer.write(b\"GET /\\r\\n\")\n writer.write_eof()\n \n response = await reader.read()\n + sys.stdout.buffer.write(response)\n - print(response.decode(\"utf8\"))\n \n===========changed ref 1===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # parse URL\n parsed = urlparse(url)\n assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n if \":\" in parsed.netloc:\n server_name, port_str = parsed.netloc.split(\":\")\n port = int(port_str)\n else:\n server_name = parsed.netloc\n port = 443\n \n # prepare socket\n server_addr = (socket.gethostbyname(server_name), port)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n \n # prepare QUIC connection\n quic = QuicConnection(\n configuration=QuicConfiguration(\n alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n is_client=True,\n server_name=server_name,\n **kwargs\n ),\n session_ticket_handler=save_session_ticket,\n )\n quic.connect(server_addr, now=time.time())\n \n # send request\n http: HttpConnection\n if legacy_http:\n http = H0Connection(quic)\n else:\n http = H3Connection(quic)\n stream_id = quic.get_next_available_stream_id()\n http.send_headers(\n stream_id=stream_id,\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n (b\":authority\", parsed.netloc.encode(\"utf8\")),\n (b\":path\", parsed.path.encode(\"utf8\")),\n (b\"user-agent\", b\"aioquic\"),\n ],\n )\n http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data,\n===========changed ref 2===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n , addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n - print(http_event)\n + if isinstance(http_event, ResponseReceived):\n - if isinstance(http_event, (DataReceived, ResponseReceived)):\n stream_ended = http_event.stream_ended\n + headers = b\"\"\n + for k, v in http_event.headers:\n + headers += k + b\": \" + v + b\"\\r\\n\"\n + if headers:\n + sys.stderr.buffer.write(headers + b\"\\r\\n\")\n + if isinstance(http_event, DataReceived):\n + stream_ended = http_event.stream_ended\n + sys.stdout.buffer.write(http_event.data)\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n "}}},{"rowIdx":3063,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"4678fdd22323723bd6bc0e5016fdb7ed264722a7"},"commit_message":{"kind":"string","value":"[http3] ensure table size update gets sent"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> consumed = 0\n <7> \n <8> buf = Buffer(data=self._stream_buffers[stream_id])\n <9> while not buf.eof():\n<10> # fetch stream type for unidirectional streams\n<11> if (\n<12> stream_is_unidirectional(stream_id)\n<13> and stream_id not in self._stream_types\n<14> ):\n<15> try:\n<16> stream_type = buf.pull_uint_var()\n<17> except BufferReadError:\n<18> break\n<19> consumed = buf.tell()\n<20> \n<21> if stream_type == StreamType.CONTROL:\n<22> assert self._peer_control_stream_id is None\n<23> self._peer_control_stream_id = stream_id\n<24> elif stream_type == StreamType.QPACK_DECODER:\n<25> assert self._peer_decoder_stream_id is None\n<26> self._peer_decoder_stream_id = stream_id\n<27> elif stream_type == StreamType.QPACK_ENCODER:\n<28> assert self._peer_encoder_stream_id is None\n<29> self._peer_encoder_stream_id = stream_id\n<30> self._stream_types[stream_id] = stream_type\n<31> \n<32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n<33> # fetch next frame\n<34> try:\n<35> frame_type = buf.pull_uint_var()\n<36> frame_length = buf.pull_uint_var()\n<37> frame_data = buf.pull_bytes(frame_length)\n<38> except BufferReadError:\n<39> break\n<40> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n decoder, headers = self._decoder.feed_header(\n stream_id, frame_data\n )\n self._quic.send_stream_data(\n self._local_decoder_stream_id, decoder\n )\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(\n Setting.QPACK_BLOCKED_STREAMS, 0\n ),\n )\n else:\n # fetch unframed data\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n \n if stream_id == self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id == self._peer_encoder_stream_id:\n self._decoder.feed_encoder(data)\n \n # remove processed data from buffer\n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 2\n ._peer_encoder_stream_id:\n self._decoder.feed_encoder(data)\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._quic = quic\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n self._peer_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n "}}},{"rowIdx":3064,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"88362eee9e4573402d32f88554680c03f67dabaf"},"commit_message":{"kind":"string","value":"[http3] handle receiving FIN only on a stream"},"ground_truth":{"kind":"string","value":" <6>: \n buf = Buffer(data=self._stream_buffers[stream_id])\n <8>: # some peers (e.g. f5) end the stream with no data\n if stream_ended and buf.eof() and (stream_id % 4 == 0):\n http_events.append(\n DataReceived(data=b\"\", stream_id=stream_id, stream_ended=True)\n )\n \n buf = Buffer(data=self._stream_buffers[stream_id])\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> consumed = 0\n <7> \n <8> buf = Buffer(data=self._stream_buffers[stream_id])\n <9> while not buf.eof():\n<10> # fetch stream type for unidirectional streams\n<11> if (\n<12> stream_is_unidirectional(stream_id)\n<13> and stream_id not in self._stream_types\n<14> ):\n<15> try:\n<16> stream_type = buf.pull_uint_var()\n<17> except BufferReadError:\n<18> break\n<19> consumed = buf.tell()\n<20> \n<21> if stream_type == StreamType.CONTROL:\n<22> assert self._peer_control_stream_id is None\n<23> self._peer_control_stream_id = stream_id\n<24> elif stream_type == StreamType.QPACK_DECODER:\n<25> assert self._peer_decoder_stream_id is None\n<26> self._peer_decoder_stream_id = stream_id\n<27> elif stream_type == StreamType.QPACK_ENCODER:\n<28> assert self._peer_encoder_stream_id is None\n<29> self._peer_encoder_stream_id = stream_id\n<30> self._stream_types[stream_id] = stream_type\n<31> \n<32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n<33> # fetch next frame\n<34> try:\n<35> frame_type = buf.pull_uint_var()\n<36> frame_length = buf.pull_uint_var()\n<37> frame_data = buf.pull_bytes(frame_length)\n<38> except BufferReadError:\n<39> break\n<40> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n decoder, headers = self._decoder.feed_header(\n stream_id, frame_data\n )\n self._quic.send_stream_data(\n self._local_decoder_stream_id, decoder\n )\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n encoder = self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(\n Setting.QPACK_BLOCKED_STREAMS, 0\n ),\n )\n self._quic.send_stream_data(\n self._local_encoder_stream_id, encoder\n )\n else:\n # fetch unframed data\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n \n if stream_id == self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id ==\n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 2\n self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id == self._peer_encoder_stream_id:\n self._decoder.feed_encoder(data)\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._quic = quic\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_types: Dict[int, int] = {}\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n self._peer_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n "}}},{"rowIdx":3065,"cells":{"path":{"kind":"string","value":"aioquic.packet_builder/QuicPacketBuilder.start_packet"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n <0> \"\"\"\n <1> Starts a new packet.\n <2> \"\"\"\n <3> buf = self.buffer\n <4> self._ack_eliciting = False\n <5> \n <6> # if there is too little space remaining, start a new datagram\n <7> # FIXME: the limit is arbitrary!\n <8> packet_start = buf.tell()\n <9> if self._buffer_capacity - packet_start < 128:\n<10> self._flush_current_datagram()\n<11> packet_start = 0\n<12> \n<13> # initialize datagram if needed\n<14> if self._datagram_init:\n<15> if self.max_flight_bytes is not None:\n<16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n<17> if remaining_flight_bytes < self._buffer_capacity:\n<18> self._buffer_capacity = remaining_flight_bytes\n<19> if self.max_total_bytes is not None:\n<20> remaining_total_bytes = self.max_total_bytes - self._total_bytes\n<21> if remaining_total_bytes < self._buffer_capacity:\n<22> self._buffer_capacity = remaining_total_bytes\n<23> self._datagram_init = False\n<24> \n<25> # calculate header size\n<26> packet_long_header = is_long_header(packet_type)\n<27> if packet_long_header:\n<28> header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n<29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n<30> token_length = len(self._peer_token)\n<31> header_size += size_uint_var(token_length) + token_length\n<32> else:\n<33> header_size = 3 + len(self._peer_cid)\n<34> \n<35> # check we have enough space\n<36> if packet_start + header_size >= self._buffer_capacity:\n<37> raise QuicPacketBuilderStop\n<38> \n<39> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n at: aioquic.buffer\n size_uint_var(value: int) -> int\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_MASK = 0xF0\n \n is_long_header(first_byte: int) -> bool\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n QuicPacketBuilderStop(*args: object)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n _flush_current_datagram() -> None\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.max_flight_bytes: Optional[int] = None\n \n self.max_total_bytes: Optional[int] = None\n \n self._host_cid = host_cid\n \n self._peer_cid = peer_cid\n \n self._peer_token = peer_token\n \n self._ack_eliciting = False\n \n self._datagram_init = True\n \n self._flight_bytes = 0\n \n self._total_bytes = 0\n \n self._header_size = 0\n \n self._packet: Optional[QuicSentPacket] = None\n \n self._packet_crypto: Optional[CryptoPair] = None\n \n self._packet_long_header = False\n \n self._packet_number = packet_number\n \n self._packet_start = 0\n \n \n===========unchanged ref 1===========\n self._packet_type = 0\n \n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n self._buffer_capacity = PACKET_MAX_SIZE\n \n at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram\n self._datagram_init = True\n \n self._flight_bytes += datagram_bytes\n \n self._total_bytes += datagram_bytes\n \n at: aioquic.packet_builder.QuicPacketBuilder.end_packet\n self._packet_number += 1\n \n self._packet = None\n \n at: aioquic.packet_builder.QuicPacketBuilder.start_frame\n self._ack_eliciting = True\n \n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n packet_type: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.tls\n Epoch()\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n "}}},{"rowIdx":3066,"cells":{"path":{"kind":"string","value":"tests.test_recovery/QuicPacketRecoveryTest.test_on_packet_lost_crypto"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":" <6>: packet_type=PACKET_TYPE_INITIAL,\n"},"main_code":{"kind":"string","value":" # module: tests.test_recovery\n class QuicPacketRecoveryTest(TestCase):\n def test_on_packet_lost_crypto(self):\n <0> packet = QuicSentPacket(\n <1> epoch=tls.Epoch.INITIAL,\n <2> in_flight=True,\n <3> is_ack_eliciting=True,\n <4> is_crypto_packet=True,\n <5> packet_number=0,\n <6> sent_bytes=1280,\n <7> sent_time=123.45,\n <8> )\n <9> space = self.INITIAL_SPACE\n<10> \n<11> self.recovery.on_packet_sent(packet, space)\n<12> self.assertEqual(self.recovery.bytes_in_flight, 1280)\n<13> self.assertEqual(space.ack_eliciting_in_flight, 1)\n<14> self.assertEqual(len(space.sent_packets), 1)\n<15> \n<16> self.recovery.on_packet_lost(packet, space)\n<17> self.assertEqual(self.recovery.bytes_in_flight, 0)\n<18> self.assertEqual(space.ack_eliciting_in_flight, 0)\n<19> self.assertEqual(len(space.sent_packets), 0)\n<20> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n packet_type: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.recovery.QuicPacketRecovery\n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n on_packet_sent(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n at: aioquic.recovery.QuicPacketRecovery.__init__\n self.bytes_in_flight = 0\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_acked\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_expired\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_lost\n self.bytes_in_flight -= packet.sent_bytes\n \n at: aioquic.recovery.QuicPacketRecovery.on_packet_sent\n self.bytes_in_flight += packet.sent_bytes\n \n \n===========unchanged ref 1===========\n at: aioquic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: aioquic.tls\n Epoch()\n \n at: tests.test_recovery.QuicPacketRecoveryTest.setUp\n self.INITIAL_SPACE = QuicPacketSpace()\n \n self.recovery = QuicPacketRecovery(\n is_client_without_1rtt=False, send_probe=send_probe\n )\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHA\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n + packet_type=packet_type,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3067,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":"<33>: packet_type=PACKET_TYPE_INITIAL,\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_padding(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> pad_first_datagram=True,\n <4> peer_cid=bytes(8),\n <5> peer_token=b\"\",\n <6> spin_bit=False,\n <7> version=QuicProtocolVersion.DRAFT_20,\n <8> )\n <9> crypto = CryptoPair()\n<10> crypto.setup_initial(bytes(8), is_client=True)\n<11> \n<12> # INITIAL, fully padded\n<13> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<14> self.assertEqual(builder.remaining_space, 1236)\n<15> builder.start_frame(QuicFrameType.CRYPTO)\n<16> builder.buffer.push_bytes(bytes(100))\n<17> self.assertTrue(builder.end_packet())\n<18> self.assertEqual(builder.buffer.tell(), 1280)\n<19> \n<20> # check datagrams\n<21> datagrams, packets = builder.flush()\n<22> self.assertEqual(len(datagrams), 1)\n<23> self.assertEqual(len(datagrams[0]), 1280)\n<24> self.assertEqual(\n<25> packets,\n<26> [\n<27> QuicSentPacket(\n<28> epoch=Epoch.INITIAL,\n<29> in_flight=True,\n<30> is_ack_eliciting=True,\n<31> is_crypto_packet=True,\n<32> packet_number=0,\n<33> sent_bytes=1280,\n<34> )\n<35> ],\n<36> )\n<37> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n packet_type: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHA\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n + packet_type=packet_type,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n===========changed ref 3===========\n # module: tests.test_recovery\n class QuicPacketRecoveryTest(TestCase):\n def test_on_packet_lost_crypto(self):\n packet = QuicSentPacket(\n epoch=tls.Epoch.INITIAL,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=0,\n + packet_type=PACKET_TYPE_INITIAL,\n sent_bytes=1280,\n sent_time=123.45,\n )\n space = self.INITIAL_SPACE\n \n self.recovery.on_packet_sent(packet, space)\n self.assertEqual(self.recovery.bytes_in_flight, 1280)\n self.assertEqual(space.ack_eliciting_in_flight, 1)\n self.assertEqual(len(space.sent_packets), 1)\n \n self.recovery.on_packet_lost(packet, space)\n self.assertEqual(self.recovery.bytes_in_flight, 0)\n self.assertEqual(space.ack_eliciting_in_flight, 0)\n self.assertEqual(len(space.sent_packets), 0)\n "}}},{"rowIdx":3068,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_short_header(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> crypto.setup_initial(bytes(8), is_client=True)\n<10> \n<11> # INITIAL, fully padded\n<12> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<13> self.assertEqual(builder.remaining_space, 1236)\n<14> builder.start_frame(QuicFrameType.CRYPTO)\n<15> builder.buffer.push_bytes(bytes(builder.remaining_space))\n<16> self.assertTrue(builder.end_packet())\n<17> self.assertEqual(builder.buffer.tell(), 1280)\n<18> \n<19> # ONE_RTT, fully padded\n<20> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)\n<21> self.assertEqual(builder.remaining_space, 1253)\n<22> builder.start_frame(QuicFrameType.STREAM_BASE)\n<23> builder.buffer.push_bytes(bytes(builder.remaining_space))\n<24> self.assertTrue(builder.end_packet())\n<25> self.assertEqual(builder.buffer.tell(), 0)\n<26> \n<27> # check datagrams\n<28> datagrams, packets = builder.flush()\n<29> self.assertEqual(len(datagrams), 2)\n<30> self.assertEqual(len(datagrams[0]), 1280)\n<31> self.assertEqual(len(datagrams[1]), 1280)\n<32> self.assertEqual(\n<33> packets,\n<34> [\n<35> QuicSentPacket(\n<36> epoch=Epoch.INITIAL,\n<37> in_flight=True,\n<38> is_ack_eliciting=True,"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_short_header(self):\n # offset: 1\n packet_number=0,\n sent_bytes=1280,\n ),\n QuicSentPacket(\n epoch=Epoch.ONE_RTT,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=False,\n packet_number=1,\n sent_bytes=1280,\n ),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHA\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n + packet_type=packet_type,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3069,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_long_header(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> crypto.setup_initial(bytes(8), is_client=True)\n<10> \n<11> # INITIAL\n<12> builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n<13> self.assertEqual(builder.remaining_space, 1236)\n<14> builder.start_frame(QuicFrameType.CRYPTO)\n<15> builder.buffer.push_bytes(bytes(199))\n<16> self.assertEqual(builder.buffer.tell(), 228)\n<17> self.assertTrue(builder.end_packet())\n<18> self.assertEqual(builder.buffer.tell(), 244)\n<19> \n<20> # HANDSHAKE\n<21> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto)\n<22> self.assertEqual(builder.buffer.tell(), 271)\n<23> self.assertEqual(builder.remaining_space, 993)\n<24> builder.start_frame(QuicFrameType.CRYPTO)\n<25> builder.buffer.push_bytes(bytes(299))\n<26> self.assertEqual(builder.buffer.tell(), 571)\n<27> self.assertTrue(builder.end_packet())\n<28> self.assertEqual(builder.buffer.tell(), 587)\n<29> \n<30> # ONE_RTT\n<31> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)\n<32> self.assertEqual(builder.remaining_space, 666)\n<33> builder.start_frame(QuicFrameType.CRYPTO)\n<34> builder.buffer.push_bytes(bytes(299))\n<35> self.assertTrue(builder.end_packet())\n<36> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_then_long_header(self):\n # offset: 1\n \n # check datagrams\n datagrams, packets = builder.flush()\n self.assertEqual(len(datagrams), 1)\n self.assertEqual(len(datagrams[0]), 914)\n self.assertEqual(\n packets,\n [\n QuicSentPacket(\n epoch=Epoch.INITIAL,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=0,\n sent_bytes=244,\n ),\n QuicSentPacket(\n epoch=Epoch.HANDSHAKE,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=1,\n sent_bytes=343,\n ),\n QuicSentPacket(\n epoch=Epoch.ONE_RTT,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=2,\n sent_bytes=327,\n ),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00\n \n PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20\n \n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n \n===========unchanged ref 1===========\n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n at: aioquic.tls\n Epoch()\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHA\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n + packet_type=packet_type,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n "}}},{"rowIdx":3070,"cells":{"path":{"kind":"string","value":"tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_padding"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6372da7c3d7c88a9293d6069f4dd94b604346b95"},"commit_message":{"kind":"string","value":"[packet builder] keep track of the packet type"},"ground_truth":{"kind":"string","value":"<35>: packet_type=PACKET_TYPE_ONE_RTT,\n"},"main_code":{"kind":"string","value":" # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_short_header_padding(self):\n <0> builder = QuicPacketBuilder(\n <1> host_cid=bytes(8),\n <2> packet_number=0,\n <3> peer_cid=bytes(8),\n <4> peer_token=b\"\",\n <5> spin_bit=False,\n <6> version=QuicProtocolVersion.DRAFT_20,\n <7> )\n <8> crypto = CryptoPair()\n <9> crypto.setup_initial(bytes(8), is_client=True)\n<10> \n<11> # ONE_RTT, fully padded\n<12> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)\n<13> self.assertEqual(builder.remaining_space, 1253)\n<14> builder.start_frame(QuicFrameType.CRYPTO)\n<15> builder.buffer.push_bytes(bytes(builder.remaining_space))\n<16> self.assertTrue(builder.end_packet())\n<17> \n<18> # check builder\n<19> self.assertEqual(builder.buffer.tell(), 0)\n<20> self.assertEqual(builder.packet_number, 1)\n<21> \n<22> # check datagrams\n<23> datagrams, packets = builder.flush()\n<24> self.assertEqual(len(datagrams), 1)\n<25> self.assertEqual(len(datagrams[0]), 1280)\n<26> self.assertEqual(\n<27> packets,\n<28> [\n<29> QuicSentPacket(\n<30> epoch=Epoch.ONE_RTT,\n<31> in_flight=True,\n<32> is_ack_eliciting=True,\n<33> is_crypto_packet=True,\n<34> packet_number=0,\n<35> sent_bytes=1280,\n<36> )\n<37> ],\n<38> )\n<39> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer.Buffer\n tell() -> int\n \n push_bytes(value: bytes) -> None\n \n at: aioquic.crypto\n CryptoPair()\n \n at: aioquic.crypto.CryptoPair\n setup_initial(cid: bytes, is_client: bool) -> None\n \n at: aioquic.packet\n PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT\n \n QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int)\n QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n QuicFrameType(x: Union[str, bytes, bytearray], base: int)\n \n at: aioquic.packet_builder\n 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(\n default_factory=list\n ))\n \n QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b\"\", spin_bit: bool=False)\n \n at: aioquic.packet_builder.QuicPacketBuilder\n flush() -> Tuple[List[bytes], List[QuicSentPacket]]\n \n start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None\n \n start_packet(packet_type: int, crypto: CryptoPair) -> None\n \n end_packet() -> bool\n \n at: aioquic.packet_builder.QuicPacketBuilder.__init__\n self.buffer = Buffer(PACKET_MAX_SIZE)\n \n \n===========unchanged ref 1===========\n at: aioquic.tls\n Epoch()\n \n at: tests.test_packet_builder.QuicPacketBuilderTest.test_short_header_empty\n builder = QuicPacketBuilder(\n host_cid=bytes(8),\n packet_number=0,\n peer_cid=bytes(8),\n peer_token=b\"\",\n spin_bit=False,\n version=QuicProtocolVersion.DRAFT_20,\n )\n \n at: unittest.case.TestCase\n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.packet_builder\n @dataclass\n class QuicSentPacket:\n epoch: Epoch\n in_flight: bool\n is_ack_eliciting: bool\n is_crypto_packet: bool\n packet_number: int\n + packet_type: int\n sent_time: Optional[float] = None\n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n===========changed ref 1===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n \"\"\"\n Starts a new packet.\n \"\"\"\n buf = self.buffer\n self._ack_eliciting = False\n \n # if there is too little space remaining, start a new datagram\n # FIXME: the limit is arbitrary!\n packet_start = buf.tell()\n if self._buffer_capacity - packet_start < 128:\n self._flush_current_datagram()\n packet_start = 0\n \n # initialize datagram if needed\n if self._datagram_init:\n if self.max_flight_bytes is not None:\n remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes\n if remaining_flight_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_flight_bytes\n if self.max_total_bytes is not None:\n remaining_total_bytes = self.max_total_bytes - self._total_bytes\n if remaining_total_bytes < self._buffer_capacity:\n self._buffer_capacity = remaining_total_bytes\n self._datagram_init = False\n \n # calculate header size\n packet_long_header = is_long_header(packet_type)\n if packet_long_header:\n header_size = 11 + len(self._peer_cid) + len(self._host_cid)\n if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL:\n token_length = len(self._peer_token)\n header_size += size_uint_var(token_length) + token_length\n else:\n header_size = 3 + len(self._peer_cid)\n \n # check we have enough space\n if packet_start + header_size >= self._buffer_capacity:\n raise QuicPacketBuilderStop\n \n # determine ack epoch\n if packet_type == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHA\n===========changed ref 2===========\n # module: aioquic.packet_builder\n class QuicPacketBuilder:\n def start_packet(self, packet_type: int, crypto: CryptoPair) -> None:\n # offset: 1\n == PACKET_TYPE_INITIAL:\n epoch = Epoch.INITIAL\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n epoch = Epoch.HANDSHAKE\n else:\n epoch = Epoch.ONE_RTT\n \n self._header_size = header_size\n self._packet = QuicSentPacket(\n epoch=epoch,\n in_flight=False,\n is_ack_eliciting=False,\n is_crypto_packet=False,\n packet_number=self._packet_number,\n + packet_type=packet_type,\n )\n self._packet_crypto = crypto\n self._packet_long_header = packet_long_header\n self._packet_start = packet_start\n self._packet_type = packet_type\n \n buf.seek(self._packet_start + self._header_size)\n \n===========changed ref 3===========\n # module: tests.test_packet_builder\n class QuicPacketBuilderTest(TestCase):\n def test_long_header_padding(self):\n builder = QuicPacketBuilder(\n host_cid=bytes(8),\n packet_number=0,\n pad_first_datagram=True,\n peer_cid=bytes(8),\n peer_token=b\"\",\n spin_bit=False,\n version=QuicProtocolVersion.DRAFT_20,\n )\n crypto = CryptoPair()\n crypto.setup_initial(bytes(8), is_client=True)\n \n # INITIAL, fully padded\n builder.start_packet(PACKET_TYPE_INITIAL, crypto)\n self.assertEqual(builder.remaining_space, 1236)\n builder.start_frame(QuicFrameType.CRYPTO)\n builder.buffer.push_bytes(bytes(100))\n self.assertTrue(builder.end_packet())\n self.assertEqual(builder.buffer.tell(), 1280)\n \n # check datagrams\n datagrams, packets = builder.flush()\n self.assertEqual(len(datagrams), 1)\n self.assertEqual(len(datagrams[0]), 1280)\n self.assertEqual(\n packets,\n [\n QuicSentPacket(\n epoch=Epoch.INITIAL,\n in_flight=True,\n is_ack_eliciting=True,\n is_crypto_packet=True,\n packet_number=0,\n + packet_type=PACKET_TYPE_INITIAL,\n sent_bytes=1280,\n )\n ],\n )\n "}}},{"rowIdx":3071,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"90c4cb26b181cfe614e91e0218a5c8f1b80c62bd"},"commit_message":{"kind":"string","value":"[http3] add support for blocked streams"},"ground_truth":{"kind":"string","value":" <7>: self._stream_blocked: Set[int] = set()\n <8>: self._stream_ended: Set[int] = set()\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n <0> self._max_table_capacity = 0x100\n <1> self._blocked_streams = 0x10\n <2> \n <3> self._is_client = quic.configuration.is_client\n <4> self._quic = quic\n <5> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n <6> self._encoder = Encoder()\n <7> self._stream_buffers: Dict[int, bytes] = {}\n <8> self._stream_types: Dict[int, int] = {}\n <9> \n<10> self._local_control_stream_id: Optional[int] = None\n<11> self._local_decoder_stream_id: Optional[int] = None\n<12> self._local_encoder_stream_id: Optional[int] = None\n<13> \n<14> self._peer_control_stream_id: Optional[int] = None\n<15> self._peer_decoder_stream_id: Optional[int] = None\n<16> self._peer_encoder_stream_id: Optional[int] = None\n<17> \n<18> self._init_connection()\n<19> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL)\n \n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.connection.H3Connection._receive_stream_data\n self._peer_control_stream_id = stream_id\n \n self._peer_decoder_stream_id = stream_id\n \n self._peer_encoder_stream_id = stream_id\n \n at: typing\n Set = _alias(set, 1, inst=False, name='Set')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":3072,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"90c4cb26b181cfe614e91e0218a5c8f1b80c62bd"},"commit_message":{"kind":"string","value":"[http3] add support for blocked streams"},"ground_truth":{"kind":"string","value":" <6>: if stream_ended:\n self._stream_ended.add(stream_id)\n if stream_id in self._stream_blocked:\n return http_events\n <9>: unblocked_streams: Set[int] = set()\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> \n <7> buf = Buffer(data=self._stream_buffers[stream_id])\n <8> consumed = 0\n <9> \n<10> # some peers (e.g. f5) end the stream with no data\n<11> if stream_ended and buf.eof() and (stream_id % 4 == 0):\n<12> http_events.append(\n<13> DataReceived(data=b\"\", stream_id=stream_id, stream_ended=True)\n<14> )\n<15> \n<16> while not buf.eof():\n<17> # fetch stream type for unidirectional streams\n<18> if (\n<19> stream_is_unidirectional(stream_id)\n<20> and stream_id not in self._stream_types\n<21> ):\n<22> try:\n<23> stream_type = buf.pull_uint_var()\n<24> except BufferReadError:\n<25> break\n<26> consumed = buf.tell()\n<27> \n<28> if stream_type == StreamType.CONTROL:\n<29> assert self._peer_control_stream_id is None\n<30> self._peer_control_stream_id = stream_id\n<31> elif stream_type == StreamType.QPACK_DECODER:\n<32> assert self._peer_decoder_stream_id is None\n<33> self._peer_decoder_stream_id = stream_id\n<34> elif stream_type == StreamType.QPACK_ENCODER:\n<35> assert self._peer_encoder_stream_id is None\n<36> self._peer_encoder_stream_id = stream_id\n<37> self._stream_types[stream_id] = stream_type\n<38> \n<39> if (stream_id % 4 == 0) or stream_id"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n # fetch next frame\n try:\n frame_type = buf.pull_uint_var()\n frame_length = buf.pull_uint_var()\n frame_data = buf.pull_bytes(frame_length)\n except BufferReadError:\n break\n consumed = buf.tell()\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n decoder, headers = self._decoder.feed_header(\n stream_id, frame_data\n )\n self._quic.send_stream_data(\n self._local_decoder_stream_id, decoder\n )\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n encoder = self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(\n Setting.QPACK_BLOCKED_STREAMS, 0\n ),\n )\n self._quic.send_stream_data(\n self._local_encoder_stream_id, encoder\n )\n else:\n \n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 2\n ic.send_stream_data(\n self._local_encoder_stream_id, encoder\n )\n else:\n # fetch unframed data\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n \n if stream_id == self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id == self._peer_encoder_stream_id:\n self._decoder.feed_encoder(data)\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n return http_events\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._quic = quic\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream_blocked: Set[int] = set()\n \n self._stream_buffers: Dict[int, bytes] = {}\n \n self._stream_ended: Set[int] = set()\n \n self._stream_types: Dict[int, int] = {}\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._local_encoder_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n self._peer_encoder_stream_id: Optional[int] = None\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n Set = _alias(set, 1, inst=False, name='Set')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n + self._stream_blocked: Set[int] = set()\n self._stream_buffers: Dict[int, bytes] = {}\n + self._stream_ended: Set[int] = set()\n self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n \n self._init_connection()\n "}}},{"rowIdx":3073,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_fragmented_frame"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"90c4cb26b181cfe614e91e0218a5c8f1b80c62bd"},"commit_message":{"kind":"string","value":"[http3] add support for blocked streams"},"ground_truth":{"kind":"string","value":" <0>: class FakeQuicConnection:\n <1>: def __init__(self, configuration):\n <2>: self.configuration = configuration\n <3>: self.stream_queue = []\n <4>: self._next_stream_bidi = 0 if configuration.is_client else 2\n <5>: self._next_stream_uni = 1 if configuration.is_client else 3\n <6>: \n <7>: def get_next_available_stream_id(self, is_unidirectional=False):\n <8>: if is_unidirectional:\n <9>: stream_id = self._next_stream_uni\n<10>: self._next_stream_uni += 4\n<11>: else:\n<12>: stream_id = self._next_stream_bidi\n<13>: self._next_stream_bidi += 4\n<14>: return stream_id\n<15>: \n<16>: def send_stream_data(self, stream_id, data, end_stream=False):\n<17>: # chop up data into individual bytes\n<18>: for c in data:\n<19>: self.stream_queue.append(\n<20>: StreamDataReceived(\n<21>: data=bytes([c]), end_stream=False, stream_id=stream_id\n<22>: )\n<23>: )\n<24>: if end_stream:\n<25>: self.stream_queue.append(\n<26>: StreamDataReceived(\n<27>: data=b\"\", end_stream=end_stream, stream_id=stream_id\n<28>: )\n<29>: )\n<30>: \n"},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_fragmented_frame(self):\n <0> class FakeQuicConnection:\n <1> def __init__(self, configuration):\n <2> self.configuration = configuration\n <3> self.stream_queue = []\n <4> self._next_stream_bidi = 0 if configuration.is_client else 2\n <5> self._next_stream_uni = 1 if configuration.is_client else 3\n <6> \n <7> def get_next_available_stream_id(self, is_unidirectional=False):\n <8> if is_unidirectional:\n <9> stream_id = self._next_stream_uni\n<10> self._next_stream_uni += 4\n<11> else:\n<12> stream_id = self._next_stream_bidi\n<13> self._next_stream_bidi += 4\n<14> return stream_id\n<15> \n<16> def send_stream_data(self, stream_id, data, end_stream=False):\n<17> # chop up data into individual bytes\n<18> for c in data:\n<19> self.stream_queue.append(\n<20> StreamDataReceived(\n<21> data=bytes([c]), end_stream=False, stream_id=stream_id\n<22> )\n<23> )\n<24> if end_stream:\n<25> self.stream_queue.append(\n<26> StreamDataReceived(\n<27> data=b\"\", end_stream=end_stream, stream_id=stream_id\n<28> )\n<29> )\n<30> \n<31> quic_client = FakeQuicConnection(\n<32> configuration=QuicConfiguration(is_client=True)\n<33> )\n<34> quic_server = FakeQuicConnection(\n<35> configuration=QuicConfiguration(is_client=False)\n<36> )\n<37> \n<38> h3_client = H3Connection(quic_client)\n<39> h3_server = H3Connection(quic_server)\n<40> \n<41> # send headers\n<42> stream_id = quic_client.get_next_available_stream_id()\n<43> h3_client.send_headers(\n "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_fragmented_frame(self):\n # offset: 1\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n (b\"x-foo\", b\"client\"),\n ],\n )\n http_events = []\n for event in quic_client.stream_queue:\n http_events.extend(h3_server.handle_event(event))\n quic_client.stream_queue.clear()\n self.assertEqual(\n http_events,\n [\n RequestReceived(\n headers=[\n (b\":method\", b\"GET\"),\n (b\":scheme\", b\"https\"),\n (b\":authority\", b\"localhost\"),\n (b\":path\", b\"/\"),\n (b\"x-foo\", b\"client\"),\n ],\n stream_id=0,\n stream_ended=False,\n )\n ],\n )\n \n # send body\n h3_client.send_data(stream_id=stream_id, data=b\"hello\", end_stream=True)\n http_events = []\n for event in quic_client.stream_queue:\n http_events.extend(h3_server.handle_event(event))\n quic_client.stream_queue.clear()\n self.assertEqual(\n http_events,\n [\n DataReceived(data=b\"hello\", stream_id=0, stream_ended=False),\n DataReceived(data=b\"\", stream_id=0, stream_ended=True),\n ],\n )\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n \n===========unchanged ref 1===========\n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n FakeQuicConnection(configuration)\n \n at: tests.test_h3.FakeQuicConnection\n get_next_available_stream_id(is_unidirectional=False)\n \n at: tests.test_h3.FakeQuicConnection.__init__\n self.stream_queue = []\n \n at: tests.test_h3.H3ConnectionTest\n _make_request(h3_client, h3_server)\n \n at: tests.test_h3.H3ConnectionTest._make_request\n stream_id = quic_client.get_next_available_stream_id()\n \n events = h3_transfer(quic_server, h3_client)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n assertTrue(expr: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def get_next_available_stream_id(self, is_unidirectional=False):\n + if is_unidirectional:\n + stream_id = self._next_stream_uni\n + self._next_stream_uni += 4\n + else:\n + stream_id = self._next_stream_bidi\n + self._next_stream_bidi += 4\n + return stream_id\n + \n===========changed ref 1===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def __init__(self, configuration):\n + self.configuration = configuration\n + self.stream_queue = []\n + self._next_stream_bidi = 0 if configuration.is_client else 2\n + self._next_stream_uni = 1 if configuration.is_client else 3\n + \n===========changed ref 2===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def send_stream_data(self, stream_id, data, end_stream=False):\n + # chop up data into individual bytes\n + for c in data:\n + self.stream_queue.append(\n + StreamDataReceived(\n + data=bytes([c]), end_stream=False, stream_id=stream_id\n + )\n + )\n + if end_stream:\n + self.stream_queue.append(\n + StreamDataReceived(data=b\"\", end_stream=end_stream, stream_id=stream_id)\n + )\n + \n===========changed ref 3===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n + self._stream_blocked: Set[int] = set()\n self._stream_buffers: Dict[int, bytes] = {}\n + self._stream_ended: Set[int] = set()\n self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n \n self._init_connection()\n "}}},{"rowIdx":3074,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"90c4cb26b181cfe614e91e0218a5c8f1b80c62bd"},"commit_message":{"kind":"string","value":"[http3] add support for blocked streams"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n<18> is_client=True,\n<19> server_name=server_name,\n<20> **kwargs\n<21> ),\n<22> session_ticket_handler=save_session_ticket,\n<23> )\n<24> quic.connect(server_addr, now=time.time())\n<25> \n<26> # send request\n<27> http: HttpConnection\n<28> if legacy_http:\n<29> http = H0Connection(quic)\n<30> else:\n<31> http = H3Connection(quic)\n<32> stream_id = quic.get_next_available_stream_id()\n<33> http.send_headers(\n<34> stream_id=stream_id,\n<35> headers=[\n<36> (b\":method\", b\"GET\"),\n<37> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<38> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<39> (b\":path\", parsed.path.encode(\"utf8\")),\n<40> (b\"user-agent\", b\"aioquic\"),\n<41> ],\n<42> )\n<43> http.send_data(stream_id=stream_id, data"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n if isinstance(http_event, ResponseReceived):\n stream_ended = http_event.stream_ended\n headers = b\"\"\n for k, v in http_event.headers:\n headers += k + b\": \" + v + b\"\\r\\n\"\n if headers:\n sys.stderr.buffer.write(headers + b\"\\r\\n\")\n if isinstance(http_event, DataReceived):\n stream_ended = http_event.stream_ended\n sys.stdout.buffer.write(http_event.data)\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: aioquic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[tls.SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.connection.QuicConnection\n close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str=\"\") -> None\n \n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n \n===========unchanged ref 1===========\n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n save_session_ticket(ticket)\n \n at: socket\n AF_INET: AddressFamily\n \n SOCK_DGRAM: SocketKind\n \n socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...)\n \n gethostbyname(hostname: str) -> str\n \n at: socket.socket\n family: int\n \n type: int\n \n proto: int\n \n recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress]\n \n sendto(data: bytes, address: _Address) -> int\n sendto(data: bytes, flags: int, address: _Address) -> int\n \n at: sys\n stdout: TextIO\n \n stderr: TextIO\n \n at: time\n time() -> float\n \n at: typing.BinaryIO\n __slots__ = ()\n \n \n===========unchanged ref 2===========\n write(s: AnyStr) -> int\n \n at: typing.IO\n __slots__ = ()\n \n flush() -> None\n \n at: typing.TextIO\n __slots__ = ()\n \n at: urllib.parse\n urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult\n urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes\n \n \n===========changed ref 0===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def __init__(self, configuration):\n + self.configuration = configuration\n + self.stream_queue = []\n + self._next_stream_bidi = 0 if configuration.is_client else 2\n + self._next_stream_uni = 1 if configuration.is_client else 3\n + \n===========changed ref 1===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def get_next_available_stream_id(self, is_unidirectional=False):\n + if is_unidirectional:\n + stream_id = self._next_stream_uni\n + self._next_stream_uni += 4\n + else:\n + stream_id = self._next_stream_bidi\n + self._next_stream_bidi += 4\n + return stream_id\n + \n===========changed ref 2===========\n # module: tests.test_h3\n + class FakeQuicConnection:\n + def send_stream_data(self, stream_id, data, end_stream=False):\n + # chop up data into individual bytes\n + for c in data:\n + self.stream_queue.append(\n + StreamDataReceived(\n + data=bytes([c]), end_stream=False, stream_id=stream_id\n + )\n + )\n + if end_stream:\n + self.stream_queue.append(\n + StreamDataReceived(data=b\"\", end_stream=end_stream, stream_id=stream_id)\n + )\n + "}}},{"rowIdx":3075,"cells":{"path":{"kind":"string","value":"aioquic.h0.connection/H0Connection.handle_event"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d01c68649c57e02e4343a86bc401d5beb0405de2"},"commit_message":{"kind":"string","value":"[quic] move quic code to aioquic.quic"},"ground_truth":{"kind":"string","value":" <3>: isinstance(event, aioquic.quic.events.StreamDataReceived)\n isinstance(event, aioquic.events.StreamDataReceived)\n"},"main_code":{"kind":"string","value":" # module: aioquic.h0.connection\n class H0Connection:\n + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if (\n <3> isinstance(event, aioquic.events.StreamDataReceived)\n <4> and (event.stream_id % 4) == 0\n <5> ):\n <6> data = event.data\n <7> if not self._headers_received.get(event.stream_id, False):\n <8> if self._is_client:\n <9> http_events.append(\n<10> ResponseReceived(\n<11> headers=[], stream_ended=False, stream_id=event.stream_id\n<12> )\n<13> )\n<14> else:\n<15> method, path = data.rstrip().split(b\" \", 1)\n<16> http_events.append(\n<17> RequestReceived(\n<18> headers=[(b\":method\", method), (b\":path\", path)],\n<19> stream_ended=False,\n<20> stream_id=event.stream_id,\n<21> )\n<22> )\n<23> data = b\"\"\n<24> self._headers_received[event.stream_id] = True\n<25> \n<26> http_events.append(\n<27> DataReceived(\n<28> data=data, stream_ended=event.end_stream, stream_id=event.stream_id\n<29> )\n<30> )\n<31> \n<32> return http_events\n<33> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.events\n Event()\n \n StreamDataReceived(data: bytes, end_stream: bool, stream_id: int)\n \n at: aioquic.h0.connection.H0Connection.__init__\n self._headers_received: Dict[int, bool] = {}\n \n self._is_client = quic.configuration.is_client\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n \n===========changed ref 0===========\n + # module: aioquic.quic.retry\n + \n + \n===========changed ref 1===========\n + # module: aioquic.quic\n + \n + \n===========changed ref 2===========\n + # module: aioquic.quic.connection\n + \n + \n===========changed ref 3===========\n + # module: aioquic.quic.configuration\n + \n + \n===========changed ref 4===========\n + # module: aioquic.quic.stream\n + \n + \n===========changed ref 5===========\n + # module: aioquic.quic.packet_builder\n + \n + \n===========changed ref 6===========\n + # module: aioquic.quic.crypto\n + \n + \n===========changed ref 7===========\n + # module: aioquic.quic.packet\n + \n + \n===========changed ref 8===========\n + # module: aioquic.quic.rangeset\n + \n + \n===========changed ref 9===========\n + # module: aioquic.quic.packet_builder\n + class QuicPacketBuilderStop(Exception):\n + pass\n + \n===========changed ref 10===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __bool__(self) -> bool:\n + raise NotImplementedError\n + \n===========changed ref 11===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + @property\n + def configuration(self) -> QuicConfiguration:\n + return self._configuration\n + \n===========changed ref 12===========\n + # module: aioquic.quic.stream\n + class QuicStream:\n + @property\n + def stream_id(self) -> Optional[int]:\n + return self.__stream_id\n + \n===========changed ref 13===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def _send_probe(self) -> None:\n + self._probe_pending = True\n + \n===========changed ref 14===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __len__(self) -> int:\n + return len(self.__ranges)\n + \n===========changed ref 15===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __getitem__(self, key: Any) -> range:\n + return self.__ranges[key]\n + \n===========changed ref 16===========\n + # module: aioquic.quic.crypto\n + class CryptoContext:\n + def is_valid(self) -> bool:\n + return self.aead is not None\n + \n===========changed ref 17===========\n + # module: aioquic.quic.crypto\n + class CryptoPair:\n + def update_key(self) -> None:\n + self._update_key_requested = True\n + \n===========changed ref 18===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def shift(self) -> range:\n + return self.__ranges.pop(0)\n + \n===========changed ref 19===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + \"\"\"\n + A QUIC connection.\n + \"\"\"\n + \n===========changed ref 20===========\n + # module: aioquic.quic.connection\n + def dump_cid(cid: bytes) -> str:\n + return binascii.hexlify(cid).decode(\"ascii\")\n + \n===========changed ref 21===========\n + # module: aioquic.quic.recovery\n + # TODO : collapse congestion window if persistent congestion\n + \n===========changed ref 22===========\n + # module: aioquic.quic.recovery\n + class QuicPacketRecovery:\n + def on_packet_expired(self, packet: QuicSentPacket) -> None:\n + self.bytes_in_flight -= packet.sent_bytes\n + \n===========changed ref 23===========\n + # module: aioquic.quic.packet_builder\n + class QuicPacketBuilder:\n + \"\"\"\n + Helper for building QUIC packets.\n + \"\"\"\n + \n===========changed ref 24===========\n + # module: aioquic.quic.recovery\n + class QuicPacketRecovery:\n + \"\"\"\n + Packet loss and congestion controller.\n + \"\"\"\n + \n===========changed ref 25===========\n + # module: aioquic.quic.packet\n + def is_long_header(first_byte: int) -> bool:\n + return bool(first_byte & PACKET_LONG_HEADER)\n + \n===========changed ref 26===========\n + # module: aioquic.quic.packet\n + def get_spin_bit(first_byte: int) -> bool:\n + return bool(first_byte & PACKET_SPIN_BIT)\n + \n===========changed ref 27===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __repr__(self) -> str:\n + return \"RangeSet({})\".format(repr(self.__ranges))\n + \n===========changed ref 28===========\n + # module: aioquic.quic.packet_builder\n + class QuicDeliveryState(Enum):\n + ACKED = 0\n + LOST = 1\n + EXPIRED = 2\n + \n===========changed ref 29===========\n + # module: aioquic.quic.crypto\n + class CryptoPair:\n + def teardown(self) -> None:\n + self.recv.teardown()\n + self.send.teardown()\n + \n===========changed ref 30===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def _handle_padding_frame(\n + self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n + ) -> None:\n + \"\"\"\n + Handle a PADDING or PING frame.\n + \"\"\"\n + pass\n + \n===========changed ref 31===========\n + # module: aioquic.quic.connection\n + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]:\n + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut)\n + \n===========changed ref 32===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def bounds(self) -> range:\n + return range(self.__ranges[0].start, self.__ranges[-1].stop)\n + \n===========changed ref 33===========\n + # module: aioquic.quic.packet\n + @dataclass\n + class QuicStreamFrame:\n + data: bytes = b\"\"\n + fin: bool = False\n + offset: int = 0\n + \n===========changed ref 34===========\n + # module: aioquic.quic.connection\n + class QuicConnectionAdapter(logging.LoggerAdapter):\n + def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:\n + return \"[%s] %s\" % (self.extra[\"host_cid\"], msg), kwargs\n + \n===========changed ref 35===========\n + # module: aioquic.quic.packet\n + def pull_new_token_frame(buf: Buffer) -> bytes:\n + length = buf.pull_uint_var()\n + return buf.pull_bytes(length)\n + \n===========changed ref 36===========\n + # module: aioquic.quic.packet\n + def push_new_token_frame(buf: Buffer, token: bytes) -> None:\n + buf.push_uint_var(len(token))\n + buf.push_bytes(token)\n + \n===========changed ref 37===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __contains__(self, val: Any) -> bool:\n + for r in self.__ranges:\n + if val in r:\n + return True\n + return False\n + "}}},{"rowIdx":3076,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.handle_event"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d01c68649c57e02e4343a86bc401d5beb0405de2"},"commit_message":{"kind":"string","value":"[quic] move quic code to aioquic.quic"},"ground_truth":{"kind":"string","value":" <5>: if isinstance(event, aioquic.quic.events.StreamDataReceived):\n if isinstance(event, aioquic.events.StreamDataReceived):\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n <0> \"\"\"\n <1> Handle a QUIC event and return a list of HTTP events.\n <2> \"\"\"\n <3> http_events: List[Event] = []\n <4> \n <5> if isinstance(event, aioquic.events.StreamDataReceived):\n <6> http_events.extend(\n <7> self._receive_stream_data(event.stream_id, event.data, event.end_stream)\n <8> )\n <9> \n<10> return http_events\n<11> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection.H3Connection\n _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event]\n \n at: aioquic.h3.events\n Event()\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n + # module: aioquic.quic.events\n + \n + \n===========changed ref 1===========\n + # module: aioquic.quic.retry\n + \n + \n===========changed ref 2===========\n + # module: aioquic.quic\n + \n + \n===========changed ref 3===========\n + # module: aioquic.quic.connection\n + \n + \n===========changed ref 4===========\n + # module: aioquic.quic.configuration\n + \n + \n===========changed ref 5===========\n + # module: aioquic.quic.stream\n + \n + \n===========changed ref 6===========\n + # module: aioquic.quic.packet_builder\n + \n + \n===========changed ref 7===========\n + # module: aioquic.quic.crypto\n + \n + \n===========changed ref 8===========\n + # module: aioquic.quic.packet\n + \n + \n===========changed ref 9===========\n + # module: aioquic.quic.rangeset\n + \n + \n===========changed ref 10===========\n + # module: aioquic.quic.packet_builder\n + class QuicPacketBuilderStop(Exception):\n + pass\n + \n===========changed ref 11===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __bool__(self) -> bool:\n + raise NotImplementedError\n + \n===========changed ref 12===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + @property\n + def configuration(self) -> QuicConfiguration:\n + return self._configuration\n + \n===========changed ref 13===========\n + # module: aioquic.quic.events\n + @dataclass\n + class ConnectionIdRetired(Event):\n + connection_id: bytes\n + \n===========changed ref 14===========\n + # module: aioquic.quic.events\n + @dataclass\n + class ConnectionIdIssued(Event):\n + connection_id: bytes\n + \n===========changed ref 15===========\n + # module: aioquic.quic.stream\n + class QuicStream:\n + @property\n + def stream_id(self) -> Optional[int]:\n + return self.__stream_id\n + \n===========changed ref 16===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def _send_probe(self) -> None:\n + self._probe_pending = True\n + \n===========changed ref 17===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __len__(self) -> int:\n + return len(self.__ranges)\n + \n===========changed ref 18===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __getitem__(self, key: Any) -> range:\n + return self.__ranges[key]\n + \n===========changed ref 19===========\n + # module: aioquic.quic.crypto\n + class CryptoContext:\n + def is_valid(self) -> bool:\n + return self.aead is not None\n + \n===========changed ref 20===========\n + # module: aioquic.quic.crypto\n + class CryptoPair:\n + def update_key(self) -> None:\n + self._update_key_requested = True\n + \n===========changed ref 21===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def shift(self) -> range:\n + return self.__ranges.pop(0)\n + \n===========changed ref 22===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + \"\"\"\n + A QUIC connection.\n + \"\"\"\n + \n===========changed ref 23===========\n + # module: aioquic.quic.connection\n + def dump_cid(cid: bytes) -> str:\n + return binascii.hexlify(cid).decode(\"ascii\")\n + \n===========changed ref 24===========\n + # module: aioquic.quic.recovery\n + # TODO : collapse congestion window if persistent congestion\n + \n===========changed ref 25===========\n + # module: aioquic.quic.recovery\n + class QuicPacketRecovery:\n + def on_packet_expired(self, packet: QuicSentPacket) -> None:\n + self.bytes_in_flight -= packet.sent_bytes\n + \n===========changed ref 26===========\n + # module: aioquic.quic.packet_builder\n + class QuicPacketBuilder:\n + \"\"\"\n + Helper for building QUIC packets.\n + \"\"\"\n + \n===========changed ref 27===========\n + # module: aioquic.quic.recovery\n + class QuicPacketRecovery:\n + \"\"\"\n + Packet loss and congestion controller.\n + \"\"\"\n + \n===========changed ref 28===========\n + # module: aioquic.quic.packet\n + def is_long_header(first_byte: int) -> bool:\n + return bool(first_byte & PACKET_LONG_HEADER)\n + \n===========changed ref 29===========\n + # module: aioquic.quic.packet\n + def get_spin_bit(first_byte: int) -> bool:\n + return bool(first_byte & PACKET_SPIN_BIT)\n + \n===========changed ref 30===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __repr__(self) -> str:\n + return \"RangeSet({})\".format(repr(self.__ranges))\n + \n===========changed ref 31===========\n + # module: aioquic.quic.packet_builder\n + class QuicDeliveryState(Enum):\n + ACKED = 0\n + LOST = 1\n + EXPIRED = 2\n + \n===========changed ref 32===========\n + # module: aioquic.quic.crypto\n + class CryptoPair:\n + def teardown(self) -> None:\n + self.recv.teardown()\n + self.send.teardown()\n + \n===========changed ref 33===========\n + # module: aioquic.quic.events\n + class Event:\n + \"\"\"\n + Base class for QUIC events.\n + \"\"\"\n + \n + pass\n + \n===========changed ref 34===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def _handle_padding_frame(\n + self, context: QuicReceiveContext, frame_type: int, buf: Buffer\n + ) -> None:\n + \"\"\"\n + Handle a PADDING or PING frame.\n + \"\"\"\n + pass\n + \n===========changed ref 35===========\n + # module: aioquic.quic.connection\n + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]:\n + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut)\n + \n===========changed ref 36===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def bounds(self) -> range:\n + return range(self.__ranges[0].start, self.__ranges[-1].stop)\n + \n===========changed ref 37===========\n + # module: aioquic.quic.packet\n + @dataclass\n + class QuicStreamFrame:\n + data: bytes = b\"\"\n + fin: bool = False\n + offset: int = 0\n + \n===========changed ref 38===========\n + # module: aioquic.quic.connection\n + class QuicConnectionAdapter(logging.LoggerAdapter):\n + def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:\n + return \"[%s] %s\" % (self.extra[\"host_cid\"], msg), kwargs\n + \n===========changed ref 39===========\n + # module: aioquic.quic.packet\n + def pull_new_token_frame(buf: Buffer) -> bytes:\n + length = buf.pull_uint_var()\n + return buf.pull_bytes(length)\n + \n===========changed ref 40===========\n + # module: aioquic.quic.packet\n + def push_new_token_frame(buf: Buffer, token: bytes) -> None:\n + buf.push_uint_var(len(token))\n + buf.push_bytes(token)\n + \n===========changed ref 41===========\n + # module: aioquic.quic.rangeset\n + class RangeSet(Sequence):\n + def __contains__(self, val: Any) -> bool:\n + for r in self.__ranges:\n + if val in r:\n + return True\n + return False\n + \n===========changed ref 42===========\n + # module: aioquic.quic.packet_builder\n + class QuicPacketBuilder:\n + @property\n + def packet_number(self) -> int:\n + \"\"\"\n + Returns the packet number for the next packet.\n + \"\"\"\n + return self._packet_number\n + \n===========changed ref 43===========\n + # module: aioquic.quic.packet\n + def decode_reason_phrase(reason_bytes: bytes) -> str:\n + try:\n + return reason_bytes.decode(\"utf8\")\n + except UnicodeDecodeError:\n + return \"\"\n + "}}},{"rowIdx":3077,"cells":{"path":{"kind":"string","value":"examples.http3-server/HttpServer._consume_events"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"d01c68649c57e02e4343a86bc401d5beb0405de2"},"commit_message":{"kind":"string","value":"[quic] move quic code to aioquic.quic"},"ground_truth":{"kind":"string","value":" <3>: if isinstance(event, aioquic.quic.events.ConnectionTerminated):\n if isinstance(event, aioquic.events.ConnectionTerminated):\n<11>: elif isinstance(event, aioquic.quic.events.ProtocolNegotiated):\n elif isinstance(event, aioquic.events.ProtocolNegotiated):\n<16>: elif isinstance(event, aioquic.quic.events.ConnectionIdIssued):\n elif isinstance(event, aioquic.events.ConnectionIdIssued):\n<18>: elif isinstance(event, aioquic.quic.events.ConnectionIdRetired):\n elif isinstance(event, aioquic.events.ConnectionIdRetired):\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n <0> # process events\n <1> event = connection.next_event()\n <2> while event is not None:\n <3> if isinstance(event, aioquic.events.ConnectionTerminated):\n <4> # remove the connection\n <5> for cid, conn in list(self._connections.items()):\n <6> if conn == connection:\n <7> del self._connections[cid]\n <8> self._http.pop(connection, None)\n <9> self._timer.pop(connection, None)\n<10> return\n<11> elif isinstance(event, aioquic.events.ProtocolNegotiated):\n<12> if event.alpn_protocol == \"h3-22\":\n<13> self._http[connection] = H3Connection(connection)\n<14> elif event.alpn_protocol == \"hq-22\":\n<15> self._http[connection] = H0Connection(connection)\n<16> elif isinstance(event, aioquic.events.ConnectionIdIssued):\n<17> self._connections[event.connection_id] = connection\n<18> elif isinstance(event, aioquic.events.ConnectionIdRetired):\n<19> assert self._connections[event.connection_id] == connection\n<20> del self._connections[event.connection_id]\n<21> \n<22> #  pass event to the HTTP layer\n<23> http = self._http.get(connection)\n<24> if http is not None:\n<25> for http_event in http.handle_event(event):\n<26> handle_http_event(http, http_event)\n<27> \n<28> event = connection.next_event()\n<29> \n<30> # send datagrams\n<31> for data, addr in connection.datagrams_to_send(now=self._loop.time()):\n<32> self._transport.sendto(data, addr)\n<33> \n<34> # re-arm timer\n<35> next_timer_at = connection.get_timer()\n<36> (timer, timer_at) = self._timer.get(connection, (None, None))\n<37> if timer is not None and"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-server\n class HttpServer(asyncio.DatagramProtocol):\n def _consume_events(self, connection: QuicConnection) -> None:\n # offset: 1\n timer.cancel()\n timer = None\n if timer is None and timer_at is not None:\n timer = self._loop.call_at(\n next_timer_at, partial(self._handle_timer, connection)\n )\n self._timer[connection] = (timer, next_timer_at)\n \n \n===========unchanged ref 0===========\n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.quic.events.Event) -> List[Event]\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.quic.events.Event) -> List[Event]\n \n at: aioquic.quic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.quic.connection.QuicConnection\n datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]]\n \n get_timer() -> Optional[float]\n \n next_event() -> Optional[events.Event]\n \n at: asyncio.events.AbstractEventLoop\n call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle\n \n time() -> float\n \n at: asyncio.events.TimerHandle\n __slots__ = ['_scheduled', '_when']\n \n cancel() -> None\n \n at: asyncio.transports.DatagramTransport\n __slots__ = ()\n \n sendto(data: Any, addr: Optional[_Address]=...) -> None\n \n at: examples.http3-server\n handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None\n \n at: examples.http3-server.HttpServer\n _handle_timer(connection: QuicConnection) -> None\n \n at: examples.http3-server.HttpServer.__init__\n self._connections: Dict[bytes, QuicConnection] = {}\n \n self._http: Dict[QuicConnection, HttpConnection] = {}\n \n \n===========unchanged ref 1===========\n self._loop = asyncio.get_event_loop()\n \n self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {}\n \n self._transport: Optional[asyncio.DatagramTransport] = None\n \n at: examples.http3-server.HttpServer.connection_made\n self._transport = cast(asyncio.DatagramTransport, transport)\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + \"\"\"\n + A QUIC connection.\n + \"\"\"\n + \n===========changed ref 1===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def next_event(self) -> Optional[events.Event]:\n + \"\"\"\n + Retrieve the next event from the event buffer.\n + \n + Returns `None` if there are no buffered events.\n + \"\"\"\n + try:\n + return self._events.popleft()\n + except IndexError:\n + return None\n + \n===========changed ref 2===========\n # module: aioquic.h3.connection\n class H3Connection:\n + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n \"\"\"\n Handle a QUIC event and return a list of HTTP events.\n \"\"\"\n http_events: List[Event] = []\n \n + if isinstance(event, aioquic.quic.events.StreamDataReceived):\n - if isinstance(event, aioquic.events.StreamDataReceived):\n http_events.extend(\n self._receive_stream_data(event.stream_id, event.data, event.end_stream)\n )\n \n return http_events\n \n===========changed ref 3===========\n + # module: aioquic.quic.connection\n + class QuicConnection:\n + def get_timer(self) -> Optional[float]:\n + \"\"\"\n + Return the time at which the timer should fire or None if no timer is needed.\n + \"\"\"\n + timer_at = self._close_at\n + if self._state not in END_STATES:\n + # ack timer\n + for space in self._loss.spaces:\n + if space.ack_at is not None and space.ack_at < timer_at:\n + timer_at = space.ack_at\n + \n + # loss detection timer\n + self._loss_at = self._loss.get_loss_detection_time()\n + if self._loss_at is not None and self._loss_at < timer_at:\n + timer_at = self._loss_at\n + return timer_at\n + \n===========changed ref 4===========\n # module: aioquic.h0.connection\n class H0Connection:\n + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]:\n - def handle_event(self, event: aioquic.events.Event) -> List[Event]:\n http_events: List[Event] = []\n \n if (\n + isinstance(event, aioquic.quic.events.StreamDataReceived)\n - isinstance(event, aioquic.events.StreamDataReceived)\n and (event.stream_id % 4) == 0\n ):\n data = event.data\n if not self._headers_received.get(event.stream_id, False):\n if self._is_client:\n http_events.append(\n ResponseReceived(\n headers=[], stream_ended=False, stream_id=event.stream_id\n )\n )\n else:\n method, path = data.rstrip().split(b\" \", 1)\n http_events.append(\n RequestReceived(\n headers=[(b\":method\", method), (b\":path\", path)],\n stream_ended=False,\n stream_id=event.stream_id,\n )\n )\n data = b\"\"\n self._headers_received[event.stream_id] = True\n \n http_events.append(\n DataReceived(\n data=data, stream_ended=event.end_stream, stream_id=event.stream_id\n )\n )\n \n return http_events\n "}}},{"rowIdx":3078,"cells":{"path":{"kind":"string","value":"examples.interop/test_version_negotiation"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6b1303b581bb4d9f18b2caad7d95268af271d7e5"},"commit_message":{"kind":"string","value":"[interop] separate stateless retry test from the rest"},"ground_truth":{"kind":"string","value":" <3>: await connection.ping()\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_version_negotiation(config, **kwargs):\n <0> async with connect(\n <1> config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs\n <2> ) as connection:\n <3> if connection._connection._version_negotiation_count == 1:\n <4> config.result |= Result.V\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n \n===========changed ref 0===========\n # module: examples.interop\n @dataclass\n class Config:\n name: str\n host: str\n port: int\n + retry_port: Optional[int]\n path: str\n result: Result = field(default_factory=lambda: Result(0))\n \n===========changed ref 1===========\n # module: examples.interop\n CONFIGS = [\n + Config(\"aioquic\", \"quic.aiortc.org\", 4433, 4434, \"/\"),\n - Config(\"aioquic\", \"quic.aiortc.org\", 4434, \"/\"),\n + Config(\"ats\", \"quic.ogre.com\", 4433, 4434, \"/\"),\n - Config(\"ats\", \"quic.ogre.com\", 4434, \"/\"),\n + Config(\"f5\", \"f5quic.com\", 4433, 4433, \"/\"),\n - Config(\"f5\", \"f5quic.com\", 4433, \"/\"),\n + Config(\"gquic\", \"quic.rocks\", 4433, 4433, \"/\"),\n - Config(\"gquic\", \"quic.rocks\", 4433, \"/\"),\n + Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4433, 4434, None),\n - Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4434, None),\n + Config(\"mvfst\", \"fb.mvfst.net\", 4433, 4434, \"/\"),\n - Config(\"mvfst\", \"fb.mvfst.net\", 4433, \"/\"),\n + Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, None),\n - Config(\"ngtcp2\", \"nghttp2.org\", 4434, None),\n + Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, 443, None),\n - Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, None),\n + Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, 4434, \"/\"),\n - Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, \"/\"),\n + Config(\"picoquic\", \"test.privateoctopus.com\", 4433, 4434, \"/\"),\n - Config(\"picoquic\", \"test.privateoctopus.com\", 4434\n===========changed ref 2===========\n # module: examples.interop\n # offset: 1\n 4433, 4434, \"/\"),\n - Config(\"picoquic\", \"test.privateoctopus.com\", 4434, \"/\"),\n + Config(\"quant\", \"quant.eggert.org\", 4433, 4434, \"/\"),\n - Config(\"quant\", \"quant.eggert.org\", 4434, \"/\"),\n + Config(\"quic-go\", \"quic.seemann.io\", 443, 443, \"/\"),\n - Config(\"quic-go\", \"quic.seemann.io\", 443, \"/\"),\n + Config(\"quiche\", \"quic.tech\", 4433, 4433, \"/\"),\n - Config(\"quiche\", \"quic.tech\", 4433, \"/\"),\n + Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, None, \"/\"),\n - Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, \"/\"),\n + Config(\"quicly\", \"kazuhooku.com\", 4433, 4434, \"/\"),\n - Config(\"quicly\", \"kazuhooku.com\", 4434, \"/\"),\n + Config(\"quinn\", \"ralith.com\", 4433, 4434, \"/\"),\n - Config(\"quinn\", \"ralith.com\", 4433, \"/\"),\n + Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4433, 4434, \"/\"),\n - Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4434, \"/\"),\n ]\n "}}},{"rowIdx":3079,"cells":{"path":{"kind":"string","value":"examples.interop/test_handshake_and_close"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"6b1303b581bb4d9f18b2caad7d95268af271d7e5"},"commit_message":{"kind":"string","value":"[interop] separate stateless retry test from the rest"},"ground_truth":{"kind":"string","value":" <1>: await connection.ping()\n <2>: if connection._connection._stateless_retry_count == 1:\n <3>: config.result |= Result.S\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_handshake_and_close(config, **kwargs):\n <0> async with connect(config.host, config.port, **kwargs) as connection:\n <1> config.result |= Result.H\n <2> if connection._connection._stateless_retry_count == 1:\n <3> config.result |= Result.S\n <4> config.result |= Result.C\n <5> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n ping() -> None\n \n at: examples.interop\n Result()\n \n \n===========changed ref 0===========\n # module: examples.interop\n def test_version_negotiation(config, **kwargs):\n async with connect(\n config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs\n ) as connection:\n + await connection.ping()\n if connection._connection._version_negotiation_count == 1:\n config.result |= Result.V\n \n===========changed ref 1===========\n # module: examples.interop\n @dataclass\n class Config:\n name: str\n host: str\n port: int\n + retry_port: Optional[int]\n path: str\n result: Result = field(default_factory=lambda: Result(0))\n \n===========changed ref 2===========\n # module: examples.interop\n CONFIGS = [\n + Config(\"aioquic\", \"quic.aiortc.org\", 4433, 4434, \"/\"),\n - Config(\"aioquic\", \"quic.aiortc.org\", 4434, \"/\"),\n + Config(\"ats\", \"quic.ogre.com\", 4433, 4434, \"/\"),\n - Config(\"ats\", \"quic.ogre.com\", 4434, \"/\"),\n + Config(\"f5\", \"f5quic.com\", 4433, 4433, \"/\"),\n - Config(\"f5\", \"f5quic.com\", 4433, \"/\"),\n + Config(\"gquic\", \"quic.rocks\", 4433, 4433, \"/\"),\n - Config(\"gquic\", \"quic.rocks\", 4433, \"/\"),\n + Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4433, 4434, None),\n - Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4434, None),\n + Config(\"mvfst\", \"fb.mvfst.net\", 4433, 4434, \"/\"),\n - Config(\"mvfst\", \"fb.mvfst.net\", 4433, \"/\"),\n + Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, None),\n - Config(\"ngtcp2\", \"nghttp2.org\", 4434, None),\n + Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, 443, None),\n - Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, None),\n + Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, 4434, \"/\"),\n - Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, \"/\"),\n + Config(\"picoquic\", \"test.privateoctopus.com\", 4433, 4434, \"/\"),\n - Config(\"picoquic\", \"test.privateoctopus.com\", 4434\n===========changed ref 3===========\n # module: examples.interop\n # offset: 1\n 4433, 4434, \"/\"),\n - Config(\"picoquic\", \"test.privateoctopus.com\", 4434, \"/\"),\n + Config(\"quant\", \"quant.eggert.org\", 4433, 4434, \"/\"),\n - Config(\"quant\", \"quant.eggert.org\", 4434, \"/\"),\n + Config(\"quic-go\", \"quic.seemann.io\", 443, 443, \"/\"),\n - Config(\"quic-go\", \"quic.seemann.io\", 443, \"/\"),\n + Config(\"quiche\", \"quic.tech\", 4433, 4433, \"/\"),\n - Config(\"quiche\", \"quic.tech\", 4433, \"/\"),\n + Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, None, \"/\"),\n - Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, \"/\"),\n + Config(\"quicly\", \"kazuhooku.com\", 4433, 4434, \"/\"),\n - Config(\"quicly\", \"kazuhooku.com\", 4434, \"/\"),\n + Config(\"quinn\", \"ralith.com\", 4433, 4434, \"/\"),\n - Config(\"quinn\", \"ralith.com\", 4433, \"/\"),\n + Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4433, 4434, \"/\"),\n - Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4434, \"/\"),\n ]\n "}}},{"rowIdx":3080,"cells":{"path":{"kind":"string","value":"examples.http3-client/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"659aaff67ea8b508400ea580d9a0d43e0fdce7ec"},"commit_message":{"kind":"string","value":"[examples] make http3 client example use asyncio"},"ground_truth":{"kind":"string","value":"<10>: # lookup remote address\n infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM)\n server_addr = infos[0][4]\n if len(server_addr) == 2:\n server_addr = (\"::ffff:\" + server_addr[0], server_addr[1], 0, 0)\n # prepare socket\n<11>: server_addr = (socket.gethostbyname(server_name), port)\n<12>: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<15>: _, client = await loop.create_datagram_endpoint(\n lambda: HttpClient(\n quic = QuicConnection(\n<16>: configuration=QuicConfiguration(\n configuration=QuicConfiguration(\n<17>: alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n<18>: is_client=True,\n is_client=True,\n<19>: server_name=server_name,\n server_name=server_name,\n<20>: **kwargs\n **kwargs\n<21>: ),\n server_addr=server_addr,\n session_ticket_handler=save_session_ticket,\n<22>: local_addr=(\"::\", 0),\n session_ticket_handler=save_session_ticket,\n<24>: client ="},"main_code":{"kind":"string","value":" # module: examples.http3-client\n + def run(url: str, legacy_http: bool, **kwargs) -> None:\n - def run(url: str, legacy_http: bool, **kwargs) -> None:\n <0> # parse URL\n <1> parsed = urlparse(url)\n <2> assert parsed.scheme == \"https\", \"Only HTTPS URLs are supported.\"\n <3> if \":\" in parsed.netloc:\n <4> server_name, port_str = parsed.netloc.split(\":\")\n <5> port = int(port_str)\n <6> else:\n <7> server_name = parsed.netloc\n <8> port = 443\n <9> \n<10> # prepare socket\n<11> server_addr = (socket.gethostbyname(server_name), port)\n<12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n<13> \n<14> # prepare QUIC connection\n<15> quic = QuicConnection(\n<16> configuration=QuicConfiguration(\n<17> alpn_protocols=[\"hq-22\" if legacy_http else \"h3-22\"],\n<18> is_client=True,\n<19> server_name=server_name,\n<20> **kwargs\n<21> ),\n<22> session_ticket_handler=save_session_ticket,\n<23> )\n<24> quic.connect(server_addr, now=time.time())\n<25> \n<26> # send request\n<27> http: HttpConnection\n<28> if legacy_http:\n<29> http = H0Connection(quic)\n<30> else:\n<31> http = H3Connection(quic)\n<32> stream_id = quic.get_next_available_stream_id()\n<33> http.send_headers(\n<34> stream_id=stream_id,\n<35> headers=[\n<36> (b\":method\", b\"GET\"),\n<37> (b\":scheme\", parsed.scheme.encode(\"utf8\")),\n<38> (b\":authority\", parsed.netloc.encode(\"utf8\")),\n<39> (b\":path\", parsed.path.encode(\"utf8\")),\n<40> (b\"user-agent\", b\"aioquic\"),\n<41> ],"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: examples.http3-client\n + def run(url: str, legacy_http: bool, **kwargs) -> None:\n - def run(url: str, legacy_http: bool, **kwargs) -> None:\n # offset: 1\n http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # handle events\n stream_ended = False\n while not stream_ended:\n data, addr = sock.recvfrom(2048)\n quic.receive_datagram(data, addr, now=time.time())\n \n # process events\n event = quic.next_event()\n while event is not None:\n for http_event in http.handle_event(event):\n if isinstance(http_event, ResponseReceived):\n stream_ended = http_event.stream_ended\n headers = b\"\"\n for k, v in http_event.headers:\n headers += k + b\": \" + v + b\"\\r\\n\"\n if headers:\n sys.stderr.buffer.write(headers + b\"\\r\\n\")\n sys.stderr.buffer.flush()\n if isinstance(http_event, DataReceived):\n stream_ended = http_event.stream_ended\n sys.stdout.buffer.write(http_event.data)\n event = quic.next_event()\n \n # send datagrams\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n # close connection\n quic.close()\n for data, addr in quic.datagrams_to_send(now=time.time()):\n sock.sendto(data, addr)\n \n \n===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: _asyncio.Future\n set_result(result, /)\n \n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h0.connection.H0Connection\n handle_event(event: aioquic.quic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None\n \n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection\n handle_event(event: aioquic.quic.events.Event) -> List[Event]\n \n send_data(stream_id: int, data: bytes, end_stream: bool) -> None\n \n send_headers(stream_id: int, headers: Headers) -> None\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.quic.connection\n NetworkAddress = Any\n \n \n===========unchanged ref 1===========\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.quic.connection.QuicConnection\n close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str=\"\") -> None\n \n connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None\n \n get_next_available_stream_id(is_unidirectional=False) -> int\n \n next_event() -> Optional[events.Event]\n \n receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None\n \n at: aioquic.quic.events\n ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str)\n \n at: asyncio.events\n TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...)\n \n get_event_loop() -> AbstractEventLoop\n \n at: asyncio.events.AbstractEventLoop\n time() -> float\n \n create_future() -> Future[Any]\n \n at: asyncio.futures\n Future(*, loop: Optional[AbstractEventLoop]=...)\n Future = _CFuture = _asyncio.Future\n \n at: asyncio.futures.Future\n _state = _PENDING\n \n _result = None\n \n _exception = None\n \n _loop = None\n \n _source_traceback = None\n \n _cancel_message = None\n \n _cancelled_exc = None\n \n _asyncio_future_blocking = False\n \n __log_traceback = False\n \n __class_getitem__ = classmethod(GenericAlias)\n \n set_result(result: _T, /) -> None\n \n __iter__ = __await__ # make compatible with 'yield from'.\n \n \n===========unchanged ref 2===========\n at: asyncio.locks\n Event(*, loop: Optional[AbstractEventLoop]=...)\n \n at: asyncio.locks.Event\n wait() -> bool\n \n at: asyncio.protocols.BaseProtocol\n __slots__ = ()\n \n connection_made(self, transport: transports.BaseTransport) -> None\n \n at: asyncio.protocols.DatagramProtocol\n __slots__ = ()\n \n datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None\n \n at: asyncio.tasks\n shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T]\n \n at: asyncio.transports\n BaseTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n DatagramTransport(extra: Optional[Mapping[Any, Any]]=...)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n at: examples.http3-client.HttpClient._consume_events\n self._timer = self._loop.call_at(timer_at, self._handle_timer)\n self._timer = None\n \n self._timer_at = timer_at\n \n at: examples.http3-client.HttpClient._handle_timer\n self._timer = None\n \n self._timer_at = None\n \n at: typing\n cast(typ: Type[_T], val: Any) -> _T\n cast(typ: str, val: Any) -> Any\n cast(typ: object, val: Any) -> Any\n \n List = _alias(list, 1, inst=False, name='List')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n Text = str\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n "}}},{"rowIdx":3081,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_client_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"3ad2650f57fbc13f539606b2d0b55be7c39eefdc"},"commit_message":{"kind":"string","value":"[tls] don't fail if presented with unsupported cipher suites"},"ground_truth":{"kind":"string","value":" <8>: cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> client_random = buf.pull_bytes(32)\n <4> \n <5> hello = ClientHello(\n <6> random=client_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n <9> compression_methods=pull_list(\n<10> buf, 1, partial(pull_compression_method, buf)\n<11> ),\n<12> )\n<13> \n<14> # extensions\n<15> after_psk = False\n<16> \n<17> def pull_extension() -> None:\n<18> # pre_shared_key MUST be last\n<19> nonlocal after_psk\n<20> assert not after_psk\n<21> \n<22> extension_type = buf.pull_uint16()\n<23> extension_length = buf.pull_uint16()\n<24> if extension_type == ExtensionType.KEY_SHARE:\n<25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n<26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n<28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n<29> hello.signature_algorithms = pull_list(\n<30> buf, 2, partial(pull_signature_algorithm, buf)\n<31> )\n<32> elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n<33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n<34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n<35> hello.psk_key_exchange_modes = pull_list(\n<36> buf, 1, partial(pull_psk_key_exchange_mode"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n )\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n pull_uint8() -> int\n \n pull_uint16() -> int\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_compression_method(buf: Buffer) -> CompressionMethod\n \n pull_group(buf: Buffer) -> Group\n \n pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode\n \n pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm\n \n pull_block(buf: Buffer, capacity: int) -> Generator\n \n pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n pull_key_share(buf: Buffer) -> KeyShareEntry\n \n pull_alpn_protocol(buf: Buffer) -> str\n \n pull_psk_identity(buf: Buffer) -> PskIdentity\n \n pull_psk_binder(buf: Buffer) -> bytes\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n \n===========unchanged ref 1===========\n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n at: aioquic.tls.ClientHello\n random: bytes\n \n session_id: bytes\n \n cipher_suites: List[int]\n \n compression_methods: List[CompressionMethod]\n \n alpn_protocols: Optional[List[str]] = None\n \n early_data: bool = False\n \n key_share: Optional[List[KeyShareEntry]] = None\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n \n server_name: Optional[str] = None\n \n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n \n supported_groups: Optional[List[Group]] = None\n \n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n at: aioquic.tls.OfferedPsks\n identities: List[PskIdentity]\n \n binders: List[bytes]\n \n at: functools\n partial(func: Callable[..., _T], *args: Any, **kwargs: Any)\n partial(func, *args, **keywords, /) -> function with partial application()\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n + cipher_suites: List[int]\n - cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_cipher_suite(buf: Buffer) -> CipherSuite:\n - return CipherSuite(buf.pull_uint16())\n - "}}},{"rowIdx":3082,"cells":{"path":{"kind":"string","value":"aioquic.tls/pull_server_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"3ad2650f57fbc13f539606b2d0b55be7c39eefdc"},"commit_message":{"kind":"string","value":"[tls] don't fail if presented with unsupported cipher suites"},"ground_truth":{"kind":"string","value":" <8>: cipher_suite=buf.pull_uint16(),\n cipher_suite=pull_cipher_suite(buf),\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n <1> with pull_block(buf, 3):\n <2> assert buf.pull_uint16() == TLS_VERSION_1_2\n <3> server_random = buf.pull_bytes(32)\n <4> \n <5> hello = ServerHello(\n <6> random=server_random,\n <7> session_id=pull_opaque(buf, 1),\n <8> cipher_suite=pull_cipher_suite(buf),\n <9> compression_method=pull_compression_method(buf),\n<10> )\n<11> \n<12> # extensions\n<13> def pull_extension() -> None:\n<14> extension_type = buf.pull_uint16()\n<15> extension_length = buf.pull_uint16()\n<16> if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n<17> hello.supported_version = buf.pull_uint16()\n<18> elif extension_type == ExtensionType.KEY_SHARE:\n<19> hello.key_share = pull_key_share(buf)\n<20> elif extension_type == ExtensionType.PRE_SHARED_KEY:\n<21> hello.pre_shared_key = buf.pull_uint16()\n<22> else:\n<23> hello.other_extensions.append(\n<24> (extension_type, buf.pull_bytes(extension_length))\n<25> )\n<26> \n<27> pull_list(buf, 2, pull_extension)\n<28> \n<29> return hello\n<30> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n pull_bytes(length: int) -> bytes\n \n pull_uint16() -> int\n \n at: aioquic.tls\n TLS_VERSION_1_2 = 0x0303\n \n ExtensionType(x: Union[str, bytes, bytearray], base: int)\n ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n pull_compression_method(buf: Buffer) -> CompressionMethod\n \n pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]\n \n pull_opaque(buf: Buffer, capacity: int) -> bytes\n \n pull_key_share(buf: Buffer) -> KeyShareEntry\n \n ServerHello(random: bytes, session_id: bytes, cipher_suite: int, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list))\n \n at: aioquic.tls.ServerHello\n random: bytes\n \n session_id: bytes\n \n cipher_suite: int\n \n compression_method: CompressionMethod\n \n key_share: Optional[KeyShareEntry] = None\n \n pre_shared_key: Optional[int] = None\n \n supported_version: Optional[int] = None\n \n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n + cipher_suite: int\n - cipher_suite: CipherSuite\n compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_cipher_suite(buf: Buffer) -> CipherSuite:\n - return CipherSuite(buf.pull_uint16())\n - \n===========changed ref 2===========\n # module: aioquic.tls\n @dataclass\n class ClientHello:\n random: bytes\n session_id: bytes\n + cipher_suites: List[int]\n - cipher_suites: List[CipherSuite]\n compression_methods: List[CompressionMethod]\n \n # extensions\n alpn_protocols: Optional[List[str]] = None\n early_data: bool = False\n key_share: Optional[List[KeyShareEntry]] = None\n pre_shared_key: Optional[OfferedPsks] = None\n psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None\n server_name: Optional[str] = None\n signature_algorithms: Optional[List[SignatureAlgorithm]] = None\n supported_groups: Optional[List[Group]] = None\n supported_versions: Optional[List[int]] = None\n \n other_extensions: List[Extension] = field(default_factory=list)\n \n===========changed ref 3===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n client_random = buf.pull_bytes(32)\n \n hello = ClientHello(\n random=client_random,\n session_id=pull_opaque(buf, 1),\n + cipher_suites=pull_list(buf, 2, buf.pull_uint16),\n - cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),\n compression_methods=pull_list(\n buf, 1, partial(pull_compression_method, buf)\n ),\n )\n \n # extensions\n after_psk = False\n \n def pull_extension() -> None:\n # pre_shared_key MUST be last\n nonlocal after_psk\n assert not after_psk\n \n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf))\n elif extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_versions = pull_list(buf, 1, buf.pull_uint16)\n elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS:\n hello.signature_algorithms = pull_list(\n buf, 2, partial(pull_signature_algorithm, buf)\n )\n elif extension_type == ExtensionType.SUPPORTED_GROUPS:\n hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf))\n elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES:\n hello.psk_key_exchange_modes = pull_list(\n buf, 1, partial(pull_psk_key_exchange_mode, buf)\n )\n elif extension_type ==\n===========changed ref 4===========\n # module: aioquic.tls\n def pull_client_hello(buf: Buffer) -> ClientHello:\n # offset: 1\n buf, 1, partial(pull_psk_key_exchange_mode, buf)\n )\n elif extension_type == ExtensionType.SERVER_NAME:\n with pull_block(buf, 2):\n assert buf.pull_uint8() == 0\n hello.server_name = pull_opaque(buf, 2).decode(\"ascii\")\n elif extension_type == ExtensionType.ALPN:\n hello.alpn_protocols = pull_list(\n buf, 2, partial(pull_alpn_protocol, buf)\n )\n elif extension_type == ExtensionType.EARLY_DATA:\n hello.early_data = True\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = OfferedPsks(\n identities=pull_list(buf, 2, partial(pull_psk_identity, buf)),\n binders=pull_list(buf, 2, partial(pull_psk_binder, buf)),\n )\n after_psk = True\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n "}}},{"rowIdx":3083,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_send_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"3ad2650f57fbc13f539606b2d0b55be7c39eefdc"},"commit_message":{"kind":"string","value":"[tls] don't fail if presented with unsupported cipher suites"},"ground_truth":{"kind":"string","value":"<20>: cipher_suites=[int(x) for x in self._cipher_suites],\n cipher_suites=self._cipher_suites,\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n <0> key_share: List[KeyShareEntry] = []\n <1> supported_groups: List[Group] = []\n <2> \n <3> if Group.SECP256R1 in self._supported_groups:\n <4> self._ec_private_key = ec.generate_private_key(\n <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n <6> )\n <7> key_share.append(encode_public_key(self._ec_private_key.public_key()))\n <8> supported_groups.append(Group.SECP256R1)\n <9> \n<10> if Group.X25519 in self._supported_groups:\n<11> self._x25519_private_key = x25519.X25519PrivateKey.generate()\n<12> key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n<13> supported_groups.append(Group.X25519)\n<14> \n<15> assert len(key_share), \"no key share entries\"\n<16> \n<17> hello = ClientHello(\n<18> random=self.client_random,\n<19> session_id=self.session_id,\n<20> cipher_suites=self._cipher_suites,\n<21> compression_methods=self._compression_methods,\n<22> alpn_protocols=self.alpn_protocols,\n<23> key_share=key_share,\n<24> psk_key_exchange_modes=self._psk_key_exchange_modes\n<25> if (self.session_ticket or self.new_session_ticket_cb is not None)\n<26> else None,\n<27> server_name=self.server_name,\n<28> signature_algorithms=self._signature_algorithms,\n<29> supported_groups=supported_groups,\n<30> supported_versions=self._supported_versions,\n<31> other_extensions=self.handshake_extensions,\n<32> )\n<33> \n<34> # PSK\n<35> if self.session_ticket and self.session_ticket.is_valid:\n<36> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 1\n self._key_schedule_psk.extract(self.session_ticket.resumption_secret)\n binder_key = self._key_schedule_psk.derive_secret(b\"res binder\")\n binder_length = self._key_schedule_psk.algorithm.digest_size\n \n # update hello\n if self.session_ticket.max_early_data_size is not None:\n hello.early_data = True\n hello.pre_shared_key = OfferedPsks(\n identities=[\n (self.session_ticket.ticket, self.session_ticket.obfuscated_age)\n ],\n binders=[bytes(binder_length)],\n )\n \n # serialize hello without binder\n tmp_buf = Buffer(capacity=1024)\n push_client_hello(tmp_buf, hello)\n \n # calculate binder\n hash_offset = tmp_buf.tell() - binder_length - 3\n self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset))\n binder = self._key_schedule_psk.finished_verify_data(binder_key)\n hello.pre_shared_key.binders[0] = binder\n self._key_schedule_psk.update_hash(\n tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder\n )\n \n # calculate early data key\n if hello.early_data:\n early_key = self._key_schedule_psk.derive_secret(b\"c e traffic\")\n self.update_traffic_key_cb(\n Direction.ENCRYPT,\n Epoch.ZERO_RTT,\n self._key_schedule_psk.cipher_suite,\n early_key,\n )\n \n self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites)\n self._key_schedule_proxy.extract(None)\n===========below chunk 1===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n # offset: 2\n _schedule_proxy = KeyScheduleProxy(hello.cipher_suites)\n self._key_schedule_proxy.extract(None)\n \n with push_message(self._key_schedule_proxy, output_buf):\n push_client_hello(output_buf, hello)\n \n self._set_state(State.CLIENT_EXPECT_SERVER_HELLO)\n \n \n===========unchanged ref 0===========\n at: aioquic._buffer\n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n data_slice(start: int, end: int) -> bytes\n \n tell() -> int\n \n at: aioquic.tls\n Direction()\n \n Epoch()\n \n State()\n \n Group(x: Union[str, bytes, bytearray], base: int)\n Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n OfferedPsks(identities: List[PskIdentity], binders: List[bytes])\n \n ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list))\n \n push_client_hello(buf: Buffer, hello: ClientHello) -> None\n \n pull_server_hello(buf: Buffer) -> ServerHello\n \n KeySchedule(cipher_suite: CipherSuite)\n \n KeyScheduleProxy(cipher_suites: List[CipherSuite])\n \n GROUP_TO_CURVE = {\n Group.SECP256R1: ec.SECP256R1,\n Group.SECP384R1: ec.SECP384R1,\n Group.SECP521R1: ec.SECP521R1,\n }\n \n encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry\n \n \n===========unchanged ref 1===========\n push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator\n \n at: aioquic.tls.ClientHello\n early_data: bool = False\n \n pre_shared_key: Optional[OfferedPsks] = None\n \n at: aioquic.tls.Context\n _set_state(state: State) -> None\n \n at: aioquic.tls.Context.__init__\n self.alpn_protocols: Optional[List[str]] = None\n \n self.handshake_extensions: List[Extension] = []\n \n self.session_ticket: Optional[SessionTicket] = None\n \n self.server_name: Optional[str] = None\n \n self.new_session_ticket_cb: Optional[SessionTicketHandler] = None\n \n self.update_traffic_key_cb: Callable[\n [Direction, Epoch, CipherSuite, bytes], None\n ] = lambda d, e, c, s: None\n \n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n \n self._compression_methods = [CompressionMethod.NULL]\n \n self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE]\n \n self._signature_algorithms = [\n SignatureAlgorithm.RSA_PSS_RSAE_SHA256,\n SignatureAlgorithm.ECDSA_SECP256R1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA256,\n SignatureAlgorithm.RSA_PKCS1_SHA1,\n ]\n \n self._supported_groups = [Group.SECP256R1]\n \n self._supported_versions = [TLS_VERSION_1_3]\n \n self._key_schedule_psk: Optional[KeySchedule] = None\n \n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n \n "}}},{"rowIdx":3084,"cells":{"path":{"kind":"string","value":"aioquic.tls/Context._client_handle_hello"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"3ad2650f57fbc13f539606b2d0b55be7c39eefdc"},"commit_message":{"kind":"string","value":"[tls] don't fail if presented with unsupported cipher suites"},"ground_truth":{"kind":"string","value":" <2>: cipher_suite = negotiate(\n self._cipher_suites,\n [peer_hello.cipher_suite],\n AlertHandshakeFailure(\"Unsupported cipher suite\"),\n )\n assert peer_hello.cipher_suite in self._cipher_suites\n<11>: or cipher_suite != self._key_schedule_psk.cipher_suite\n or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite\n<17>: self.key_schedule = self._key_schedule_proxy.select(cipher_suite)\n self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n"},"main_code":{"kind":"string","value":" # module: aioquic.tls\n class Context:\n def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None:\n <0> peer_hello = pull_server_hello(input_buf)\n <1> \n <2> assert peer_hello.cipher_suite in self._cipher_suites\n <3> assert peer_hello.compression_method in self._compression_methods\n <4> assert peer_hello.supported_version in self._supported_versions\n <5> \n <6> # select key schedule\n <7> if peer_hello.pre_shared_key is not None:\n <8> if (\n <9> self._key_schedule_psk is None\n<10> or peer_hello.pre_shared_key != 0\n<11> or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite\n<12> ):\n<13> raise AlertIllegalParameter\n<14> self.key_schedule = self._key_schedule_psk\n<15> self._session_resumed = True\n<16> else:\n<17> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)\n<18> self._key_schedule_psk = None\n<19> self._key_schedule_proxy = None\n<20> \n<21> # perform key exchange\n<22> peer_public_key = decode_public_key(peer_hello.key_share)\n<23> shared_key: Optional[bytes] = None\n<24> if (\n<25> isinstance(peer_public_key, x25519.X25519PublicKey)\n<26> and self._x25519_private_key is not None\n<27> ):\n<28> shared_key = self._x25519_private_key.exchange(peer_public_key)\n<29> elif (\n<30> isinstance(peer_public_key, ec.EllipticCurvePublicKey)\n<31> and self._ec_private_key is not None\n<32> and self._ec_private_key.public_key().curve.__class__\n<33> == peer_public_key.curve.__class__\n<34> ):\n<35> shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key)\n<36> "},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.tls\n class Context:\n def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None:\n # offset: 1\n \n self.key_schedule.update_hash(input_buf.data)\n self.key_schedule.extract(shared_key)\n \n self._setup_traffic_protection(\n Direction.DECRYPT, Epoch.HANDSHAKE, b\"s hs traffic\"\n )\n \n self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS)\n \n \n===========unchanged ref 0===========\n at: aioquic.tls\n AlertHandshakeFailure(*args: object)\n \n AlertIllegalParameter(*args: object)\n \n Direction()\n \n Epoch()\n \n decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]\n \n negotiate(supported: List[T], offered: Optional[List[Any]], exc: Optional[Alert]=None) -> T\n \n at: aioquic.tls.Context\n _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None\n \n at: aioquic.tls.Context.__init__\n self.key_schedule: Optional[KeySchedule] = None\n \n self._cipher_suites = [\n CipherSuite.AES_256_GCM_SHA384,\n CipherSuite.AES_128_GCM_SHA256,\n CipherSuite.CHACHA20_POLY1305_SHA256,\n ]\n \n self._compression_methods = [CompressionMethod.NULL]\n \n self._supported_versions = [TLS_VERSION_1_3]\n \n self._key_schedule_psk: Optional[KeySchedule] = None\n \n self._key_schedule_proxy: Optional[KeyScheduleProxy] = None\n \n self._session_resumed = False\n \n self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None\n \n self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None\n \n at: aioquic.tls.Context._client_handle_hello\n peer_hello = pull_server_hello(input_buf)\n \n at: aioquic.tls.Context._client_send_hello\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite)\n \n \n===========unchanged ref 1===========\n self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites)\n \n at: aioquic.tls.Context._server_handle_hello\n self.key_schedule = KeySchedule(cipher_suite)\n \n self._session_resumed = True\n \n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n \n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[key_share[0]](), default_backend()\n )\n \n at: aioquic.tls.KeySchedule\n extract(key_material: Optional[bytes]=None) -> None\n \n update_hash(data: bytes) -> None\n \n at: aioquic.tls.KeySchedule.__init__\n self.cipher_suite = cipher_suite\n \n at: aioquic.tls.KeyScheduleProxy\n select(cipher_suite: CipherSuite) -> KeySchedule\n \n at: aioquic.tls.ServerHello\n cipher_suite: int\n \n compression_method: CompressionMethod\n \n key_share: Optional[KeyShareEntry] = None\n \n pre_shared_key: Optional[int] = None\n \n supported_version: Optional[int] = None\n \n \n===========changed ref 0===========\n # module: aioquic.tls\n @dataclass\n class ServerHello:\n random: bytes\n session_id: bytes\n + cipher_suite: int\n - cipher_suite: CipherSuite\n compression_method: CompressionMethod\n \n # extensions\n key_share: Optional[KeyShareEntry] = None\n pre_shared_key: Optional[int] = None\n supported_version: Optional[int] = None\n other_extensions: List[Tuple[int, bytes]] = field(default_factory=list)\n \n===========changed ref 1===========\n # module: aioquic.tls\n - # INTEGERS\n - \n - \n - def pull_cipher_suite(buf: Buffer) -> CipherSuite:\n - return CipherSuite(buf.pull_uint16())\n - \n===========changed ref 2===========\n # module: aioquic.tls\n def pull_server_hello(buf: Buffer) -> ServerHello:\n assert buf.pull_uint8() == HandshakeType.SERVER_HELLO\n with pull_block(buf, 3):\n assert buf.pull_uint16() == TLS_VERSION_1_2\n server_random = buf.pull_bytes(32)\n \n hello = ServerHello(\n random=server_random,\n session_id=pull_opaque(buf, 1),\n + cipher_suite=buf.pull_uint16(),\n - cipher_suite=pull_cipher_suite(buf),\n compression_method=pull_compression_method(buf),\n )\n \n # extensions\n def pull_extension() -> None:\n extension_type = buf.pull_uint16()\n extension_length = buf.pull_uint16()\n if extension_type == ExtensionType.SUPPORTED_VERSIONS:\n hello.supported_version = buf.pull_uint16()\n elif extension_type == ExtensionType.KEY_SHARE:\n hello.key_share = pull_key_share(buf)\n elif extension_type == ExtensionType.PRE_SHARED_KEY:\n hello.pre_shared_key = buf.pull_uint16()\n else:\n hello.other_extensions.append(\n (extension_type, buf.pull_bytes(extension_length))\n )\n \n pull_list(buf, 2, pull_extension)\n \n return hello\n \n===========changed ref 3===========\n # module: aioquic.tls\n class Context:\n def _client_send_hello(self, output_buf: Buffer) -> None:\n key_share: List[KeyShareEntry] = []\n supported_groups: List[Group] = []\n \n if Group.SECP256R1 in self._supported_groups:\n self._ec_private_key = ec.generate_private_key(\n GROUP_TO_CURVE[Group.SECP256R1](), default_backend()\n )\n key_share.append(encode_public_key(self._ec_private_key.public_key()))\n supported_groups.append(Group.SECP256R1)\n \n if Group.X25519 in self._supported_groups:\n self._x25519_private_key = x25519.X25519PrivateKey.generate()\n key_share.append(encode_public_key(self._x25519_private_key.public_key()))\n supported_groups.append(Group.X25519)\n \n assert len(key_share), \"no key share entries\"\n \n hello = ClientHello(\n random=self.client_random,\n session_id=self.session_id,\n + cipher_suites=[int(x) for x in self._cipher_suites],\n - cipher_suites=self._cipher_suites,\n compression_methods=self._compression_methods,\n alpn_protocols=self.alpn_protocols,\n key_share=key_share,\n psk_key_exchange_modes=self._psk_key_exchange_modes\n if (self.session_ticket or self.new_session_ticket_cb is not None)\n else None,\n server_name=self.server_name,\n signature_algorithms=self._signature_algorithms,\n supported_groups=supported_groups,\n supported_versions=self._supported_versions,\n other_extensions=self.handshake_extensions,\n )\n \n # PSK\n if self.session_ticket and self.session_ticket.is_valid:\n self._key_schedule_psk = KeySchedule(self"}}},{"rowIdx":3085,"cells":{"path":{"kind":"string","value":"examples.http3-client/HttpClient.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"727405af8916490c50afe2502ec0096c3123734c"},"commit_message":{"kind":"string","value":"[examples] make HTTP/3 client save session ticket"},"ground_truth":{"kind":"string","value":" <4>: self._quic = QuicConnection(\n configuration=configuration, session_ticket_handler=session_ticket_handler\n )\n self._quic = QuicConnection(configuration=configuration)\n"},"main_code":{"kind":"string","value":" # module: examples.http3-client\n class HttpClient(asyncio.DatagramProtocol):\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n server_addr: NetworkAddress,\n session_ticket_handler: Optional[SessionTicketHandler] = None\n ):\n <0> self._closed = asyncio.Event()\n <1> self._connect_called = False\n <2> self._http: HttpConnection\n <3> self._loop = asyncio.get_event_loop()\n <4> self._quic = QuicConnection(configuration=configuration)\n <5> self._server_addr = server_addr\n <6> self._timer: Optional[asyncio.TimerHandle] = None\n <7> self._timer_at = 0.0\n <8> \n <9> self._request_events: Dict[int, List[Event]] = {}\n<10> self._request_waiter: Dict[int, asyncio.Future[List[Event]]] = {}\n<11> \n<12> if configuration.alpn_protocols[0].startswith(\"hq-\"):\n<13> self._http = H0Connection(self._quic)\n<14> else:\n<15> self._http = H3Connection(self._quic)\n<16> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: _asyncio\n get_event_loop()\n \n at: aioquic.h0.connection\n H0Connection(quic: QuicConnection)\n \n at: aioquic.h3.events\n Event()\n \n at: aioquic.quic.configuration\n QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n ))\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.quic.connection\n NetworkAddress = Any\n \n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: aioquic.tls\n SessionTicketHandler = Callable[[SessionTicket], None]\n \n at: asyncio.events\n TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...)\n \n get_event_loop() -> AbstractEventLoop\n \n \n===========unchanged ref 1===========\n at: asyncio.futures\n Future(*, loop: Optional[AbstractEventLoop]=...)\n Future = _CFuture = _asyncio.Future\n \n at: asyncio.locks\n Event(*, loop: Optional[AbstractEventLoop]=...)\n \n at: examples.http3-client\n HttpConnection = Union[H0Connection, H3Connection]\n \n at: examples.http3-client.HttpClient._consume_events\n self._timer = self._loop.call_at(timer_at, self._handle_timer)\n self._timer = None\n \n self._timer_at = timer_at\n \n at: examples.http3-client.HttpClient._handle_timer\n self._timer = None\n \n self._timer_at = None\n \n at: examples.http3-client.HttpClient.get\n self._connect_called = True\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n "}}},{"rowIdx":3086,"cells":{"path":{"kind":"string","value":"examples.interop/test_session_resumption"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"975975ab854a8e2e0c7d2622377a844aa18ea79f"},"commit_message":{"kind":"string","value":"[interop] rework interop script"},"ground_truth":{"kind":"string","value":"<22>: # check session was resumed\n # check session was resumed\n<23>: if connection._connection.tls.session_resumed:\n if connection._connection.tls.session_resumed:\n<24>: config.result |= Result.R\n config.result |= Result.R\n<26>: # check early data was accepted\n # check early data was accepted\n<27>: if connection._connection.tls.early_data_accepted:\n if connection._connection.tls.early_data_accepted:\n<28>: config.result |= Result.Z\n config.result |= Result.Z\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def test_session_resumption(config, **kwargs):\n <0> saved_ticket = None\n <1> \n <2> def session_ticket_handler(ticket):\n <3> nonlocal saved_ticket\n <4> saved_ticket = ticket\n <5> \n <6> # connect a first time, receive a ticket\n <7> async with connect(\n <8> config.host,\n <9> config.port,\n<10> session_ticket_handler=session_ticket_handler,\n<11> **kwargs\n<12> ) as connection:\n<13> await connection.ping()\n<14> \n<15> # connect a second time, with the ticket\n<16> if saved_ticket is not None:\n<17> async with connect(\n<18> config.host, config.port, session_ticket=saved_ticket, **kwargs\n<19> ) as connection:\n<20> await connection.ping()\n<21> \n<22> # check session was resumed\n<23> if connection._connection.tls.session_resumed:\n<24> config.result |= Result.R\n<25> \n<26> # check early data was accepted\n<27> if connection._connection.tls.early_data_accepted:\n<28> config.result |= Result.Z\n<29> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n ping() -> None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._connection = connection\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._stateless_retry_count = 0\n \n at: aioquic.quic.connection.QuicConnection.receive_datagram\n self._stateless_retry_count += 1\n \n at: examples.interop\n Result()\n \n http_request(connection, path)\n \n http3_request(connection, authority, path)\n \n \n===========changed ref 0===========\n # module: examples.interop\n + def http3_request(connection, authority, path):\n + reader, writer = await connection.create_stream()\n + stream_id = writer.get_extra_info(\"stream_id\")\n + \n + http = H3Connection(connection._connection)\n + http.send_headers(\n + stream_id=stream_id,\n + headers=[\n + (b\":method\", b\"GET\"),\n + (b\":scheme\", b\"https\"),\n + (b\":authority\", authority.encode(\"utf8\")),\n + (b\":path\", path.encode(\"utf8\")),\n + ],\n + )\n + http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n + \n + return await reader.read()\n + \n===========changed ref 1===========\n # module: examples.interop\n class Result(Flag):\n + V = 0x0001\n - V = 1\n + H = 0x0002\n - H = 2\n + D = 0x0004\n - D = 4\n + C = 0x0008\n - C = 8\n + R = 0x0010\n - R = 16\n + Z = 0x0020\n - Z = 32\n + S = 0x0040\n - S = 64\n - # M = 128\n - # B = 256\n - U = 512\n - # 3 = 1024\n + M = 0x0080\n + B = 0x0100\n + U = 0x0200\n + P = 0x0400\n - P = 2048\n + E = 0x0800\n + T = 0x1000\n + three = 0x2000\n + d = 0x4000\n + p = 0x8000\n \n===========changed ref 2===========\n # module: examples.interop\n - def test_data_transfer(config, **kwargs):\n - if config.path is None:\n - return\n - \n - async with connect(config.host, config.port, **kwargs) as connection:\n - response1 = await http_request(connection, config.path)\n - response2 = await http_request(connection, config.path)\n - \n - if response1 and response2:\n - config.result |= Result.D\n - \n===========changed ref 3===========\n # module: examples.interop\n CONFIGS = [\n Config(\"aioquic\", \"quic.aiortc.org\", 4433, 4434, \"/\"),\n Config(\"ats\", \"quic.ogre.com\", 4433, 4434, \"/\"),\n Config(\"f5\", \"f5quic.com\", 4433, 4433, \"/\"),\n Config(\"gquic\", \"quic.rocks\", 4433, 4433, \"/\"),\n Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4433, 4434, None),\n Config(\"mvfst\", \"fb.mvfst.net\", 4433, 4434, \"/\"),\n + Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, \"/\"),\n - Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, None),\n Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, 443, None),\n Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, 4434, \"/\"),\n Config(\"picoquic\", \"test.privateoctopus.com\", 4433, 4434, \"/\"),\n Config(\"quant\", \"quant.eggert.org\", 4433, 4434, \"/\"),\n Config(\"quic-go\", \"quic.seemann.io\", 443, 443, \"/\"),\n Config(\"quiche\", \"quic.tech\", 4433, 4433, \"/\"),\n Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, None, \"/\"),\n Config(\"quicly\", \"kazuhooku.com\", 4433, 4434, \"/\"),\n Config(\"quinn\", \"ralith.com\", 4433, 4434, \"/\"),\n Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4433, 4434, \"/\"),\n ]\n "}}},{"rowIdx":3087,"cells":{"path":{"kind":"string","value":"examples.interop/print_result"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"975975ab854a8e2e0c7d2622377a844aa18ea79f"},"commit_message":{"kind":"string","value":"[interop] rework interop script"},"ground_truth":{"kind":"string","value":" <0>: result = str(config.result).replace(\"three\", \"3\")\n result = result[0:7] + \" \" + result[7:13] + \" \" + result[13:]\n print(\"%s%s%s\" % (config.name, \" \" * (20 - len(config.name)), result))\n print(\"%s%s%s\" % (config.name, \" \" * (20 - len(config.name)), config.result))\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n def print_result(config: Config) -> None:\n <0> print(\"%s%s%s\" % (config.name, \" \" * (20 - len(config.name)), config.result))\n <1> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n ping() -> None\n \n \n===========changed ref 0===========\n # module: examples.interop\n + def test_http_0(config, **kwargs):\n + if config.path is None:\n + return\n + \n + kwargs[\"alpn_protocols\"] = [\"hq-22\"]\n + async with connect(config.host, config.port, **kwargs) as connection:\n + response = await http_request(connection, config.path)\n + if response:\n + config.result |= Result.D\n + \n===========changed ref 1===========\n # module: examples.interop\n + def test_http_3(config, **kwargs):\n + if config.path is None:\n + return\n + \n + kwargs[\"alpn_protocols\"] = [\"h3-22\"]\n + async with connect(config.host, config.port, **kwargs) as connection:\n + response = await http3_request(connection, config.host, config.path)\n + if response:\n + config.result |= Result.D\n + config.result |= Result.three\n + \n===========changed ref 2===========\n # module: examples.interop\n - def test_data_transfer(config, **kwargs):\n - if config.path is None:\n - return\n - \n - async with connect(config.host, config.port, **kwargs) as connection:\n - response1 = await http_request(connection, config.path)\n - response2 = await http_request(connection, config.path)\n - \n - if response1 and response2:\n - config.result |= Result.D\n - \n===========changed ref 3===========\n # module: examples.interop\n + def http3_request(connection, authority, path):\n + reader, writer = await connection.create_stream()\n + stream_id = writer.get_extra_info(\"stream_id\")\n + \n + http = H3Connection(connection._connection)\n + http.send_headers(\n + stream_id=stream_id,\n + headers=[\n + (b\":method\", b\"GET\"),\n + (b\":scheme\", b\"https\"),\n + (b\":authority\", authority.encode(\"utf8\")),\n + (b\":path\", path.encode(\"utf8\")),\n + ],\n + )\n + http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n + \n + return await reader.read()\n + \n===========changed ref 4===========\n # module: examples.interop\n def test_session_resumption(config, **kwargs):\n saved_ticket = None\n \n def session_ticket_handler(ticket):\n nonlocal saved_ticket\n saved_ticket = ticket\n \n # connect a first time, receive a ticket\n async with connect(\n config.host,\n config.port,\n session_ticket_handler=session_ticket_handler,\n **kwargs\n ) as connection:\n await connection.ping()\n \n # connect a second time, with the ticket\n if saved_ticket is not None:\n async with connect(\n config.host, config.port, session_ticket=saved_ticket, **kwargs\n ) as connection:\n await connection.ping()\n \n + # check session was resumed\n - # check session was resumed\n + if connection._connection.tls.session_resumed:\n - if connection._connection.tls.session_resumed:\n + config.result |= Result.R\n - config.result |= Result.R\n \n + # check early data was accepted\n - # check early data was accepted\n + if connection._connection.tls.early_data_accepted:\n - if connection._connection.tls.early_data_accepted:\n + config.result |= Result.Z\n - config.result |= Result.Z\n \n===========changed ref 5===========\n # module: examples.interop\n class Result(Flag):\n + V = 0x0001\n - V = 1\n + H = 0x0002\n - H = 2\n + D = 0x0004\n - D = 4\n + C = 0x0008\n - C = 8\n + R = 0x0010\n - R = 16\n + Z = 0x0020\n - Z = 32\n + S = 0x0040\n - S = 64\n - # M = 128\n - # B = 256\n - U = 512\n - # 3 = 1024\n + M = 0x0080\n + B = 0x0100\n + U = 0x0200\n + P = 0x0400\n - P = 2048\n + E = 0x0800\n + T = 0x1000\n + three = 0x2000\n + d = 0x4000\n + p = 0x8000\n \n===========changed ref 6===========\n # module: examples.interop\n CONFIGS = [\n Config(\"aioquic\", \"quic.aiortc.org\", 4433, 4434, \"/\"),\n Config(\"ats\", \"quic.ogre.com\", 4433, 4434, \"/\"),\n Config(\"f5\", \"f5quic.com\", 4433, 4433, \"/\"),\n Config(\"gquic\", \"quic.rocks\", 4433, 4433, \"/\"),\n Config(\"lsquic\", \"http3-test.litespeedtech.com\", 4433, 4434, None),\n Config(\"mvfst\", \"fb.mvfst.net\", 4433, 4434, \"/\"),\n + Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, \"/\"),\n - Config(\"ngtcp2\", \"nghttp2.org\", 4433, 4434, None),\n Config(\"ngx_quic\", \"cloudflare-quic.com\", 443, 443, None),\n Config(\"pandora\", \"pandora.cm.in.tum.de\", 4433, 4434, \"/\"),\n Config(\"picoquic\", \"test.privateoctopus.com\", 4433, 4434, \"/\"),\n Config(\"quant\", \"quant.eggert.org\", 4433, 4434, \"/\"),\n Config(\"quic-go\", \"quic.seemann.io\", 443, 443, \"/\"),\n Config(\"quiche\", \"quic.tech\", 4433, 4433, \"/\"),\n Config(\"quicker\", \"quicker.edm.uhasselt.be\", 4433, None, \"/\"),\n Config(\"quicly\", \"kazuhooku.com\", 4433, 4434, \"/\"),\n Config(\"quinn\", \"ralith.com\", 4433, 4434, \"/\"),\n Config(\"winquic\", \"quic.westus.cloudapp.azure.com\", 4433, 4434, \"/\"),\n ]\n "}}},{"rowIdx":3088,"cells":{"path":{"kind":"string","value":"examples.interop/run"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"975975ab854a8e2e0c7d2622377a844aa18ea79f"},"commit_message":{"kind":"string","value":"[interop] rework interop script"},"ground_truth":{"kind":"string","value":" <0>: configs = list(filter(lambda x: not only or x.name == only, CONFIGS))\n <1>: \n <3>: for test_name, test_func in tests:\n for test_name, test_func in filter(\n <4>: lambda x: x[0].startswith(\"test_\"), globals().items()\n <5>: ):\n"},"main_code":{"kind":"string","value":" # module: examples.interop\n + def run(configs, tests, **kwargs) -> None:\n - def run(only=None, **kwargs) -> None:\n <0> configs = list(filter(lambda x: not only or x.name == only, CONFIGS))\n <1> \n <2> for config in configs:\n <3> for test_name, test_func in filter(\n <4> lambda x: x[0].startswith(\"test_\"), globals().items()\n <5> ):\n <6> print(\"\\n=== %s %s ===\\n\" % (config.name, test_name))\n <7> try:\n <8> await asyncio.wait_for(test_func(config, **kwargs), timeout=5)\n <9> except Exception as exc:\n<10> print(exc)\n<11> print(\"\")\n<12> print_result(config)\n<13> \n<14> # print summary\n<15> if len(configs) > 1:\n<16> print(\"SUMMARY\")\n<17> for config in configs:\n<18> print_result(config)\n<19> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.asyncio.client\n connect(*args, **kwds)\n connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None]\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol\n request_key_update() -> None\n \n ping() -> None\n \n at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__\n self._connection = connection\n \n at: aioquic.quic.connection.QuicConnection._initialize\n self.tls = tls.Context(is_client=self._is_client, logger=self._logger)\n \n at: aioquic.tls.Context.__init__\n self.early_data_accepted = False\n \n at: aioquic.tls.Context._client_handle_encrypted_extensions\n self.early_data_accepted = encrypted_extensions.early_data\n \n at: aioquic.tls.Context._server_handle_hello\n self.early_data_accepted = True\n \n at: examples.interop\n Result()\n \n \n===========changed ref 0===========\n # module: examples.interop\n class Result(Flag):\n + V = 0x0001\n - V = 1\n + H = 0x0002\n - H = 2\n + D = 0x0004\n - D = 4\n + C = 0x0008\n - C = 8\n + R = 0x0010\n - R = 16\n + Z = 0x0020\n - Z = 32\n + S = 0x0040\n - S = 64\n - # M = 128\n - # B = 256\n - U = 512\n - # 3 = 1024\n + M = 0x0080\n + B = 0x0100\n + U = 0x0200\n + P = 0x0400\n - P = 2048\n + E = 0x0800\n + T = 0x1000\n + three = 0x2000\n + d = 0x4000\n + p = 0x8000\n \n===========changed ref 1===========\n # module: examples.interop\n def print_result(config: Config) -> None:\n + result = str(config.result).replace(\"three\", \"3\")\n + result = result[0:7] + \" \" + result[7:13] + \" \" + result[13:]\n + print(\"%s%s%s\" % (config.name, \" \" * (20 - len(config.name)), result))\n - print(\"%s%s%s\" % (config.name, \" \" * (20 - len(config.name)), config.result))\n \n===========changed ref 2===========\n # module: examples.interop\n + def test_http_0(config, **kwargs):\n + if config.path is None:\n + return\n + \n + kwargs[\"alpn_protocols\"] = [\"hq-22\"]\n + async with connect(config.host, config.port, **kwargs) as connection:\n + response = await http_request(connection, config.path)\n + if response:\n + config.result |= Result.D\n + \n===========changed ref 3===========\n # module: examples.interop\n + def test_http_3(config, **kwargs):\n + if config.path is None:\n + return\n + \n + kwargs[\"alpn_protocols\"] = [\"h3-22\"]\n + async with connect(config.host, config.port, **kwargs) as connection:\n + response = await http3_request(connection, config.host, config.path)\n + if response:\n + config.result |= Result.D\n + config.result |= Result.three\n + \n===========changed ref 4===========\n # module: examples.interop\n - def test_data_transfer(config, **kwargs):\n - if config.path is None:\n - return\n - \n - async with connect(config.host, config.port, **kwargs) as connection:\n - response1 = await http_request(connection, config.path)\n - response2 = await http_request(connection, config.path)\n - \n - if response1 and response2:\n - config.result |= Result.D\n - \n===========changed ref 5===========\n # module: examples.interop\n + def http3_request(connection, authority, path):\n + reader, writer = await connection.create_stream()\n + stream_id = writer.get_extra_info(\"stream_id\")\n + \n + http = H3Connection(connection._connection)\n + http.send_headers(\n + stream_id=stream_id,\n + headers=[\n + (b\":method\", b\"GET\"),\n + (b\":scheme\", b\"https\"),\n + (b\":authority\", authority.encode(\"utf8\")),\n + (b\":path\", path.encode(\"utf8\")),\n + ],\n + )\n + http.send_data(stream_id=stream_id, data=b\"\", end_stream=True)\n + \n + return await reader.read()\n + \n===========changed ref 6===========\n # module: examples.interop\n def test_session_resumption(config, **kwargs):\n saved_ticket = None\n \n def session_ticket_handler(ticket):\n nonlocal saved_ticket\n saved_ticket = ticket\n \n # connect a first time, receive a ticket\n async with connect(\n config.host,\n config.port,\n session_ticket_handler=session_ticket_handler,\n **kwargs\n ) as connection:\n await connection.ping()\n \n # connect a second time, with the ticket\n if saved_ticket is not None:\n async with connect(\n config.host, config.port, session_ticket=saved_ticket, **kwargs\n ) as connection:\n await connection.ping()\n \n + # check session was resumed\n - # check session was resumed\n + if connection._connection.tls.session_resumed:\n - if connection._connection.tls.session_resumed:\n + config.result |= Result.R\n - config.result |= Result.R\n \n + # check early data was accepted\n - # check early data was accepted\n + if connection._connection.tls.early_data_accepted:\n - if connection._connection.tls.early_data_accepted:\n + config.result |= Result.Z\n - config.result |= Result.Z\n "}}},{"rowIdx":3089,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"71523435ae58fde0a6d8029c0e0746b451683c02"},"commit_message":{"kind":"string","value":"[http3] add an H3Stream class"},"ground_truth":{"kind":"string","value":" <7>: self._stream_blocked: Set[int] = set()\n <8>: self._stream_buffers: Dict[int, bytes] = {}\n <9>: self._stream_ended: Set[int] = set()\n<10>: self._stream: Dict[int, H3Stream] = {}\n self._stream_types: Dict[int, int] = {}\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n <0> self._max_table_capacity = 0x100\n <1> self._blocked_streams = 0x10\n <2> \n <3> self._is_client = quic.configuration.is_client\n <4> self._quic = quic\n <5> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n <6> self._encoder = Encoder()\n <7> self._stream_blocked: Set[int] = set()\n <8> self._stream_buffers: Dict[int, bytes] = {}\n <9> self._stream_ended: Set[int] = set()\n<10> self._stream_types: Dict[int, int] = {}\n<11> \n<12> self._local_control_stream_id: Optional[int] = None\n<13> self._local_decoder_stream_id: Optional[int] = None\n<14> self._local_encoder_stream_id: Optional[int] = None\n<15> \n<16> self._peer_control_stream_id: Optional[int] = None\n<17> self._peer_decoder_stream_id: Optional[int] = None\n<18> self._peer_encoder_stream_id: Optional[int] = None\n<19> \n<20> self._init_connection()\n<21> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Stream()\n \n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL)\n \n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n self._local_decoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_DECODER\n )\n \n at: aioquic.quic.configuration.QuicConfiguration\n alpn_protocols: Optional[List[str]] = None\n \n certificate: Any = None\n \n idle_timeout: float = 60.0\n \n is_client: bool = True\n \n private_key: Any = None\n \n secrets_log_file: TextIO = None\n \n server_name: Optional[str] = None\n \n session_ticket: Optional[SessionTicket] = None\n \n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.quic.connection\n QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None)\n \n at: typing\n Dict = _alias(dict, 2, inst=False, name='Dict')\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n + class H3Stream:\n + def __init__(self):\n + self.blocked = False\n + self.buffer = b\"\"\n + self.ended = False\n + self.stream_type = None\n + "}}},{"rowIdx":3090,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Connection._receive_stream_data"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"71523435ae58fde0a6d8029c0e0746b451683c02"},"commit_message":{"kind":"string","value":"[http3] add an H3Stream class"},"ground_truth":{"kind":"string","value":" <2>: if stream_id not in self._stream:\n if stream_id in self._stream_buffers:\n <3>: self._stream_buffers[stream_id] += data\n <4>: else:\n <5>: self._stream[stream_id] = H3Stream()\n self._stream_buffers[stream_id] = data\n <6>: stream = self._stream[stream_id]\n stream.buffer += data\n <7>: stream.ended = True\n if stream.blocked:\n self._stream_ended.add(stream_id)\n <8>: if stream_id in self._stream_blocked:\n<11>: buf = Buffer(data=stream.buffer)\n buf = Buffer(data=self._stream_buffers[stream_id])\n<23>: if (\n<24>: stream_is_unidirectional(stream_id)\n<25>: and stream_id not in self._stream_types\n<26>: ):\n<27>: if stream_is_unidirectional(stream_id) and stream.stream_type is None:\n<28>: stream.stream_type = buf.pull_uint_var()\n stream_type = buf.pull_uint_var()\n<33>: if stream.stream_type == StreamType.CONTROL:\n if stream_type == StreamType.CONTROL:\n<36>: elif stream.stream_type == StreamType.QPACK_DECODER:\n elif stream_type == StreamType.QPACK_DECODER:\n<39>: elif stream.stream_type == StreamType.QPACK_ENCODER:\n elif stream_type == StreamType.QPACK_ENCODER:\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n <0> http_events: List[Event] = []\n <1> \n <2> if stream_id in self._stream_buffers:\n <3> self._stream_buffers[stream_id] += data\n <4> else:\n <5> self._stream_buffers[stream_id] = data\n <6> if stream_ended:\n <7> self._stream_ended.add(stream_id)\n <8> if stream_id in self._stream_blocked:\n <9> return http_events\n<10> \n<11> buf = Buffer(data=self._stream_buffers[stream_id])\n<12> consumed = 0\n<13> unblocked_streams: Set[int] = set()\n<14> \n<15> # some peers (e.g. f5) end the stream with no data\n<16> if stream_ended and buf.eof() and (stream_id % 4 == 0):\n<17> http_events.append(\n<18> DataReceived(data=b\"\", stream_id=stream_id, stream_ended=True)\n<19> )\n<20> \n<21> while not buf.eof():\n<22> # fetch stream type for unidirectional streams\n<23> if (\n<24> stream_is_unidirectional(stream_id)\n<25> and stream_id not in self._stream_types\n<26> ):\n<27> try:\n<28> stream_type = buf.pull_uint_var()\n<29> except BufferReadError:\n<30> break\n<31> consumed = buf.tell()\n<32> \n<33> if stream_type == StreamType.CONTROL:\n<34> assert self._peer_control_stream_id is None\n<35> self._peer_control_stream_id = stream_id\n<36> elif stream_type == StreamType.QPACK_DECODER:\n<37> assert self._peer_decoder_stream_id is None\n<38> self._peer_decoder_stream_id = stream_id\n<39> elif stream_type == StreamType.QPACK_ENCODER:\n<40> assert self._peer_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n self._peer_encoder_stream_id = stream_id\n self._stream_types[stream_id] = stream_type\n \n if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n # fetch next frame\n try:\n frame_type = buf.pull_uint_var()\n frame_length = buf.pull_uint_var()\n frame_data = buf.pull_bytes(frame_length)\n except BufferReadError:\n break\n consumed = buf.tell()\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type == FrameType.HEADERS:\n try:\n decoder, headers = self._decoder.feed_header(\n stream_id, frame_data\n )\n except StreamBlocked:\n self._stream_blocked.add(stream_id)\n break\n self._quic.send_stream_data(\n self._local_decoder_stream_id, decoder\n )\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif stream_id == self._peer_control_stream_id:\n # unidirectional control stream\n if frame_type == FrameType.SETTINGS:\n settings = parse_settings(frame_data)\n encoder = self._encoder.apply_settings(\n max_table_capacity=settings.get\n===========below chunk 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 2\n _settings(frame_data)\n encoder = self._encoder.apply_settings(\n max_table_capacity=settings.get(\n Setting.QPACK_MAX_TABLE_CAPACITY, 0\n ),\n blocked_streams=settings.get(\n Setting.QPACK_BLOCKED_STREAMS, 0\n ),\n )\n self._quic.send_stream_data(\n self._local_encoder_stream_id, encoder\n )\n else:\n # fetch unframed data\n data = buf.pull_bytes(buf.capacity - buf.tell())\n consumed = buf.tell()\n \n if stream_id == self._peer_decoder_stream_id:\n self._encoder.feed_decoder(data)\n \n elif stream_id == self._peer_encoder_stream_id:\n unblocked_streams.update(self._decoder.feed_encoder(data))\n \n # remove processed data from buffer\n self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:]\n \n # process unblocked streams\n for stream_id in unblocked_streams:\n decoder, headers = self._decoder.resume_header(stream_id)\n self._stream_blocked.discard(stream_id)\n cls = ResponseReceived if self._is_client else RequestReceived\n http_events.append(\n cls(\n headers=headers,\n stream_id=stream_id,\n stream_ended=stream_id in self._stream_ended\n and not self._stream_buffers[stream_id],\n )\n )\n http_events.extend(\n self._receive_stream_data(\n stream_id, b\"\", stream_id in self._stream_ended\n \n===========unchanged ref 0===========\n at: aioquic._buffer\n BufferReadError(*args: object)\n \n Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None)\n \n at: aioquic._buffer.Buffer\n eof() -> bool\n \n tell() -> int\n \n pull_bytes(length: int) -> bytes\n \n pull_uint_var() -> int\n \n at: aioquic.h3.connection\n FrameType(x: Union[str, bytes, bytearray], base: int)\n FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n Setting(x: Union[str, bytes, bytearray], base: int)\n Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n \n StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...)\n StreamType(x: Union[str, bytes, bytearray], base: int)\n \n parse_settings(data: bytes) -> Dict[int, int]\n \n H3Stream()\n \n at: aioquic.h3.connection.H3Connection\n _create_uni_stream(stream_type: int) -> int\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._is_client = quic.configuration.is_client\n \n self._quic = quic\n \n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n \n self._encoder = Encoder()\n \n self._stream: Dict[int, H3Stream] = {}\n \n self._local_decoder_stream_id: Optional[int] = None\n \n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n \n self._peer_decoder_stream_id: Optional[int] = None\n \n self._peer_encoder_stream_id: Optional[int] = None\n \n \n===========unchanged ref 1===========\n at: aioquic.h3.connection.H3Connection._init_connection\n self._local_encoder_stream_id = self._create_uni_stream(\n StreamType.QPACK_ENCODER\n )\n \n at: aioquic.h3.connection.H3Stream.__init__\n self.blocked = False\n \n self.buffer = b\"\"\n \n self.ended = False\n \n self.stream_type = None\n \n at: aioquic.h3.events\n Event()\n \n DataReceived(data: bytes, stream_id: int, stream_ended: bool)\n \n RequestReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool)\n \n at: aioquic.h3.events.DataReceived\n data: bytes\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.RequestReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.h3.events.ResponseReceived\n headers: Headers\n \n stream_id: int\n \n stream_ended: bool\n \n at: aioquic.quic.connection\n stream_is_unidirectional(stream_id: int) -> bool\n \n at: aioquic.quic.connection.QuicConnection\n send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None\n \n at: typing\n List = _alias(list, 1, inst=False, name='List')\n \n Set = _alias(set, 1, inst=False, name='Set')\n \n at: typing.Mapping\n get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]\n get(key: _KT) -> Optional[_VT_co]\n \n "}}},{"rowIdx":3091,"cells":{"path":{"kind":"string","value":"tests.test_h3/H3ConnectionTest.test_uni_stream_type"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"71523435ae58fde0a6d8029c0e0746b451683c02"},"commit_message":{"kind":"string","value":"[http3] add an H3Stream class"},"ground_truth":{"kind":"string","value":"<11>: self.assertEqual(list(h3_server._stream.keys()), [2])\n self.assertEqual(h3_server._stream[2].buffer, b\"\")\n self.assertEqual(h3_server._stream_buffers, {2: b\"\"})\n<12>: self.assertEqual(h3_server._stream[2].stream_type, 9)\n self.assertEqual(h3_server._stream_types, {2: 9})\n<20>: self.assertEqual(list(h3_server._stream.keys()), [2, 6])\n self.assertEqual(h3_server._stream[2].buffer, b\"\")\n self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\\x40\"})\n<21>: self.assertEqual(h3_server._stream[2].stream_type, 9)\n self.assertEqual(h3_server._stream_types, {2: 9})\n<22>: self.assertEqual(h3_server._stream[6].buffer, b\"\\x40\")\n self.assertEqual(h3_server._stream[6].stream_type, None)\n<25>: self.assertEqual(list(h3_server._stream.keys()), [2, 6])\n self.assertEqual(h3_server._stream[2]."},"main_code":{"kind":"string","value":" # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n <0> with client_and_server(\n <1> client_options={\"alpn_protocols\": [\"h3-22\"]},\n <2> server_options={\"alpn_protocols\": [\"h3-22\"]},\n <3> ) as (quic_client, quic_server):\n <4> h3_server = H3Connection(quic_server)\n <5> \n <6> # unknown stream type 9\n <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n <8> self.assertEqual(stream_id, 2)\n <9> quic_client.send_stream_data(stream_id, b\"\\x09\")\n<10> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<11> self.assertEqual(h3_server._stream_buffers, {2: b\"\"})\n<12> self.assertEqual(h3_server._stream_types, {2: 9})\n<13> \n<14> # unknown stream type 64, one byte at a time\n<15> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True)\n<16> self.assertEqual(stream_id, 6)\n<17> \n<18> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<19> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<20> self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\\x40\"})\n<21> self.assertEqual(h3_server._stream_types, {2: 9})\n<22> \n<23> quic_client.send_stream_data(stream_id, b\"\\x40\")\n<24> self.assertEqual(h3_transfer(quic_client, h3_server), [])\n<25> self.assertEqual(h3_server._stream_buffers, {2: b\"\", 6: b\"\"})\n<26> self.assertEqual"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: tests.test_h3\n class H3ConnectionTest(TestCase):\n def test_uni_stream_type(self):\n # offset: 1\n \n \n===========unchanged ref 0===========\n at: aioquic.h3.connection\n H3Connection(quic: QuicConnection)\n \n at: aioquic.h3.connection.H3Connection.__init__\n self._stream: Dict[int, H3Stream] = {}\n \n at: aioquic.h3.connection.H3Stream.__init__\n self.buffer = b\"\"\n \n self.stream_type = None\n \n at: tests.test_connection\n client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={})\n \n at: tests.test_h3\n h3_transfer(quic_sender, h3_receiver)\n \n at: unittest.case.TestCase\n failureException: Type[BaseException]\n \n longMessage: bool\n \n maxDiff: Optional[int]\n \n _testMethodName: str\n \n _testMethodDoc: str\n \n assertEqual(first: Any, second: Any, msg: Any=...) -> None\n \n \n===========changed ref 0===========\n # module: aioquic.h3.connection\n + class H3Stream:\n + def __init__(self):\n + self.blocked = False\n + self.buffer = b\"\"\n + self.ended = False\n + self.stream_type = None\n + \n===========changed ref 1===========\n # module: aioquic.h3.connection\n class H3Connection:\n def __init__(self, quic: QuicConnection):\n self._max_table_capacity = 0x100\n self._blocked_streams = 0x10\n \n self._is_client = quic.configuration.is_client\n self._quic = quic\n self._decoder = Decoder(self._max_table_capacity, self._blocked_streams)\n self._encoder = Encoder()\n - self._stream_blocked: Set[int] = set()\n - self._stream_buffers: Dict[int, bytes] = {}\n - self._stream_ended: Set[int] = set()\n + self._stream: Dict[int, H3Stream] = {}\n - self._stream_types: Dict[int, int] = {}\n \n self._local_control_stream_id: Optional[int] = None\n self._local_decoder_stream_id: Optional[int] = None\n self._local_encoder_stream_id: Optional[int] = None\n \n self._peer_control_stream_id: Optional[int] = None\n self._peer_decoder_stream_id: Optional[int] = None\n self._peer_encoder_stream_id: Optional[int] = None\n \n self._init_connection()\n \n===========changed ref 2===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n http_events: List[Event] = []\n \n + if stream_id not in self._stream:\n - if stream_id in self._stream_buffers:\n - self._stream_buffers[stream_id] += data\n - else:\n + self._stream[stream_id] = H3Stream()\n - self._stream_buffers[stream_id] = data\n + stream = self._stream[stream_id]\n + stream.buffer += data\n if stream_ended:\n + stream.ended = True\n + if stream.blocked:\n - self._stream_ended.add(stream_id)\n - if stream_id in self._stream_blocked:\n return http_events\n \n + buf = Buffer(data=stream.buffer)\n - buf = Buffer(data=self._stream_buffers[stream_id])\n consumed = 0\n unblocked_streams: Set[int] = set()\n \n # some peers (e.g. f5) end the stream with no data\n if stream_ended and buf.eof() and (stream_id % 4 == 0):\n http_events.append(\n DataReceived(data=b\"\", stream_id=stream_id, stream_ended=True)\n )\n \n while not buf.eof():\n # fetch stream type for unidirectional streams\n - if (\n - stream_is_unidirectional(stream_id)\n - and stream_id not in self._stream_types\n - ):\n + if stream_is_unidirectional(stream_id) and stream.stream_type is None:\n try:\n + stream.stream_type = buf.pull_uint_var()\n - stream_type = buf.pull_uint_var()\n except BufferReadError:\n break\n consumed = buf.tell()\n \n + if stream.stream_type == StreamType.CONTROL:\n - if\n===========changed ref 3===========\n # module: aioquic.h3.connection\n class H3Connection:\n def _receive_stream_data(\n self, stream_id: int, data: bytes, stream_ended: bool\n ) -> List[Event]:\n # offset: 1\n break\n consumed = buf.tell()\n \n + if stream.stream_type == StreamType.CONTROL:\n - if stream_type == StreamType.CONTROL:\n assert self._peer_control_stream_id is None\n self._peer_control_stream_id = stream_id\n + elif stream.stream_type == StreamType.QPACK_DECODER:\n - elif stream_type == StreamType.QPACK_DECODER:\n assert self._peer_decoder_stream_id is None\n self._peer_decoder_stream_id = stream_id\n + elif stream.stream_type == StreamType.QPACK_ENCODER:\n - elif stream_type == StreamType.QPACK_ENCODER:\n assert self._peer_encoder_stream_id is None\n self._peer_encoder_stream_id = stream_id\n - self._stream_types[stream_id] = stream_type\n \n if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id:\n # fetch next frame\n try:\n frame_type = buf.pull_uint_var()\n frame_length = buf.pull_uint_var()\n frame_data = buf.pull_bytes(frame_length)\n except BufferReadError:\n break\n consumed = buf.tell()\n \n if (stream_id % 4) == 0:\n # client-initiated bidirectional streams carry requests and responses\n if frame_type == FrameType.DATA:\n http_events.append(\n DataReceived(\n data=frame_data,\n stream_id=stream_id,\n stream_ended=stream_ended and buf.eof(),\n )\n )\n elif frame_type =="}}},{"rowIdx":3092,"cells":{"path":{"kind":"string","value":"aioquic.h3.connection/H3Stream.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"ed5190a3f3df75433a902c776c0bcfe01f97e8c5"},"commit_message":{"kind":"string","value":"[http3] fix mypy errors"},"ground_truth":{"kind":"string","value":" <3>: self.stream_type: Optional[int] = None\n self.stream_type = None\n"},"main_code":{"kind":"string","value":" # module: aioquic.h3.connection\n class H3Stream:\n + def __init__(self) -> None:\n - def __init__(self):\n <0> self.blocked = False\n <1> self.buffer = b\"\"\n <2> self.ended = False\n <3> self.stream_type = None\n <4> \n "},"context":{"kind":"string","value":""}}},{"rowIdx":3093,"cells":{"path":{"kind":"string","value":"aioquic.quic.recovery/QuicPacketRecovery.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":" <6>: self._quic_logger = quic_logger\n<21>: self._ssthresh: Optional[int] = None\n self._ssthresh = math.inf\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def __init__(\n + self,\n + is_client_without_1rtt: bool,\n + send_probe: Callable[[], None],\n + quic_logger: Optional[QuicLogger] = None,\n - self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n ) -> None:\n <0> self.ack_delay_exponent = 3\n <1> self.is_client_without_1rtt = is_client_without_1rtt\n <2> self.max_ack_delay = 25 # ms\n <3> self.spaces: List[QuicPacketSpace] = []\n <4> \n <5> # callbacks\n <6> self._send_probe = send_probe\n <7> \n <8> # loss detection\n <9> self._pto_count = 0\n<10> self._rtt_initialized = False\n<11> self._rtt_latest = 0.0\n<12> self._rtt_min = math.inf\n<13> self._rtt_smoothed = 0.0\n<14> self._rtt_variance = 0.0\n<15> self._time_of_last_sent_ack_eliciting_packet = 0.0\n<16> \n<17> # congestion control\n<18> self.bytes_in_flight = 0\n<19> self.congestion_window = K_INITIAL_WINDOW\n<20> self._congestion_recovery_start_time = 0.0\n<21> self._ssthresh = math.inf\n<22> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.logger\n QuicLogger()\n \n at: aioquic.quic.recovery\n QuicPacketSpace()\n \n at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received\n self._rtt_latest = max(latest_rtt, 0.001)\n self._rtt_latest -= ack_delay\n \n self._rtt_min = self._rtt_latest\n \n self._rtt_initialized = True\n \n self._rtt_variance = latest_rtt / 2\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n \n self._rtt_smoothed = latest_rtt\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self._pto_count = 0\n \n at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout\n self._pto_count += 1\n \n at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_sent\n self._time_of_last_sent_ack_eliciting_packet = packet.sent_time\n \n at: math\n inf: float\n \n at: typing\n Callable = _CallableType(collections.abc.Callable, 2)\n \n List = _alias(list, 1, inst=False, name='List')\n \n \n===========changed ref 0===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + \"\"\"\n + A QUIC event logger.\n + \n + Events are logged in the format defined by qlog draft-00.\n + \n + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00\n + \"\"\"\n + \n===========changed ref 1===========\n + # module: aioquic.quic.logger\n + \n + \n===========changed ref 2===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def log_event(self, *, category: str, event: str, data: Dict) -> None:\n + self._events.append((time.time(), category, event, data))\n + \n===========changed ref 3===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def __init__(self) -> None:\n + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()\n + \n===========changed ref 4===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def packet_type(self, packet_type: int) -> str:\n + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, \"1RTT\")\n + \n===========changed ref 5===========\n + # module: aioquic.quic.logger\n + PACKET_TYPE_NAMES = {\n + PACKET_TYPE_INITIAL: \"initial\",\n + PACKET_TYPE_HANDSHAKE: \"handshake\",\n + PACKET_TYPE_ZERO_RTT: \"0RTT\",\n + PACKET_TYPE_ONE_RTT: \"1RTT\",\n + PACKET_TYPE_RETRY: \"retry\",\n + }\n + \n===========changed ref 6===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def to_dict(self) -> Dict[str, Any]:\n + \"\"\"\n + Return the trace as a dictionary which can be written as JSON.\n + \"\"\"\n + traces = []\n + if self._events:\n + reference_time = self._events[0][0]\n + trace = {\n + \"common_fields\": {\"reference_time\": \"%d\" % (reference_time * 1000)},\n + \"event_fields\": [\"relative_time\", \"CATEGORY\", \"EVENT_TYPE\", \"DATA\"],\n + \"events\": list(\n + map(\n + lambda event: (\n + \"%d\" % ((event[0] - reference_time) * 1000),\n + event[1].upper(), # draft-00\n + event[2].upper(), # draft-00\n + event[3],\n + ),\n + self._events,\n + )\n + ),\n + }\n + traces.append(trace)\n + \n + return {\"qlog_version\": \"draft-00\", \"traces\": traces}\n + "}}},{"rowIdx":3094,"cells":{"path":{"kind":"string","value":"aioquic.quic.recovery/QuicPacketRecovery.on_ack_received"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n <0> \"\"\"\n <1> Update metrics as the result of an ACK being received.\n <2> \"\"\"\n <3> is_ack_eliciting = False\n <4> largest_acked = ack_rangeset.bounds().stop - 1\n <5> largest_newly_acked = None\n <6> largest_sent_time = None\n <7> \n <8> if largest_acked > space.largest_acked_packet:\n <9> space.largest_acked_packet = largest_acked\n<10> \n<11> for packet_number in sorted(space.sent_packets.keys()):\n<12> if packet_number > largest_acked:\n<13> break\n<14> if packet_number in ack_rangeset:\n<15> # remove packet and update counters\n<16> packet = space.sent_packets.pop(packet_number)\n<17> if packet.is_ack_eliciting:\n<18> is_ack_eliciting = True\n<19> space.ack_eliciting_in_flight -= 1\n<20> if packet.in_flight:\n<21> self.on_packet_acked(packet)\n<22> largest_newly_acked = packet_number\n<23> largest_sent_time = packet.sent_time\n<24> \n<25> # trigger callbacks\n<26> for handler, args in packet.delivery_handlers:\n<27> handler(QuicDeliveryState.ACKED, *args)\n<28> \n<29> # nothing to do if there are no newly acked packets\n<30> if largest_newly_acked is None:\n<31> return\n<32> \n<33> if largest_acked == largest_newly_acked and is_ack_eliciting:\n<34> latest_rtt = now - largest_sent_time\n<35> \n<36> # decode ACK delay into seconds\n<37> ack_delay = max(\n<38> (ack_delay_encoded << self.ack_delay_"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n # offset: 1\n self.max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._rtt_latest = max(latest_rtt, 0.001)\n if self._rtt_latest < self._rtt_min:\n self._rtt_min = self._rtt_latest\n if self._rtt_latest > self._rtt_min + ack_delay:\n self._rtt_latest -= ack_delay\n \n if not self._rtt_initialized:\n self._rtt_initialized = True\n self._rtt_variance = latest_rtt / 2\n self._rtt_smoothed = latest_rtt\n else:\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n self.detect_loss(space, now=now)\n \n self._pto_count = 0\n \n \n===========unchanged ref 0===========\n at: aioquic.quic.packet_builder\n QuicDeliveryState()\n \n at: aioquic.quic.packet_builder.QuicSentPacket\n epoch: Epoch\n \n in_flight: bool\n \n is_ack_eliciting: bool\n \n is_crypto_packet: bool\n \n packet_number: int\n \n packet_type: int\n \n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field(\n default_factory=list\n )\n \n at: aioquic.quic.rangeset\n RangeSet(ranges: Iterable[range]=[])\n \n at: aioquic.quic.rangeset.RangeSet\n bounds() -> range\n \n at: aioquic.quic.recovery\n K_GRANULARITY = 0.001 # seconds\n \n QuicPacketSpace()\n \n at: aioquic.quic.recovery.QuicPacketRecovery\n on_packet_acked(packet: QuicSentPacket) -> None\n \n at: aioquic.quic.recovery.QuicPacketRecovery.__init__\n self.ack_delay_exponent = 3\n \n self.max_ack_delay = 25 # ms\n \n self._rtt_initialized = False\n \n self._rtt_latest = 0.0\n \n self._rtt_min = math.inf\n \n self._rtt_smoothed = 0.0\n \n self._rtt_variance = 0.0\n \n at: aioquic.quic.recovery.QuicPacketSpace.__init__\n self.ack_eliciting_in_flight = 0\n \n self.largest_acked_packet = 0\n \n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n at: typing.MutableMapping\n pop(key: _KT) -> _VT\n pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]\n \n \n===========changed ref 0===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def __init__(\n + self,\n + is_client_without_1rtt: bool,\n + send_probe: Callable[[], None],\n + quic_logger: Optional[QuicLogger] = None,\n - self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n ) -> None:\n self.ack_delay_exponent = 3\n self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n + self._quic_logger = quic_logger\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n + self._ssthresh: Optional[int] = None\n - self._ssthresh = math.inf\n \n===========changed ref 1===========\n + # module: aioquic.quic.logger\n + \n + \n===========changed ref 2===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def log_event(self, *, category: str, event: str, data: Dict) -> None:\n + self._events.append((time.time(), category, event, data))\n + \n===========changed ref 3===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def __init__(self) -> None:\n + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()\n + \n===========changed ref 4===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def packet_type(self, packet_type: int) -> str:\n + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, \"1RTT\")\n + \n===========changed ref 5===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + \"\"\"\n + A QUIC event logger.\n + \n + Events are logged in the format defined by qlog draft-00.\n + \n + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00\n + \"\"\"\n + \n===========changed ref 6===========\n + # module: aioquic.quic.logger\n + PACKET_TYPE_NAMES = {\n + PACKET_TYPE_INITIAL: \"initial\",\n + PACKET_TYPE_HANDSHAKE: \"handshake\",\n + PACKET_TYPE_ZERO_RTT: \"0RTT\",\n + PACKET_TYPE_ONE_RTT: \"1RTT\",\n + PACKET_TYPE_RETRY: \"retry\",\n + }\n + \n===========changed ref 7===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def to_dict(self) -> Dict[str, Any]:\n + \"\"\"\n + Return the trace as a dictionary which can be written as JSON.\n + \"\"\"\n + traces = []\n + if self._events:\n + reference_time = self._events[0][0]\n + trace = {\n + \"common_fields\": {\"reference_time\": \"%d\" % (reference_time * 1000)},\n + \"event_fields\": [\"relative_time\", \"CATEGORY\", \"EVENT_TYPE\", \"DATA\"],\n + \"events\": list(\n + map(\n + lambda event: (\n + \"%d\" % ((event[0] - reference_time) * 1000),\n + event[1].upper(), # draft-00\n + event[2].upper(), # draft-00\n + event[3],\n + ),\n + self._events,\n + )\n + ),\n + }\n + traces.append(trace)\n + \n + return {\"qlog_version\": \"draft-00\", \"traces\": traces}\n + "}}},{"rowIdx":3095,"cells":{"path":{"kind":"string","value":"aioquic.quic.recovery/QuicPacketRecovery.on_packet_acked"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":" <6>: if self._ssthresh is None or self.congestion_window < self._ssthresh:\n if self.congestion_window < self._ssthresh:\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_packet_acked(self, packet: QuicSentPacket) -> None:\n <0> self.bytes_in_flight -= packet.sent_bytes\n <1> \n <2> # don't increase window in congestion recovery\n <3> if packet.sent_time <= self._congestion_recovery_start_time:\n <4> return\n <5> \n <6> if self.congestion_window < self._ssthresh:\n <7> # slow start\n <8> self.congestion_window += packet.sent_bytes\n <9> else:\n<10> # congestion avoidance\n<11> self.congestion_window += (\n<12> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window\n<13> )\n<14> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.recovery.QuicPacketRecovery\n detect_loss(space: QuicPacketSpace, now: float) -> None\n \n get_earliest_loss_time() -> Optional[QuicPacketSpace]\n \n on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None\n \n at: aioquic.quic.recovery.QuicPacketRecovery.__init__\n self.spaces: List[QuicPacketSpace] = []\n \n self._pto_count = 0\n \n at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received\n self._pto_count = 0\n \n at: aioquic.quic.recovery.QuicPacketSpace.__init__\n self.sent_packets: Dict[int, QuicSentPacket] = {}\n \n \n===========changed ref 0===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def __init__(\n + self,\n + is_client_without_1rtt: bool,\n + send_probe: Callable[[], None],\n + quic_logger: Optional[QuicLogger] = None,\n - self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n ) -> None:\n self.ack_delay_exponent = 3\n self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n + self._quic_logger = quic_logger\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n + self._ssthresh: Optional[int] = None\n - self._ssthresh = math.inf\n \n===========changed ref 1===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n \"\"\"\n Update metrics as the result of an ACK being received.\n \"\"\"\n is_ack_eliciting = False\n largest_acked = ack_rangeset.bounds().stop - 1\n largest_newly_acked = None\n largest_sent_time = None\n \n if largest_acked > space.largest_acked_packet:\n space.largest_acked_packet = largest_acked\n \n for packet_number in sorted(space.sent_packets.keys()):\n if packet_number > largest_acked:\n break\n if packet_number in ack_rangeset:\n # remove packet and update counters\n packet = space.sent_packets.pop(packet_number)\n if packet.is_ack_eliciting:\n is_ack_eliciting = True\n space.ack_eliciting_in_flight -= 1\n if packet.in_flight:\n self.on_packet_acked(packet)\n largest_newly_acked = packet_number\n largest_sent_time = packet.sent_time\n \n # trigger callbacks\n for handler, args in packet.delivery_handlers:\n handler(QuicDeliveryState.ACKED, *args)\n \n # nothing to do if there are no newly acked packets\n if largest_newly_acked is None:\n return\n \n if largest_acked == largest_newly_acked and is_ack_eliciting:\n latest_rtt = now - largest_sent_time\n \n # decode ACK delay into seconds\n ack_delay = max(\n (ack_delay_encoded << self.ack_delay_exponent) / 1000000,\n self.max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._\n===========changed ref 2===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n # offset: 1\n max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._rtt_latest = max(latest_rtt, 0.001)\n if self._rtt_latest < self._rtt_min:\n self._rtt_min = self._rtt_latest\n if self._rtt_latest > self._rtt_min + ack_delay:\n self._rtt_latest -= ack_delay\n \n if not self._rtt_initialized:\n self._rtt_initialized = True\n self._rtt_variance = latest_rtt / 2\n self._rtt_smoothed = latest_rtt\n else:\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n + if self._quic_logger is not None:\n + self._quic_logger.log_event(\n + category=\"recovery\",\n + event=\"metric_update\",\n + data={\n + \"latest_rtt\": int(self._rtt_latest * 1000),\n + \"min_rtt\": int(self._rtt_min * 1000),\n + \"smoothed_rtt\": int(self._rtt_smoothed * 1000),\n + \"rtt_variance\": int(self._rtt_variance * 1000),\n + },\n + )\n + \n self.detect_loss(space, now\n===========changed ref 3===========\n + # module: aioquic.quic.logger\n + \n + \n===========changed ref 4===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def log_event(self, *, category: str, event: str, data: Dict) -> None:\n + self._events.append((time.time(), category, event, data))\n + \n===========changed ref 5===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def __init__(self) -> None:\n + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()\n + \n===========changed ref 6===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def packet_type(self, packet_type: int) -> str:\n + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, \"1RTT\")\n + \n===========changed ref 7===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + \"\"\"\n + A QUIC event logger.\n + \n + Events are logged in the format defined by qlog draft-00.\n + \n + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00\n + \"\"\"\n + \n===========changed ref 8===========\n + # module: aioquic.quic.logger\n + PACKET_TYPE_NAMES = {\n + PACKET_TYPE_INITIAL: \"initial\",\n + PACKET_TYPE_HANDSHAKE: \"handshake\",\n + PACKET_TYPE_ZERO_RTT: \"0RTT\",\n + PACKET_TYPE_ONE_RTT: \"1RTT\",\n + PACKET_TYPE_RETRY: \"retry\",\n + }\n + "}}},{"rowIdx":3096,"cells":{"path":{"kind":"string","value":"aioquic.quic.recovery/QuicPacketRecovery.on_packet_lost"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":" <7>: if self._quic_logger is not None:\n self._quic_logger.log_event(\n category=\"recovery\",\n event=\"packet_lost\",\n data={\n \"type\": self._quic_logger.packet_type(packet.packet_type),\n \"packet_number\": packet.packet_number,\n },\n )\n self._log_metric_update()\n \n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None:\n <0> del space.sent_packets[packet.packet_number]\n <1> \n <2> if packet.is_ack_eliciting:\n <3> space.ack_eliciting_in_flight -= 1\n <4> if packet.in_flight:\n <5> self.bytes_in_flight -= packet.sent_bytes\n <6> \n <7> # trigger callbacks\n <8> for handler, args in packet.delivery_handlers:\n <9> handler(QuicDeliveryState.LOST, *args)\n<10> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: aioquic.quic.packet_builder.QuicSentPacket\n sent_time: Optional[float] = None\n \n sent_bytes: int = 0\n \n at: aioquic.quic.recovery.QuicPacketRecovery.__init__\n self.congestion_window = K_INITIAL_WINDOW\n \n self._congestion_recovery_start_time = 0.0\n \n self._ssthresh: Optional[int] = None\n \n at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost\n self._congestion_recovery_start_time = now\n \n self.congestion_window = max(\n int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW\n )\n \n self._ssthresh = self.congestion_window\n \n \n===========changed ref 0===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_packet_acked(self, packet: QuicSentPacket) -> None:\n self.bytes_in_flight -= packet.sent_bytes\n \n # don't increase window in congestion recovery\n if packet.sent_time <= self._congestion_recovery_start_time:\n return\n \n + if self._ssthresh is None or self.congestion_window < self._ssthresh:\n - if self.congestion_window < self._ssthresh:\n # slow start\n self.congestion_window += packet.sent_bytes\n else:\n # congestion avoidance\n self.congestion_window += (\n K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window\n )\n \n===========changed ref 1===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def __init__(\n + self,\n + is_client_without_1rtt: bool,\n + send_probe: Callable[[], None],\n + quic_logger: Optional[QuicLogger] = None,\n - self, is_client_without_1rtt: bool, send_probe: Callable[[], None]\n ) -> None:\n self.ack_delay_exponent = 3\n self.is_client_without_1rtt = is_client_without_1rtt\n self.max_ack_delay = 25 # ms\n self.spaces: List[QuicPacketSpace] = []\n \n # callbacks\n + self._quic_logger = quic_logger\n self._send_probe = send_probe\n \n # loss detection\n self._pto_count = 0\n self._rtt_initialized = False\n self._rtt_latest = 0.0\n self._rtt_min = math.inf\n self._rtt_smoothed = 0.0\n self._rtt_variance = 0.0\n self._time_of_last_sent_ack_eliciting_packet = 0.0\n \n # congestion control\n self.bytes_in_flight = 0\n self.congestion_window = K_INITIAL_WINDOW\n self._congestion_recovery_start_time = 0.0\n + self._ssthresh: Optional[int] = None\n - self._ssthresh = math.inf\n \n===========changed ref 2===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n \"\"\"\n Update metrics as the result of an ACK being received.\n \"\"\"\n is_ack_eliciting = False\n largest_acked = ack_rangeset.bounds().stop - 1\n largest_newly_acked = None\n largest_sent_time = None\n \n if largest_acked > space.largest_acked_packet:\n space.largest_acked_packet = largest_acked\n \n for packet_number in sorted(space.sent_packets.keys()):\n if packet_number > largest_acked:\n break\n if packet_number in ack_rangeset:\n # remove packet and update counters\n packet = space.sent_packets.pop(packet_number)\n if packet.is_ack_eliciting:\n is_ack_eliciting = True\n space.ack_eliciting_in_flight -= 1\n if packet.in_flight:\n self.on_packet_acked(packet)\n largest_newly_acked = packet_number\n largest_sent_time = packet.sent_time\n \n # trigger callbacks\n for handler, args in packet.delivery_handlers:\n handler(QuicDeliveryState.ACKED, *args)\n \n # nothing to do if there are no newly acked packets\n if largest_newly_acked is None:\n return\n \n if largest_acked == largest_newly_acked and is_ack_eliciting:\n latest_rtt = now - largest_sent_time\n \n # decode ACK delay into seconds\n ack_delay = max(\n (ack_delay_encoded << self.ack_delay_exponent) / 1000000,\n self.max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._\n===========changed ref 3===========\n # module: aioquic.quic.recovery\n class QuicPacketRecovery:\n def on_ack_received(\n self,\n space: QuicPacketSpace,\n ack_rangeset: RangeSet,\n ack_delay_encoded: int,\n now: float,\n ) -> None:\n # offset: 1\n max_ack_delay / 1000,\n )\n \n # update RTT estimate, which cannot be < 1 ms\n self._rtt_latest = max(latest_rtt, 0.001)\n if self._rtt_latest < self._rtt_min:\n self._rtt_min = self._rtt_latest\n if self._rtt_latest > self._rtt_min + ack_delay:\n self._rtt_latest -= ack_delay\n \n if not self._rtt_initialized:\n self._rtt_initialized = True\n self._rtt_variance = latest_rtt / 2\n self._rtt_smoothed = latest_rtt\n else:\n self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs(\n self._rtt_min - self._rtt_latest\n )\n self._rtt_smoothed = (\n 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest\n )\n \n + if self._quic_logger is not None:\n + self._quic_logger.log_event(\n + category=\"recovery\",\n + event=\"metric_update\",\n + data={\n + \"latest_rtt\": int(self._rtt_latest * 1000),\n + \"min_rtt\": int(self._rtt_min * 1000),\n + \"smoothed_rtt\": int(self._rtt_smoothed * 1000),\n + \"rtt_variance\": int(self._rtt_variance * 1000),\n + },\n + )\n + \n self.detect_loss(space, now\n===========changed ref 4===========\n + # module: aioquic.quic.logger\n + \n + \n===========changed ref 5===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def log_event(self, *, category: str, event: str, data: Dict) -> None:\n + self._events.append((time.time(), category, event, data))\n + \n===========changed ref 6===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def __init__(self) -> None:\n + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque()\n + \n===========changed ref 7===========\n + # module: aioquic.quic.logger\n + class QuicLogger:\n + def packet_type(self, packet_type: int) -> str:\n + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, \"1RTT\")\n + "}}},{"rowIdx":3097,"cells":{"path":{"kind":"string","value":"aioquic.quic.connection/QuicConnection.__init__"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":"<13>: self._quic_logger = configuration.quic_logger\n"},"main_code":{"kind":"string","value":" # module: aioquic.quic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n <0> if configuration.is_client:\n <1> assert (\n <2> original_connection_id is None\n <3> ), \"Cannot set original_connection_id for a client\"\n <4> else:\n <5> assert (\n <6> configuration.certificate is not None\n <7> ), \"SSL certificate is required for a server\"\n <8> assert (\n <9> configuration.private_key is not None\n<10> ), \"SSL private key is required for a server\"\n<11> \n<12> # counters for debugging\n<13> self._stateless_retry_count = 0\n<14> self._version_negotiation_count = 0\n<15> \n<16> # configuration\n<17> self._configuration = configuration\n<18> self._is_client = configuration.is_client\n<19> \n<20> self._ack_delay = K_GRANULARITY\n<21> self._close_at: Optional[float] = None\n<22> self._close_event: Optional[events.ConnectionTerminated] = None\n<23> self._connect_called = False\n<24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n<25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}\n<26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}\n<27> self._events: Deque[events.Event] = deque()\n<28> self._handshake_complete = False\n<29> self._handshake_confirmed = False\n<30> self._host_cids = [\n<31> QuicConnectionId(\n<32> cid=os.urandom(8),\n<33> sequence_number=0,\n<34> stateless_reset_token=os.urandom(16),\n<35> was_sent=True,\n<36> )\n<37> ]\n<38> self.host_cid"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 1\n self._host_cid_seq = 1\n self._local_active_connection_id_limit = 8\n self._local_max_data = MAX_DATA_WINDOW\n self._local_max_data_sent = MAX_DATA_WINDOW\n self._local_max_data_used = 0\n self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW\n self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW\n self._local_max_stream_data_uni = MAX_DATA_WINDOW\n self._local_max_streams_bidi = 128\n self._local_max_streams_uni = 128\n self._logger = QuicConnectionAdapter(\n logger, {\"host_cid\": dump_cid(self.host_cid)}\n )\n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client, send_probe=self._send_probe\n )\n self._loss_at: Optional[float] = None\n self._network_paths: List[QuicNetworkPath] = []\n self._original_connection_id = original_connection_id\n self._packet_number = 0\n self._parameters_received = False\n self._peer_cid = os.urandom(8)\n self._peer_cid_seq: Optional[int] = None\n self._peer_cid_available: List[QuicConnectionId] = []\n self._peer_token = b\"\"\n self._remote_active_connection_id_limit = 0\n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self\n===========below chunk 1===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 2\n \n self._remote_idle_timeout = 0.0 # seconds\n self._remote_max_data = 0\n self._remote_max_data_used = 0\n self._remote_max_stream_data_bidi_local = 0\n self._remote_max_stream_data_bidi_remote = 0\n self._remote_max_stream_data_uni = 0\n self._remote_max_streams_bidi = 0\n self._remote_max_streams_uni = 0\n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n self._spin_bit = False\n self._spin_bit_peer = False\n self._spin_highest_pn = 0\n self._state = QuicConnectionState.FIRSTFLIGHT\n self._streams: Dict[int, QuicStream] = {}\n self._streams_blocked_bidi: List[QuicStream] = []\n self._streams_blocked_uni: List[QuicStream] = []\n self._version: Optional[int] = None\n \n # things to send\n self._close_pending = False\n self._ping_pending: List[int] = []\n self._probe_pending = False\n self._retire_connection_ids: List[int] = []\n self._streams_blocked_pending = False\n \n # callbacks\n self._session_ticket_fetcher = session_ticket_fetcher\n self._session_ticket_handler = session_ticket_handler\n \n # frame handlers\n self.__frame_handlers = [\n \n===========below chunk 2===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 3\n ._handle_padding_frame, EPOCHS(\"IZHO\")),\n (self._handle_padding_frame, EPOCHS(\"ZO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_ack_frame, EPOCHS(\"IHO\")),\n (self._handle_reset_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stop_sending_frame, EPOCHS(\"ZO\")),\n (self._handle_crypto_frame, EPOCHS(\"IHO\")),\n (self._handle_new_token_frame, EPOCHS(\"O\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_frame, EPOCHS(\"ZO\")),\n (self._handle_max_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_stream_data_frame, EPOCHS(\"ZO\")),\n (self._handle_max_streams_bidi_frame, EPOCHS(\"ZO\n===========below chunk 3===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def __init__(\n self,\n *,\n configuration: QuicConfiguration,\n original_connection_id: Optional[bytes] = None,\n session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,\n session_ticket_handler: Optional[tls.SessionTicketHandler] = None,\n ) -> None:\n # offset: 4\n \n (self._handle_max_streams_uni_frame, EPOCHS(\"ZO\")),\n (self._handle_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_stream_data_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_streams_blocked_frame, EPOCHS(\"ZO\")),\n (self._handle_new_connection_id_frame, EPOCHS(\"ZO\")),\n (self._handle_retire_connection_id_frame, EPOCHS(\"O\")),\n (self._handle_path_challenge_frame, EPOCHS(\"ZO\")),\n (self._handle_path_response_frame, EPOCHS(\"O\")),\n (self._handle_connection_close_frame, EPOCHS(\"IZHO\")),\n (self._handle_connection_close_frame, EPOCHS(\"ZO\")),\n ]\n \n "}}},{"rowIdx":3098,"cells":{"path":{"kind":"string","value":"aioquic.quic.connection/QuicConnection.datagrams_to_send"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"aad0bcbeab3cbde64ceafd5816a83e0b311f284e"},"commit_message":{"kind":"string","value":"[logger] add initial support for QLOG format"},"ground_truth":{"kind":"string","value":""},"main_code":{"kind":"string","value":" # module: aioquic.quic.connection\n class QuicConnection:\n def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:\n <0> \"\"\"\n <1> Return a list of `(data, addr)` tuples of datagrams which need to be\n <2> sent, and the network address to which they need to be sent.\n <3> \n <4> :param now: The current time.\n <5> \"\"\"\n <6> network_path = self._network_paths[0]\n <7> \n <8> if self._state in END_STATES:\n <9> return []\n<10> \n<11> # build datagrams\n<12> builder = QuicPacketBuilder(\n<13> host_cid=self.host_cid,\n<14> packet_number=self._packet_number,\n<15> pad_first_datagram=(\n<16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT\n<17> ),\n<18> peer_cid=self._peer_cid,\n<19> peer_token=self._peer_token,\n<20> spin_bit=self._spin_bit,\n<21> version=self._version,\n<22> )\n<23> if self._close_pending:\n<24> for epoch, packet_type in (\n<25> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT),\n<26> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),\n<27> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),\n<28> ):\n<29> crypto = self._cryptos[epoch]\n<30> if crypto.send.is_valid():\n<31> builder.start_packet(packet_type, crypto)\n<32> write_close_frame(\n<33> builder=builder,\n<34> error_code=self._close_event.error_code,\n<35> frame_type=self._close_event.frame_type,\n<36> reason_phrase=self._close_event.reason_phrase,\n<37> )\n<38> builder.end_packet()\n<39> self._close_pending = False\n<40> break\n<41> self._close_begin(is_initiator=True, now"},"context":{"kind":"string","value":"===========below chunk 0===========\n # module: aioquic.quic.connection\n class QuicConnection:\n def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:\n # offset: 1\n else:\n # congestion control\n builder.max_flight_bytes = (\n self._loss.congestion_window - self._loss.bytes_in_flight\n )\n if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE:\n builder.max_flight_bytes = PACKET_MAX_SIZE\n \n # limit data on un-validated network paths\n if not network_path.is_validated:\n builder.max_total_bytes = (\n network_path.bytes_received * 3 - network_path.bytes_sent\n )\n \n try:\n if not self._handshake_confirmed:\n for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:\n self._write_handshake(builder, epoch)\n self._write_application(builder, network_path, now)\n except QuicPacketBuilderStop:\n pass\n \n datagrams, packets = builder.flush()\n \n if datagrams:\n self._packet_number = builder.packet_number\n \n # register packets\n sent_handshake = False\n for packet in packets:\n packet.sent_time = now\n self._loss.on_packet_sent(\n packet=packet, space=self._spaces[packet.epoch]\n )\n if packet.epoch == tls.Epoch.HANDSHAKE:\n sent_handshake = True\n \n # check if we can discard initial keys\n if sent_handshake and self._is_client:\n self._discard_epoch(tls.Epoch.INITIAL)\n \n # return datagrams to send and the destination network address\n ret = []\n for datagram in datagrams:\n network_path.bytes_sent += len(datagram)\n ret.append((datagram, network_path.addr))\n return ret\n \n \n===========unchanged ref 0===========\n at: aioquic.quic.configuration.QuicConfiguration\n supported_versions: List[QuicProtocolVersion] = field(\n default_factory=lambda: [QuicProtocolVersion.DRAFT_22]\n )\n \n at: aioquic.quic.connection\n NetworkAddress = Any\n \n write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None\n \n QuicConnectionState()\n \n END_STATES = frozenset(\n [\n QuicConnectionState.CLOSING,\n QuicConnectionState.DRAINING,\n QuicConnectionState.TERMINATED,\n ]\n )\n \n at: aioquic.quic.connection.QuicConnection\n _close_begin(is_initiator: bool, now: float) -> None\n \n _connect(now: float) -> None\n \n _write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float) -> None\n \n _write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None\n \n at: aioquic.quic.connection.QuicConnection.__init__\n self._configuration = configuration\n \n self._is_client = configuration.is_client\n \n self._close_event: Optional[events.ConnectionTerminated] = None\n \n self._cryptos: Dict[tls.Epoch, CryptoPair] = {}\n \n self._handshake_confirmed = False\n \n self.host_cid = self._host_cids[0].cid\n \n self._loss = QuicPacketRecovery(\n is_client_without_1rtt=self._is_client,\n quic_logger=self._quic_logger,\n send_probe=self._send_probe,\n )\n \n self._network_paths: List[QuicNetworkPath] = []\n \n self._packet_number = 0\n \n self._peer_cid = os.urandom(8)\n \n self._peer_token = b\"\"\n \n self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}\n \n \n===========unchanged ref 1===========\n self._spin_bit = False\n \n self._state = QuicConnectionState.FIRSTFLIGHT\n \n self._version: Optional[int] = None\n \n self._close_pending = False\n \n self._probe_pending = False\n \n at: aioquic.quic.connection.QuicConnection._handle_ack_frame\n self._handshake_confirmed = True\n \n at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame\n self._close_event = events.ConnectionTerminated(\n error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase\n )\n \n at: aioquic.quic.connection.QuicConnection._initialize\n self._cryptos = {\n tls.Epoch.INITIAL: CryptoPair(),\n tls.Epoch.ZERO_RTT: CryptoPair(),\n tls.Epoch.HANDSHAKE: CryptoPair(),\n tls.Epoch.ONE_RTT: CryptoPair(),\n }\n \n self._spaces = {\n tls.Epoch.INITIAL: QuicPacketSpace(),\n tls.Epoch.HANDSHAKE: QuicPacketSpace(),\n tls.Epoch.ONE_RTT: QuicPacketSpace(),\n }\n \n self._packet_number = 0\n \n at: aioquic.quic.connection.QuicConnection._send_probe\n self._probe_pending = True\n \n at: aioquic.quic.connection.QuicConnection._set_state\n self._state = state\n \n at: aioquic.quic.connection.QuicConnection._write_application\n self._probe_pending = False\n \n at: aioquic.quic.connection.QuicConnection._write_handshake\n self._probe_pending = False\n \n at: aioquic.quic.connection.QuicConnection.change_connection_id\n self._peer_cid = connection_id.cid\n \n \n===========unchanged ref 2===========\n at: aioquic.quic.connection.QuicConnection.close\n self._close_event = events.ConnectionTerminated(\n error_code=error_code,\n frame_type=frame_type,\n reason_phrase=reason_phrase,\n )\n \n self._close_pending = True\n \n at: aioquic.quic.connection.QuicConnection.connect\n self._network_paths = [QuicNetworkPath(addr, is_validated=True)]\n \n at: aioquic.quic.connection.QuicConnection.handle_timer\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Idle timeout\",\n )\n \n at: aioquic.quic.connection.QuicConnection.receive_datagram\n self._close_event = events.ConnectionTerminated(\n error_code=QuicErrorCode.INTERNAL_ERROR,\n frame_type=None,\n reason_phrase=\"Could not find a common protocol version\",\n )\n \n self._version = QuicProtocolVersion(header.version)\n self._version = QuicProtocolVersion(max(common))\n \n self._peer_cid = header.source_cid\n \n self._peer_token = header.token\n \n self._network_paths = [network_path]\n \n self._spin_bit = self._spin_bit_peer\n self._spin_bit = not self._spin_bit_peer\n \n self.host_cid = context.host_cid\n \n at: aioquic.quic.connection.QuicNetworkPath\n addr: NetworkAddress\n \n bytes_received: int = 0\n \n bytes_sent: int = 0\n \n is_validated: bool = False\n \n local_challenge: Optional[bytes] = None\n \n remote_challenge: Optional[bytes] = None\n \n at: aioquic.quic.crypto.CryptoContext\n is_valid() -> bool\n \n at: aioquic.quic.crypto.CryptoPair.__init__\n self.send = CryptoContext()\n \n "}}},{"rowIdx":3099,"cells":{"path":{"kind":"string","value":"examples.http3-server/handle_http_event"},"type":{"kind":"string","value":"Modified"},"project":{"kind":"string","value":"aiortc~aioquic"},"commit_hash":{"kind":"string","value":"b81fa362ce14f9799e9998fec604c6ce03f357f2"},"commit_message":{"kind":"string","value":"[http3] serve static files from disk"},"ground_truth":{"kind":"string","value":"<11>: content_type=\"text/plain\",\n data=b\"Bad Request\",\n data=render_html(\"Bad Request\"),\n<15>: return\n<16>: # dynamically generated data, maximum 50MB\n<18>: # we accept a maximum of 50MB\n<27>: elif path in [\"/\", \"/index.html\"]:\n<28>: send_response(\n<29>: connection=connection,\n<30>: data=render_html(\"It works!\"),\n<31>: status_code=200,\n<32>: stream_id=event.stream_id,\n<33>: return\n )\n<34>: else:\n<35>: send_response(\n<36>: connection=connection,\n<37>: data=render_html(\"The document could not be found.\"),\n<38>: status_code=404,\n<39>: stream_id=event.stream_id,\n<40>: )\n"},"main_code":{"kind":"string","value":" # module: examples.http3-server\n def handle_http_event(\n connection: HttpConnection, event: aioquic.h3.events.Event\n ) -> None:\n <0> \"\"\"\n <1> Serve HTTP requests.\n <2> \"\"\"\n <3> \n <4> if isinstance(event, RequestReceived):\n <5> headers = dict(event.headers)\n <6> try:\n <7> path = headers[b\":path\"].decode(\"utf8\")\n <8> except (UnicodeDecodeError, ValueError):\n <9> send_response(\n<10> connection=connection,\n<11> data=render_html(\"Bad Request\"),\n<12> status_code=400,\n<13> stream_id=event.stream_id,\n<14> )\n<15> \n<16> size_match = re.match(r\"^/(\\d+)$\", path)\n<17> if size_match:\n<18> # we accept a maximum of 50MB\n<19> size = min(50000000, int(size_match.group(1)))\n<20> send_response(\n<21> connection=connection,\n<22> content_type=\"text/plain\",\n<23> data=b\"Z\" * size,\n<24> status_code=200,\n<25> stream_id=event.stream_id,\n<26> )\n<27> elif path in [\"/\", \"/index.html\"]:\n<28> send_response(\n<29> connection=connection,\n<30> data=render_html(\"It works!\"),\n<31> status_code=200,\n<32> stream_id=event.stream_id,\n<33> )\n<34> else:\n<35> send_response(\n<36> connection=connection,\n<37> data=render_html(\"The document could not be found.\"),\n<38> status_code=404,\n<39> stream_id=event.stream_id,\n<40> )\n<41> \n "},"context":{"kind":"string","value":"===========unchanged ref 0===========\n at: examples.http3-server\n ROOT = os.path.join(os.path.dirname(__file__), \"htdocs\")\n \n send_response(connection: HttpConnection, stream_id: int, data: bytes=b\"\", content_type: str=\"text/html\", status_code: int=200) -> None\n \n at: io.BufferedWriter\n read(self, size: Optional[int]=..., /) -> bytes\n \n at: mimetypes\n guess_type(url: Union[Text, PathLike[str]], strict: bool=...) -> Tuple[Optional[str], Optional[str]]\n \n at: os.path\n join(a: StrPath, *paths: StrPath) -> str\n join(a: BytesPath, *paths: BytesPath) -> bytes\n \n at: re\n match(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]]\n match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]]\n \n at: typing.IO\n __slots__ = ()\n \n read(n: int=...) -> AnyStr\n \n at: typing.Match\n pos: int\n \n endpos: int\n \n lastindex: Optional[int]\n \n lastgroup: Optional[AnyStr]\n \n string: AnyStr\n \n re: Pattern[AnyStr]\n \n group(group1: Union[str, int], group2: Union[str, int], /, *groups: Union[str, int]) -> Tuple[AnyStr, ...]\n group(group: Union[str, int]=..., /) -> AnyStr\n \n \n===========changed ref 0===========\n # module: examples.http3-server\n try:\n import uvloop\n except ImportError:\n uvloop = None\n \n - TEMPLATE = \"\"\"\n - \n - \n - \n - aioquic\n - \n - \n -

Welcome to aioquic

\n -

{content}

\n - \n - \n - \"\"\"\n - \n + ROOT = os.path.join(os.path.dirname(__file__), \"htdocs\")\n \n HttpConnection = Union[H0Connection, H3Connection]\n "}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":30,"numItemsPerPage":100,"numTotalItems":7800,"offset":3000,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzcwMTQzNSwic3ViIjoiL2RhdGFzZXRzL2tyYWFsZmFyL0NvZWRpdG9yLXByb2Nlc3NlZC1kZW1vMiIsImV4cCI6MTc1NzcwNTAzNSwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.8X9g6kn-TZnfKjoOIcaBcm5v5_i5T_JpQz6ANEqKawBTBSZwpGhexJmIIXOimgA551pNQuwAKbl8SK2MryrtCQ","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<26>:<add> self.assertEqual(datagram_sizes(items), [1280, 1079]) <del> self.assertEqual(datagram_sizes(items), [1280, 1071]) <35>:<add> self.assertEqual(datagram_sizes(items), [97]) <del> self.assertEqual(datagram_sizes(items), [95])
# 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 = QuicConnection(configuration=QuicConfiguration(is_client=True)) <4> client._ack_delay = 0 <5> <6> server = QuicConnection( <7> configuration=QuicConfiguration( <8> is_client=False, <9> certificate=SERVER_CERTIFICATE, <10> private_key=SERVER_PRIVATE_KEY, <11> ) <12> ) <13> server._ack_delay = 0 <14> <15> # client sends INITIAL <16> now = 0.0 <17> client.connect(SERVER_ADDR, now=now) <18> items = client.datagrams_to_send(now=now) <19> self.assertEqual(datagram_sizes(items), [1280]) <20> self.assertEqual(client.get_timer(), 1.0) <21> <22> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <23> now = 0.1 <24> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <25> items = server.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280, 1071]) <27> self.assertEqual(server.get_timer(), 1.1) <28> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <29> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <30> <31> #  client only receives first datagram and sends ACKS <32> now = 0.2 <33> client.receive_datagram(items[0][0], SERVER_ADDR, now=now) <34> items = client.datagrams_to_send(now=now) <35> self.assertEqual(datagram_sizes(items), [95]) <36> self.assertAlmostEqual(client</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 #  client PTO - padded HANDSHAKE now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 1.25) # server receives padding, discards INITIAL 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), []) 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), 2) # 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, 893]) 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), 2) # 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</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s> items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [326]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted)) 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), [221]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted)) 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: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.connection.QuicConnection.__init__ self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) sequence_numbers(connection_ids) transfer(sender, receiver) at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_2 datagram_sizes(items) client = QuicConnection(configuration=QuicConfiguration(is_client=True)) server = QuicConnection( configuration=QuicConfiguration( is_client=False, certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, ) ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========unchanged ref 1=========== 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_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event())
tests.test_connection/QuicConnectionTest.test_receive_datagram_retry
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<4>:<add> version=QuicProtocolVersion.DRAFT_22, <del> version=QuicProtocolVersion.DRAFT_20,
# 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=QuicProtocolVersion.DRAFT_20, <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: aioquic.connection.QuicConnection receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.connection.QuicConnection.__init__ self._peer_cid = os.urandom(8) at: aioquic.connection.QuicConnection.change_connection_id self._peer_cid = connection_id.cid at: aioquic.connection.QuicConnection.receive_datagram self._peer_cid = header.source_cid at: aioquic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) encode_quic_retry(version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes) -> bytes at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_connection SERVER_ADDR = ("2.3.4.5", 4433) create_standalone_client(self) at: time time() -> float ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet def encode_quic_retry( version: int, source_cid: bytes, destination_cid: bytes, original_destination_cid: bytes, retry_token: bytes, ) -> bytes: buf = Buffer( + capacity=8 - capacity=6 + len(destination_cid) + len(source_cid) + len(original_destination_cid) + len(retry_token) ) + buf.push_uint8(PACKET_TYPE_RETRY) - buf.push_uint8(PACKET_TYPE_RETRY | encode_cid_length(len(original_destination_cid))) buf.push_uint32(version) - buf.push_uint8( - (encode_cid_length(len(destination_cid)) << 4) - | encode_cid_length(len(source_cid)) - ) + buf.push_uint8(len(destination_cid)) buf.push_bytes(destination_cid) + buf.push_uint8(len(source_cid)) buf.push_bytes(source_cid) + buf.push_uint8(len(original_destination_cid)) buf.push_bytes(original_destination_cid) buf.push_bytes(retry_token) return buf.data ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect(self): + with client_and_server() as (client, server): + # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) + self.assertIsNone(client.next_event()) + + event = server.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) + self.assertIsNone(server.next_event()) + + # check each endpoint has available connection IDs for the peer + self.assertEqual( + sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + self.assertEqual( + sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + + # client closes the connection + client.close() + self.assertEqual(transfer(client, server), 1) + + # check connection closes on the client side + client.handle_timer(client.get_timer()) + event = client.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual</s>
tests.test_connection/QuicConnectionTest.test_receive_datagram_retry_wrong_destination_cid
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<4>:<add> version=QuicProtocolVersion.DRAFT_22, <del> version=QuicProtocolVersion.DRAFT_20,
# 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=QuicProtocolVersion.DRAFT_20, <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: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection.QuicConnection _handle_ack_frame(context: QuicReceiveContext, frame_type: int, buf: Buffer) -> None at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) create_standalone_client(self) client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_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_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 4=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 5=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect(self): + with client_and_server() as (client, server): + # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) + self.assertIsNone(client.next_event()) + + event = server.next_event() + self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, None) + self.assertEqual(event.early_data_accepted, False) + self.assertEqual(event.session_resumed, False) + for i in range(7): + self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) + self.assertIsNone(server.next_event()) + + # check each endpoint has available connection IDs for the peer + self.assertEqual( + sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + self.assertEqual( + sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] + ) + + # client closes the connection + client.close() + self.assertEqual(transfer(client, server), 1) + + # check connection closes on the client side + client.handle_timer(client.get_timer()) + event = client.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual</s> ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): + def test_connect(self): # offset: 1 <s> client.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.frame_type, None) + self.assertEqual(event.reason_phrase, "") + self.assertIsNone(client.next_event()) + + # check connection closes on the server side + server.handle_timer(server.get_timer()) + event = server.next_event() + self.assertEqual(type(event), events.ConnectionTerminated) + self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) + self.assertEqual(event.frame_type, None) + self.assertEqual(event.reason_phrase, "") + self.assertIsNone(server.next_event()) + ===========changed ref 8=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase)
tests.test_connection/QuicConnectionTest.test_handle_reset_stream_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<8>:<add> Buffer(data=binascii.unhexlify("001100")), <del> Buffer(data=binascii.unhexlify("00112200")),
# 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> <4> # client receives RESET_STREAM <5> client._handle_reset_stream_frame( <6> client_receive_context(client), <7> QuicFrameType.RESET_STREAM, <8> Buffer(data=binascii.unhexlify("00112200")), <9> ) <10>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_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_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 5=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 6=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 7=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 8=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 9=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 10=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase)
tests.test_connection/QuicConnectionTest.test_handle_reset_stream_frame_send_only
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<9>:<add> Buffer(data=binascii.unhexlify("021100")), <del> Buffer(data=binascii.unhexlify("02112200")),
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame_send_only(self): <0> with client_and_server() as (client, server): <1> # client creates unidirectional stream 2 <2> client.send_stream_data(stream_id=2, data=b"hello") <3> <4> # client receives RESET_STREAM <5> with self.assertRaises(QuicConnectionError) as cm: <6> client._handle_reset_stream_frame( <7> client_receive_context(client), <8> QuicFrameType.RESET_STREAM, <9> Buffer(data=binascii.unhexlify("02112200")), <10> ) <11> self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) <12> self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) <13> self.assertEqual(cm.exception.reason_phrase, "Stream is send-only") <14>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) sequence_numbers(connection_ids) 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_reset_stream_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("001100")), - Buffer(data=binascii.unhexlify("00112200")), ) ===========changed ref 1=========== # 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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========changed ref 2=========== # 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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 6=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 7=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 8=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 9=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 10=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 11=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase)
tests.test_connection/QuicConnectionTest.test_handle_stop_sending_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<8>:<add> Buffer(data=b"\x00\x11"), <del> Buffer(data=b"\x00\x11\x22"),
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_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> <4> # client receives STOP_SENDING <5> client._handle_stop_sending_frame( <6> client_receive_context(client), <7> QuicFrameType.STOP_SENDING, <8> Buffer(data=b"\x00\x11\x22"), <9> ) <10>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("001100")), - Buffer(data=binascii.unhexlify("00112200")), ) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame_send_only(self): with client_and_server() as (client, server): # client creates unidirectional stream 2 client.send_stream_data(stream_id=2, data=b"hello") # client receives RESET_STREAM with self.assertRaises(QuicConnectionError) as cm: client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("021100")), - Buffer(data=binascii.unhexlify("02112200")), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) self.assertEqual(cm.exception.reason_phrase, "Stream is send-only") ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), 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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_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_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 7=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 8=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 9=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 10=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016
tests.test_connection/QuicConnectionTest.test_handle_stop_sending_frame_receive_only
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<9>:<add> Buffer(data=b"\x03\x11"), <del> Buffer(data=b"\x03\x11\x22"),
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_frame_receive_only(self): <0> with client_and_server() as (client, server): <1> # server creates unidirectional stream 3 <2> server.send_stream_data(stream_id=3, data=b"hello") <3> <4> # client receives STOP_SENDING <5> with self.assertRaises(QuicConnectionError) as cm: <6> client._handle_stop_sending_frame( <7> client_receive_context(client), <8> QuicFrameType.STOP_SENDING, <9> Buffer(data=b"\x03\x11\x22"), <10> ) <11> self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) <12> self.assertEqual(cm.exception.frame_type, QuicFrameType.STOP_SENDING) <13> self.assertEqual(cm.exception.reason_phrase, "Stream is receive-only") <14>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.buffer encode_uint_var(value: int) -> bytes at: aioquic.connection QuicConnectionError(error_code: int, frame_type: int, reason_phrase: str) at: aioquic.packet QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: tests.test_connection client_receive_context(client, epoch=tls.Epoch.ONE_RTT) client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: unittest.case.TestCase 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_stop_sending_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives STOP_SENDING client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x00\x11"), - Buffer(data=b"\x00\x11\x22"), ) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("001100")), - Buffer(data=binascii.unhexlify("00112200")), ) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame_send_only(self): with client_and_server() as (client, server): # client creates unidirectional stream 2 client.send_stream_data(stream_id=2, data=b"hello") # client receives RESET_STREAM with self.assertRaises(QuicConnectionError) as cm: client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("021100")), - Buffer(data=binascii.unhexlify("02112200")), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) self.assertEqual(cm.exception.reason_phrase, "Stream is send-only") ===========changed ref 3=========== # 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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 0) ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_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_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( + client_options={"alpn_protocols": ["hq-22", "h3-22"]}, - client_options={"alpn_protocols": ["hq-20", "h3-20"]}, + server_options={"alpn_protocols": ["hq-22"]}, - server_options={"alpn_protocols": ["hq-20"]}, ) as (client, server): # check handshake completed event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) + self.assertEqual(event.alpn_protocol, "hq-22") - self.assertEqual(event.alpn_protocol, "hq-20") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) ===========changed ref 8=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 9=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 -
tests.test_connection/QuicConnectionTest.test_payload_received_malformed_frame
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> # client receives malformed TRANSPORT_CLOSE frame <del> # client receives malformed frame <4>:<add> client_receive_context(client), b"\x1c\x00\x01" <del> client_receive_context(client), b"\x1c\x00\x01\x00"
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_payload_received_malformed_frame(self): <0> with client_and_server() as (client, server): <1> # client receives malformed frame <2> with self.assertRaises(QuicConnectionError) as cm: <3> client._payload_received( <4> client_receive_context(client), b"\x1c\x00\x01\x00" <5> ) <6> self.assertEqual( <7> cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR <8> ) <9> self.assertEqual(cm.exception.frame_type, 0x1C) <10> self.assertEqual(cm.exception.reason_phrase, "Failed to parse frame") <11>
===========unchanged ref 0=========== at: aioquic.events PingAcknowledged(uid: int) at: tests.test_connection consume_events(connection) 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_stop_sending_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives STOP_SENDING client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x00\x11"), - Buffer(data=b"\x00\x11\x22"), ) ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("001100")), - Buffer(data=binascii.unhexlify("00112200")), ) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_frame_receive_only(self): with client_and_server() as (client, server): # server creates unidirectional stream 3 server.send_stream_data(stream_id=3, data=b"hello") # client receives STOP_SENDING with self.assertRaises(QuicConnectionError) as cm: client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x03\x11"), - Buffer(data=b"\x03\x11\x22"), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.STOP_SENDING) self.assertEqual(cm.exception.reason_phrase, "Stream is receive-only") ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame_send_only(self): with client_and_server() as (client, server): # client creates unidirectional stream 2 client.send_stream_data(stream_id=2, data=b"hello") # client receives RESET_STREAM with self.assertRaises(QuicConnectionError) as cm: client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("021100")), - Buffer(data=binascii.unhexlify("02112200")), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) self.assertEqual(cm.exception.reason_phrase, "Stream is send-only") ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), 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_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( + version=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 8=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 9=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 10=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 11=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 12=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token)
tests.test_connection/QuicConnectionTest.test_version_negotiation_ok
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<7>:<add> supported_versions=[QuicProtocolVersion.DRAFT_22], <del> supported_versions=[QuicProtocolVersion.DRAFT_19],
# 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=[QuicProtocolVersion.DRAFT_19], <8> ), <9> SERVER_ADDR, <10> now=time.time(), <11> ) <12> self.assertEqual(drop(client), 1) <13>
===========unchanged ref 0=========== at: aioquic.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.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 can_send(size: int) -> bool at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase assertTrue(expr: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_payload_received_malformed_frame(self): with client_and_server() as (client, server): + # client receives malformed TRANSPORT_CLOSE frame - # client receives malformed frame with self.assertRaises(QuicConnectionError) as cm: client._payload_received( + client_receive_context(client), b"\x1c\x00\x01" - client_receive_context(client), b"\x1c\x00\x01\x00" ) self.assertEqual( cm.exception.error_code, QuicErrorCode.FRAME_ENCODING_ERROR ) self.assertEqual(cm.exception.frame_type, 0x1C) self.assertEqual(cm.exception.reason_phrase, "Failed to parse frame") ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives STOP_SENDING client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x00\x11"), - Buffer(data=b"\x00\x11\x22"), ) ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives RESET_STREAM client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("001100")), - Buffer(data=binascii.unhexlify("00112200")), ) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_frame_receive_only(self): with client_and_server() as (client, server): # server creates unidirectional stream 3 server.send_stream_data(stream_id=3, data=b"hello") # client receives STOP_SENDING with self.assertRaises(QuicConnectionError) as cm: client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x03\x11"), - Buffer(data=b"\x03\x11\x22"), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.STOP_SENDING) self.assertEqual(cm.exception.reason_phrase, "Stream is receive-only") ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_reset_stream_frame_send_only(self): with client_and_server() as (client, server): # client creates unidirectional stream 2 client.send_stream_data(stream_id=2, data=b"hello") # client receives RESET_STREAM with self.assertRaises(QuicConnectionError) as cm: client._handle_reset_stream_frame( client_receive_context(client), QuicFrameType.RESET_STREAM, + Buffer(data=binascii.unhexlify("021100")), - Buffer(data=binascii.unhexlify("02112200")), ) self.assertEqual(cm.exception.error_code, QuicErrorCode.STREAM_STATE_ERROR) self.assertEqual(cm.exception.frame_type, QuicFrameType.RESET_STREAM) self.assertEqual(cm.exception.reason_phrase, "Stream is send-only") ===========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=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=binascii.unhexlify("c98343fe8f5f0ff4"), 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_retry(self): client = create_standalone_client(self) client.receive_datagram( encode_quic_retry( + version=QuicProtocolVersion.DRAFT_22, - version=QuicProtocolVersion.DRAFT_20, source_cid=binascii.unhexlify("85abb547bf28be97"), destination_cid=client.host_cid, original_destination_cid=client._peer_cid, retry_token=bytes(16), ), SERVER_ADDR, now=time.time(), ) self.assertEqual(drop(client), 1) ===========changed ref 7=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 8=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 9=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 10=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) -
tests.test_h3/H3ConnectionTest.test_connect
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> client_options={"alpn_protocols": ["h3-22"]}, <del> client_options={"alpn_protocols": ["h3-20"]}, <2>:<add> server_options={"alpn_protocols": ["h3-22"]}, <del> server_options={"alpn_protocols": ["h3-20"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-20"]}, <2> server_options={"alpn_protocols": ["h3-20"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> ) <18> h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19> <20> # receive request <21> events = h3_transfer(quic_client, h3_server) <22> self.assertEqual(len(events), 2) <23> <24> self.assertTrue(isinstance(events[0], RequestReceived)) <25> self.assertEqual( <26> events[0].headers, <27> [ <28> (b":method", b"GET"), <29> (b":scheme", b"https"), <30> (b":authority", b"localhost"), <31> (b":path", b"/"), <32> ], <33> ) <34> self.assertEqual(events[0].stream_id, stream_id) <35> self.assertEqual(events[0].stream_ended, False) <36> <37> self.assertTrue(isinstance(events[1], DataReceived)) <38> self.assertEqual(events[1].data, b"") <39> self.assertEqual(events[1].stream_id,</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) 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"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 1=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 4=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 5=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 6=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 7=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 8=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id) ===========changed ref 9=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]: sequence_number = buf.pull_uint_var() + retire_prior_to = buf.pull_uint_var() length = buf.pull_uint8() connection_id = buf.pull_bytes(length) stateless_reset_token = buf.pull_bytes(16) + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 10=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_handle_stop_sending_frame(self): with client_and_server() as (client, server): # client creates bidirectional stream 0 client.send_stream_data(stream_id=0, data=b"hello") # client receives STOP_SENDING client._handle_stop_sending_frame( client_receive_context(client), QuicFrameType.STOP_SENDING, + Buffer(data=b"\x00\x11"), - Buffer(data=b"\x00\x11\x22"), )
tests.test_h3/H3ConnectionTest.test_uni_stream_type
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> client_options={"alpn_protocols": ["h3-22"]}, <del> client_options={"alpn_protocols": ["h3-20"]}, <2>:<add> server_options={"alpn_protocols": ["h3-22"]}, <del> server_options={"alpn_protocols": ["h3-20"]},
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-20"]}, <2> server_options={"alpn_protocols": ["h3-20"]}, <3> ) as (quic_client, quic_server): <4> h3_server = H3Connection(quic_server) <5> <6> # unknown stream type 9 <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <8> self.assertEqual(stream_id, 2) <9> quic_client.send_stream_data(stream_id, b"\x09") <10> self.assertEqual(h3_transfer(quic_client, h3_server), []) <11> self.assertEqual(h3_server._stream_buffers, {2: b""}) <12> self.assertEqual(h3_server._stream_types, {2: 9}) <13> <14> # unknown stream type 64, one byte at a time <15> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <16> self.assertEqual(stream_id, 6) <17> <18> quic_client.send_stream_data(stream_id, b"\x40") <19> self.assertEqual(h3_transfer(quic_client, h3_server), []) <20> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b"\x40"}) <21> self.assertEqual(h3_server._stream_types, {2: 9}) <22> <23> quic_client.send_stream_data(stream_id, b"\x40") <24> self.assertEqual(h3_transfer(quic_client, h3_server), []) <25> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b""}) <26> self.assertEqual</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): # offset: 1 ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): with client_and_server( + client_options={"alpn_protocols": ["h3-22"]}, - client_options={"alpn_protocols": ["h3-20"]}, + server_options={"alpn_protocols": ["h3-22"]}, - server_options={"alpn_protocols": ["h3-20"]}, ) as (quic_client, quic_server): h3_client = H3Connection(quic_client) h3_server = H3Connection(quic_server) # send request stream_id = quic_client.get_next_available_stream_id() h3_client.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], ) h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) # receive request events = h3_transfer(quic_client, h3_server) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], RequestReceived)) self.assertEqual( events[0].headers, [ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), ], ) 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_</s> ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 <s>)) self.assertEqual(events[1].data, b"") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) 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"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========changed ref 2=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 3=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 4=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 6=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 7=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 8=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 9=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase)
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<12>:<add> if event.alpn_protocol == "h3-22": <del> if event.alpn_protocol == "h3-20": <14>:<add> elif event.alpn_protocol == "hq-22": <del> elif event.alpn_protocol == "hq-20":
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.events.ConnectionTerminated): <4> # remove the connection <5> for cid, conn in list(self._connections.items()): <6> if conn == connection: <7> del self._connections[cid] <8> self._http.pop(connection, None) <9> self._timer.pop(connection, None) <10> return <11> elif isinstance(event, aioquic.events.HandshakeCompleted): <12> if event.alpn_protocol == "h3-20": <13> self._http[connection] = H3Connection(connection) <14> elif event.alpn_protocol == "hq-20": <15> self._http[connection] = H0Connection(connection) <16> elif isinstance(event, aioquic.events.ConnectionIdIssued): <17> self._connections[event.connection_id] = connection <18> elif isinstance(event, aioquic.events.ConnectionIdRetired): <19> assert self._connections[event.connection_id] == connection <20> del self._connections[event.connection_id] <21> <22> #  pass event to the HTTP layer <23> http = self._http.get(connection) <24> if http is not None: <25> for http_event in http.handle_event(event): <26> handle_http_event(http, http_event) <27> <28> event = connection.next_event() <29> <30> # send datagrams <31> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <32> self._transport.sendto(data, addr) <33> <34> # re-arm timer <35> next_timer_at = connection.get_timer() <36> (timer, timer_at) = self._timer.get(connection, (None, None)) <37> if timer is not None and timer</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 timer.cancel() timer = None if timer is None and timer_at is not None: timer = self._loop.call_at( next_timer_at, partial(self._handle_timer, connection) ) self._timer[connection] = (timer, next_timer_at) ===========unchanged ref 0=========== at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.Event] at: aioquic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] at: asyncio.events.AbstractEventLoop call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server H0Connection(quic: QuicConnection) handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None at: examples.http3-server.H0Connection handle_event(event: aioquic.events.Event) at: examples.http3-server.HttpServer _handle_timer(connection: QuicConnection) -> None ===========unchanged ref 1=========== at: examples.http3-server.HttpServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() 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.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 1=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 2=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 4=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 5=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 6=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 7=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 8=========== # module: aioquic.connection class QuicConnection: def _handle_stop_sending_frame( self, context: QuicReceiveContext, frame_type: int, buf: Buffer ) -> None: """ Handle a STOP_SENDING frame. """ stream_id = buf.pull_uint_var() + buf.pull_uint_var() # application error code - buf.pull_uint16() # application error code # check stream direction self._assert_stream_can_send(frame_type, stream_id) self._get_or_create_stream(frame_type, stream_id)
tests.test_packet/PacketTest.test_pull_initial_client
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<3>:<add> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) <del> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) <5>:<add> self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) <del> self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) <9>:<add> self.assertEqual(header.rest_length, 1262) <del> self.assertEqual(header.rest_length, 1263) <10>:<add> self.assertEqual(buf.tell(), 18) <del> self.assertEqual(buf.tell(), 17)
# module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): <0> buf = Buffer(data=load("initial_client.bin")) <1> header = pull_quic_header(buf, host_cid_length=8) <2> self.assertTrue(header.is_long_header) <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) <4> self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) <5> self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) <6> self.assertEqual(header.source_cid, b"") <7> self.assertEqual(header.original_destination_cid, b"") <8> self.assertEqual(header.token, b"") <9> self.assertEqual(header.rest_length, 1263) <10> self.assertEqual(buf.tell(), 17) <11>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer tell() -> int at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader at: aioquic.packet.QuicHeader is_long_header: bool version: Optional[int] packet_type: int destination_cid: bytes source_cid: bytes original_destination_cid: bytes = b"" token: bytes = b"" rest_length: int = 0 at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s> ===========changed ref 2=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 <s> else: rest_length = buf.pull_uint_var() return QuicHeader( is_long_header=True, version=version, packet_type=packet_type, destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), ) ===========changed ref 3=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 4=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 5=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 7=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 8=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 9=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase)
tests.test_packet/PacketTest.test_pull_initial_server
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<3>:<add> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) <del> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) <6>:<add> self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) <del> self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) <9>:<add> self.assertEqual(header.rest_length, 184) <del> self.assertEqual(header.rest_length, 182) <10>:<add> self.assertEqual(buf.tell(), 18) <del> self.assertEqual(buf.tell(), 17)
# module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): <0> buf = Buffer(data=load("initial_server.bin")) <1> header = pull_quic_header(buf, host_cid_length=8) <2> self.assertTrue(header.is_long_header) <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) <4> self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) <5> self.assertEqual(header.destination_cid, b"") <6> self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) <7> self.assertEqual(header.original_destination_cid, b"") <8> self.assertEqual(header.token, b"") <9> self.assertEqual(header.rest_length, 182) <10> self.assertEqual(buf.tell(), 17) <11>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer tell() -> int at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s> ===========changed ref 2=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 <s> else: rest_length = buf.pull_uint_var() return QuicHeader( is_long_header=True, version=version, packet_type=packet_type, destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), ) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 4=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 5=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 6=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 8=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 9=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token)
tests.test_packet/PacketTest.test_pull_retry
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<3>:<add> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) <del> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19) <5>:<add> self.assertEqual(header.destination_cid, binascii.unhexlify("fee746dfde699d61")) <del> self.assertEqual(header.destination_cid, binascii.unhexlify("c98343fe8f5f0ff4")) <6>:<add> self.assertEqual(header.source_cid, binascii.unhexlify("59aa0942fd2f11e9")) <7>:<del> header.source_cid, <8>:<del> binascii.unhexlify("c17f7c0473e635351b85a17e9f3296d7246c"), <9>:<del> ) <10>:<del> self.assertEqual( <11>:<add> header.original_destination_cid, binascii.unhexlify("d61e7448e0d63dff") <del> header.original_destination_cid, binascii.unhexlify("85abb547bf28be97") <16>:<add> "5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764" <del> "01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97" <20>:<add> self.assertEqual(buf.tell(), 73) <del> self.assertEqual(buf.tell(), 69)
# module: tests.test_packet class PacketTest(TestCase): def test_pull_retry(self): <0> buf = Buffer(data=load("retry.bin")) <1> header = pull_quic_header(buf, host_cid_length=8) <2> self.assertTrue(header.is_long_header) <3> self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19) <4> self.assertEqual(header.packet_type, PACKET_TYPE_RETRY) <5> self.assertEqual(header.destination_cid, binascii.unhexlify("c98343fe8f5f0ff4")) <6> self.assertEqual( <7> header.source_cid, <8> binascii.unhexlify("c17f7c0473e635351b85a17e9f3296d7246c"), <9> ) <10> self.assertEqual( <11> header.original_destination_cid, binascii.unhexlify("85abb547bf28be97") <12> ) <13> self.assertEqual( <14> header.token, <15> binascii.unhexlify( <16> "01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97" <17> ), <18> ) <19> self.assertEqual(header.rest_length, 0) <20> self.assertEqual(buf.tell(), 69) <21>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer tell() -> int at: aioquic.packet PACKET_TYPE_RETRY = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x30 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s> ===========changed ref 2=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 <s> else: rest_length = buf.pull_uint_var() return QuicHeader( is_long_header=True, version=version, packet_type=packet_type, destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), ) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 5=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 6=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) -
tests.test_packet/PacketTest.test_pull_version_negotiation
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<5>:<add> self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) <del> self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) <6>:<add> self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) <del> self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) <10>:<add> self.assertEqual(buf.tell(), 23) <del> self.assertEqual(buf.tell(), 22)
# module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): <0> buf = Buffer(data=load("version_negotiation.bin")) <1> header = pull_quic_header(buf, host_cid_length=8) <2> self.assertTrue(header.is_long_header) <3> self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) <4> self.assertEqual(header.packet_type, None) <5> self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) <6> self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) <7> self.assertEqual(header.original_destination_cid, b"") <8> self.assertEqual(header.token, b"") <9> self.assertEqual(header.rest_length, 8) <10> self.assertEqual(buf.tell(), 22) <11>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer tell() -> int at: aioquic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_packet.PacketTest.test_pull_version_negotiation buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 2=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_retry(self): buf = Buffer(data=load("retry.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19) self.assertEqual(header.packet_type, PACKET_TYPE_RETRY) + self.assertEqual(header.destination_cid, binascii.unhexlify("fee746dfde699d61")) - self.assertEqual(header.destination_cid, binascii.unhexlify("c98343fe8f5f0ff4")) + self.assertEqual(header.source_cid, binascii.unhexlify("59aa0942fd2f11e9")) self.assertEqual( - header.source_cid, - binascii.unhexlify("c17f7c0473e635351b85a17e9f3296d7246c"), - ) - self.assertEqual( + header.original_destination_cid, binascii.unhexlify("d61e7448e0d63dff") - header.original_destination_cid, binascii.unhexlify("85abb547bf28be97") ) self.assertEqual( header.token, binascii.unhexlify( + "5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764" - "01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97" ), ) self.assertEqual(header.rest_length, 0) + </s> ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_retry(self): # offset: 1 <s>7bf28be97" ), ) self.assertEqual(header.rest_length, 0) + self.assertEqual(buf.tell(), 73) - self.assertEqual(buf.tell(), 69) ===========changed ref 5=========== # module: aioquic.packet - def encode_cid_length(length: int) -> int: - return length - 3 if length else 0 - ===========changed ref 6=========== # module: aioquic.packet - def decode_cid_length(length: int) -> int: - return length + 3 if length else 0 - ===========changed ref 7=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_20(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_20], - server_versions=[QuicProtocolVersion.DRAFT_20], - ) - ===========changed ref 8=========== # module: tests.test_connection class QuicConnectionTest(TestCase): - def test_connect_draft_19(self): - self._test_connect_with_version( - client_versions=[QuicProtocolVersion.DRAFT_19], - server_versions=[QuicProtocolVersion.DRAFT_19], - ) - ===========changed ref 9=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase)
tests.test_packet/PacketTest.test_pull_long_header_no_fixed_bit
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") <del> buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00")
# module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): <0> buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") <1> with self.assertRaises(ValueError) as cm: <2> pull_quic_header(buf, host_cid_length=8) <3> self.assertEqual(str(cm.exception), "Packet fixed bit is zero") <4>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet pull_quic_header(buf: Buffer, host_cid_length: Optional[int]=None) -> QuicHeader at: tests.test_packet.PacketTest.test_pull_long_header_no_fixed_bit buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: first_byte = buf.pull_uint8() original_destination_cid = b"" token = b"" if is_long_header(first_byte): # long header packet version = buf.pull_uint32() - cid_lengths = buf.pull_uint8() + destination_cid_length = buf.pull_uint8() - destination_cid_length = decode_cid_length(cid_lengths // 16) destination_cid = buf.pull_bytes(destination_cid_length) + source_cid_length = buf.pull_uint8() - source_cid_length = decode_cid_length(cid_lengths % 16) source_cid = buf.pull_bytes(source_cid_length) if version == QuicProtocolVersion.NEGOTIATION: # version negotiation packet_type = None rest_length = buf.capacity - buf.tell() else: if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK if packet_type == PACKET_TYPE_INITIAL: token_length = buf.pull_uint_var() token = buf.pull_bytes(token_length) rest_length = buf.pull_uint_var() elif packet_type == PACKET_TYPE_RETRY: + original_destination_cid_length = buf.pull_uint8() - original_destination_cid_length = decode_cid_length(first_byte & 0xF) original_destination_cid = buf.pull_bytes( original_destination_cid_length ) token = buf.pull_bytes(buf.capacity - buf.tell()) rest_length = 0 else: rest_length = buf.pull_uint_var() return QuicHeader( is_</s> ===========changed ref 1=========== # module: aioquic.packet def pull_quic_header(buf: Buffer, host_cid_length: Optional[int] = None) -> QuicHeader: # offset: 1 <s> else: rest_length = buf.pull_uint_var() return QuicHeader( is_long_header=True, version=version, packet_type=packet_type, destination_cid=destination_cid, source_cid=source_cid, original_destination_cid=original_destination_cid, token=token, rest_length=rest_length, ) else: # short header packet if not (first_byte & PACKET_FIXED_BIT): raise ValueError("Packet fixed bit is zero") packet_type = first_byte & PACKET_TYPE_MASK destination_cid = buf.pull_bytes(host_cid_length) return QuicHeader( is_long_header=False, version=None, packet_type=packet_type, destination_cid=destination_cid, source_cid=b"", token=b"", rest_length=buf.capacity - buf.tell(), ) ===========changed ref 2=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17)
tests.test_packet/PacketTest.test_encode_quic_version_negotiation
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> destination_cid=binascii.unhexlify("9aac5a49ba87a849"), <del> destination_cid=binascii.unhexlify("dae1889b81a91c26"), <2>:<add> source_cid=binascii.unhexlify("f92f4336fa951ba1"), <del> source_cid=binascii.unhexlify("f49243784f9bf3be"), <3>:<add> supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], <del> supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A],
# module: tests.test_packet class PacketTest(TestCase): def test_encode_quic_version_negotiation(self): <0> data = encode_quic_version_negotiation( <1> destination_cid=binascii.unhexlify("dae1889b81a91c26"), <2> source_cid=binascii.unhexlify("f49243784f9bf3be"), <3> supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A], <4> ) <5> self.assertEqual(data[1:], load("version_negotiation.bin")[1:]) <6>
===========unchanged ref 0=========== at: aioquic.packet QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_packet.PacketTest.test_encode_quic_version_negotiation data = encode_quic_version_negotiation( destination_cid=binascii.unhexlify("9aac5a49ba87a849"), source_cid=binascii.unhexlify("f92f4336fa951ba1"), supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], ) at: tests.utils load(name) at: unittest.case TestCase(methodName: str=...) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): + buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") - buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") with self.assertRaises(ValueError) as cm: pull_quic_header(buf, host_cid_length=8) self.assertEqual(str(cm.exception), "Packet fixed bit is zero") ===========changed ref 2=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 5=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_retry(self): buf = Buffer(data=load("retry.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_19) self.assertEqual(header.packet_type, PACKET_TYPE_RETRY) + self.assertEqual(header.destination_cid, binascii.unhexlify("fee746dfde699d61")) - self.assertEqual(header.destination_cid, binascii.unhexlify("c98343fe8f5f0ff4")) + self.assertEqual(header.source_cid, binascii.unhexlify("59aa0942fd2f11e9")) self.assertEqual( - header.source_cid, - binascii.unhexlify("c17f7c0473e635351b85a17e9f3296d7246c"), - ) - self.assertEqual( + header.original_destination_cid, binascii.unhexlify("d61e7448e0d63dff") - header.original_destination_cid, binascii.unhexlify("85abb547bf28be97") ) self.assertEqual( header.token, binascii.unhexlify( + "5282f57f85a1a5c50de5aac2ff7dba43ff34524737099ec41c4b8e8c76734f935e8efd51177dbbe764" - "01652d68d17c8e9f968d4fb4b70c9e526c4f837dbd85abb547bf28be97" ), ) self.assertEqual(header.rest_length, 0) + </s>
tests.test_packet/FrameTest.test_new_connection_id
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<1>:<add> "0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" <del> "02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" <11>:<add> 0,
# module: tests.test_packet class FrameTest(TestCase): def test_new_connection_id(self): <0> data = binascii.unhexlify( <1> "02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" <2> ) <3> <4> # parse <5> buf = Buffer(data=data) <6> frame = packet.pull_new_connection_id_frame(buf) <7> self.assertEqual( <8> frame, <9> ( <10> 2, <11> binascii.unhexlify("7813f3d9e45e0cacbb491b4b66b039f204"), <12> binascii.unhexlify("06f68fede38ec4c31aba8ab1245244e8"), <13> ), <14> ) <15> <16> # serialize <17> buf = Buffer(capacity=len(data)) <18> packet.push_new_connection_id_frame(buf, *frame) <19> self.assertEqual(buf.data, data) <20>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes] push_new_connection_id_frame(buf: Buffer, sequence_number: int, retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes) -> None at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.test_packet.FrameTest.test_new_connection_id data = binascii.unhexlify( "0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet def push_new_connection_id_frame( buf: Buffer, sequence_number: int, + retire_prior_to: int, connection_id: bytes, stateless_reset_token: bytes, ) -> None: assert len(stateless_reset_token) == 16 buf.push_uint_var(sequence_number) + buf.push_uint_var(retire_prior_to) buf.push_uint8(len(connection_id)) buf.push_bytes(connection_id) buf.push_bytes(stateless_reset_token) ===========changed ref 1=========== # module: aioquic.packet + def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, int, bytes, bytes]: - def pull_new_connection_id_frame(buf: Buffer) -> Tuple[int, bytes, bytes]: sequence_number = buf.pull_uint_var() + retire_prior_to = buf.pull_uint_var() length = buf.pull_uint8() connection_id = buf.pull_bytes(length) stateless_reset_token = buf.pull_bytes(16) + return (sequence_number, retire_prior_to, connection_id, stateless_reset_token) - return (sequence_number, connection_id, stateless_reset_token) ===========changed ref 2=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): + buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") - buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") with self.assertRaises(ValueError) as cm: pull_quic_header(buf, host_cid_length=8) self.assertEqual(str(cm.exception), "Packet fixed bit is zero") ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_encode_quic_version_negotiation(self): data = encode_quic_version_negotiation( + destination_cid=binascii.unhexlify("9aac5a49ba87a849"), - destination_cid=binascii.unhexlify("dae1889b81a91c26"), + source_cid=binascii.unhexlify("f92f4336fa951ba1"), - source_cid=binascii.unhexlify("f49243784f9bf3be"), + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A], ) self.assertEqual(data[1:], load("version_negotiation.bin")[1:]) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 5=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 6=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17)
tests.test_packet/FrameTest.test_transport_close
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> data = binascii.unhexlify("0a0212696c6c6567616c2041434b206672616d6500") <del> data = binascii.unhexlify("000a0212696c6c6567616c2041434b206672616d6500")
# module: tests.test_packet class FrameTest(TestCase): def test_transport_close(self): <0> data = binascii.unhexlify("000a0212696c6c6567616c2041434b206672616d6500") <1> <2> # parse <3> buf = Buffer(data=data) <4> frame = packet.pull_transport_close_frame(buf) <5> self.assertEqual(frame, (10, 2, "illegal ACK frame\x00")) <6>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str] at: tests.test_packet.FrameTest.test_transport_close data = binascii.unhexlify("0a0212696c6c6567616c2041434b206672616d6500") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet def pull_transport_close_frame(buf: Buffer) -> Tuple[int, int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() frame_type = buf.pull_uint_var() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, frame_type, reason_phrase) ===========changed ref 1=========== # module: tests.test_packet class FrameTest(TestCase): def test_new_connection_id(self): data = binascii.unhexlify( + "0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" - "02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" ) # parse buf = Buffer(data=data) frame = packet.pull_new_connection_id_frame(buf) self.assertEqual( frame, ( 2, + 0, binascii.unhexlify("7813f3d9e45e0cacbb491b4b66b039f204"), binascii.unhexlify("06f68fede38ec4c31aba8ab1245244e8"), ), ) # serialize buf = Buffer(capacity=len(data)) packet.push_new_connection_id_frame(buf, *frame) self.assertEqual(buf.data, data) ===========changed ref 2=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): + buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") - buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") with self.assertRaises(ValueError) as cm: pull_quic_header(buf, host_cid_length=8) self.assertEqual(str(cm.exception), "Packet fixed bit is zero") ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_encode_quic_version_negotiation(self): data = encode_quic_version_negotiation( + destination_cid=binascii.unhexlify("9aac5a49ba87a849"), - destination_cid=binascii.unhexlify("dae1889b81a91c26"), + source_cid=binascii.unhexlify("f92f4336fa951ba1"), - source_cid=binascii.unhexlify("f49243784f9bf3be"), + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A], ) self.assertEqual(data[1:], load("version_negotiation.bin")[1:]) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 5=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17) ===========changed ref 6=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_client(self): buf = Buffer(data=load("initial_client.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) + self.assertEqual(header.destination_cid, binascii.unhexlify("858b39368b8e3c6e")) - self.assertEqual(header.destination_cid, binascii.unhexlify("90ed1e1c7b04b5d3")) self.assertEqual(header.source_cid, b"") self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 1262) - self.assertEqual(header.rest_length, 1263) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17)
tests.test_packet/FrameTest.test_application_close
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> data = binascii.unhexlify("0008676f6f6462796500") <del> data = binascii.unhexlify("000008676f6f6462796500")
# module: tests.test_packet class FrameTest(TestCase): def test_application_close(self): <0> data = binascii.unhexlify("000008676f6f6462796500") <1> <2> # parse <3> buf = Buffer(data=data) <4> frame = packet.pull_application_close_frame(buf) <5> self.assertEqual(frame, (0, "goodbye\x00")) <6>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet pull_application_close_frame(buf: Buffer) -> Tuple[int, str] at: tests.test_packet.FrameTest.test_application_close data = binascii.unhexlify("0008676f6f6462796500") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 1=========== # module: tests.test_packet class FrameTest(TestCase): def test_transport_close(self): + data = binascii.unhexlify("0a0212696c6c6567616c2041434b206672616d6500") - data = binascii.unhexlify("000a0212696c6c6567616c2041434b206672616d6500") # parse buf = Buffer(data=data) frame = packet.pull_transport_close_frame(buf) self.assertEqual(frame, (10, 2, "illegal ACK frame\x00")) ===========changed ref 2=========== # module: tests.test_packet class FrameTest(TestCase): def test_new_connection_id(self): data = binascii.unhexlify( + "0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" - "02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" ) # parse buf = Buffer(data=data) frame = packet.pull_new_connection_id_frame(buf) self.assertEqual( frame, ( 2, + 0, binascii.unhexlify("7813f3d9e45e0cacbb491b4b66b039f204"), binascii.unhexlify("06f68fede38ec4c31aba8ab1245244e8"), ), ) # serialize buf = Buffer(capacity=len(data)) packet.push_new_connection_id_frame(buf, *frame) self.assertEqual(buf.data, data) ===========changed ref 3=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): + buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") - buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") with self.assertRaises(ValueError) as cm: pull_quic_header(buf, host_cid_length=8) self.assertEqual(str(cm.exception), "Packet fixed bit is zero") ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_encode_quic_version_negotiation(self): data = encode_quic_version_negotiation( + destination_cid=binascii.unhexlify("9aac5a49ba87a849"), - destination_cid=binascii.unhexlify("dae1889b81a91c26"), + source_cid=binascii.unhexlify("f92f4336fa951ba1"), - source_cid=binascii.unhexlify("f49243784f9bf3be"), + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A], ) self.assertEqual(data[1:], load("version_negotiation.bin")[1:]) ===========changed ref 5=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 6=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17)
tests.test_packet/FrameTest.test_application_close_not_utf8
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<0>:<add> data = binascii.unhexlify("0008676f6f6462798200") <del> data = binascii.unhexlify("000008676f6f6462798200")
# module: tests.test_packet class FrameTest(TestCase): def test_application_close_not_utf8(self): <0> data = binascii.unhexlify("000008676f6f6462798200") <1> <2> # parse <3> buf = Buffer(data=data) <4> frame = packet.pull_application_close_frame(buf) <5> self.assertEqual(frame, (0, "")) <6>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.packet pull_application_close_frame(buf: Buffer) -> Tuple[int, str] at: tests.test_packet.FrameTest.test_application_close_not_utf8 data = binascii.unhexlify("0008676f6f6462798200") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet def pull_application_close_frame(buf: Buffer) -> Tuple[int, str]: + error_code = buf.pull_uint_var() - error_code = buf.pull_uint16() reason_length = buf.pull_uint_var() reason_phrase = decode_reason_phrase(buf.pull_bytes(reason_length)) return (error_code, reason_phrase) ===========changed ref 1=========== # module: tests.test_packet class FrameTest(TestCase): def test_application_close(self): + data = binascii.unhexlify("0008676f6f6462796500") - data = binascii.unhexlify("000008676f6f6462796500") # parse buf = Buffer(data=data) frame = packet.pull_application_close_frame(buf) self.assertEqual(frame, (0, "goodbye\x00")) ===========changed ref 2=========== # module: tests.test_packet class FrameTest(TestCase): def test_transport_close(self): + data = binascii.unhexlify("0a0212696c6c6567616c2041434b206672616d6500") - data = binascii.unhexlify("000a0212696c6c6567616c2041434b206672616d6500") # parse buf = Buffer(data=data) frame = packet.pull_transport_close_frame(buf) self.assertEqual(frame, (10, 2, "illegal ACK frame\x00")) ===========changed ref 3=========== # module: tests.test_packet class FrameTest(TestCase): def test_new_connection_id(self): data = binascii.unhexlify( + "0200117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" - "02117813f3d9e45e0cacbb491b4b66b039f20406f68fede38ec4c31aba8ab1245244e8" ) # parse buf = Buffer(data=data) frame = packet.pull_new_connection_id_frame(buf) self.assertEqual( frame, ( 2, + 0, binascii.unhexlify("7813f3d9e45e0cacbb491b4b66b039f204"), binascii.unhexlify("06f68fede38ec4c31aba8ab1245244e8"), ), ) # serialize buf = Buffer(capacity=len(data)) packet.push_new_connection_id_frame(buf, *frame) self.assertEqual(buf.data, data) ===========changed ref 4=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_long_header_no_fixed_bit(self): + buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00\x00") - buf = Buffer(data=b"\x80\xff\x00\x00\x11\x00") with self.assertRaises(ValueError) as cm: pull_quic_header(buf, host_cid_length=8) self.assertEqual(str(cm.exception), "Packet fixed bit is zero") ===========changed ref 5=========== # module: tests.test_packet class PacketTest(TestCase): def test_encode_quic_version_negotiation(self): data = encode_quic_version_negotiation( + destination_cid=binascii.unhexlify("9aac5a49ba87a849"), - destination_cid=binascii.unhexlify("dae1889b81a91c26"), + source_cid=binascii.unhexlify("f92f4336fa951ba1"), - source_cid=binascii.unhexlify("f49243784f9bf3be"), + supported_versions=[0x45474716, QuicProtocolVersion.DRAFT_22], - supported_versions=[QuicProtocolVersion.DRAFT_18, 0x1A2A3A4A], ) self.assertEqual(data[1:], load("version_negotiation.bin")[1:]) ===========changed ref 6=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_version_negotiation(self): buf = Buffer(data=load("version_negotiation.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) self.assertEqual(header.version, QuicProtocolVersion.NEGOTIATION) self.assertEqual(header.packet_type, None) + self.assertEqual(header.destination_cid, binascii.unhexlify("9aac5a49ba87a849")) - self.assertEqual(header.destination_cid, binascii.unhexlify("dae1889b81a91c26")) + self.assertEqual(header.source_cid, binascii.unhexlify("f92f4336fa951ba1")) - self.assertEqual(header.source_cid, binascii.unhexlify("f49243784f9bf3be")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") self.assertEqual(header.rest_length, 8) + self.assertEqual(buf.tell(), 23) - self.assertEqual(buf.tell(), 22) ===========changed ref 7=========== # module: tests.test_packet class PacketTest(TestCase): def test_pull_initial_server(self): buf = Buffer(data=load("initial_server.bin")) header = pull_quic_header(buf, host_cid_length=8) self.assertTrue(header.is_long_header) + self.assertEqual(header.version, QuicProtocolVersion.DRAFT_22) - self.assertEqual(header.version, QuicProtocolVersion.DRAFT_17) self.assertEqual(header.packet_type, PACKET_TYPE_INITIAL) self.assertEqual(header.destination_cid, b"") + self.assertEqual(header.source_cid, binascii.unhexlify("195c68344e28d479")) - self.assertEqual(header.source_cid, binascii.unhexlify("0fcee9852fde8780")) self.assertEqual(header.original_destination_cid, b"") self.assertEqual(header.token, b"") + self.assertEqual(header.rest_length, 184) - self.assertEqual(header.rest_length, 182) + self.assertEqual(buf.tell(), 18) - self.assertEqual(buf.tell(), 17)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_empty
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<11>:<add> self.assertEqual(builder.remaining_space, 1236) <del> self.assertEqual(builder.remaining_space, 1237)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> <10> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <11> self.assertEqual(builder.remaining_space, 1237) <12> <13> # nothing to write <14> <15> self.assertFalse(builder.end_packet()) <16> self.assertEqual(builder.buffer.tell(), 0) <17> self.assertEqual(builder.packet_number, 0) <18> <19> datagrams, packets = builder.flush() <20> self.assertEqual(len(datagrams), 0) <21> self.assertEqual(packets, []) <22>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int at: aioquic.crypto CryptoPair() at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.packet_builder QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertFalse(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: + header_size = 11 + len(self._peer_cid) + len(self._host_cid) - header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========changed ref 3=========== # module: aioquic.packet_builder class QuicPacketBuilder: def end_packet(self) -> bool: """ Ends the current packet. Returns `True` if the packet contains data, `False` otherwise. """ buf = self.buffer empty = True packet_size = buf.tell() - self._packet_start if packet_size > self._header_size: empty = False # pad initial datagram if self._pad_first_datagram: buf.push_bytes(bytes(self.remaining_space)) packet_size = buf.tell() - self._packet_start self._pad_first_datagram = False # write header if self._packet_long_header: length = ( packet_size - self._header_size + PACKET_NUMBER_SEND_SIZE + self._packet_crypto.aead_tag_size ) buf.seek(self._packet_start) buf.push_uint8(self._packet_type | (PACKET_NUMBER_SEND_SIZE - 1)) buf.push_uint32(self._version) + buf.push_uint8(len(self._peer_cid)) - buf.push_uint8( - (encode_cid_length(len(self._peer_cid)) << 4) - | encode_cid_length(len(self._host_cid)) - ) buf.push_bytes(self._peer_cid) + buf.push_uint8(len(self._host_cid)) buf.push_bytes(self._host_cid) if (self._packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: buf.push_uint_var(len(self._peer_token)) buf.push_bytes(self._peer_token) buf.push_uint16(length | 0x4000) buf.push_uint16(self._packet_number & 0xFFFF) else: buf.seek(self._packet</s>
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<14>:<add> self.assertEqual(builder.remaining_space, 1236) <del> self.assertEqual(builder.remaining_space, 1237)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> pad_first_datagram=True, <4> peer_cid=bytes(8), <5> peer_token=b"", <6> spin_bit=False, <7> version=QuicProtocolVersion.DRAFT_20, <8> ) <9> crypto = CryptoPair() <10> crypto.setup_initial(bytes(8), is_client=True) <11> <12> # INITIAL, fully padded <13> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <14> self.assertEqual(builder.remaining_space, 1237) <15> builder.start_frame(QuicFrameType.CRYPTO) <16> builder.buffer.push_bytes(bytes(100)) <17> self.assertTrue(builder.end_packet()) <18> self.assertEqual(builder.buffer.tell(), 1280) <19> <20> # check datagrams <21> datagrams, packets = builder.flush() <22> self.assertEqual(len(datagrams), 1) <23> self.assertEqual(len(datagrams[0]), 1280) <24> self.assertEqual( <25> packets, <26> [ <27> QuicSentPacket( <28> epoch=Epoch.INITIAL, <29> in_flight=True, <30> is_ack_eliciting=True, <31> is_crypto_packet=True, <32> packet_number=0, <33> sent_bytes=1280, <34> ) <35> ], <36> ) <37>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.tls Epoch() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: + header_size = 11 + len(self._peer_cid) + len(self._host_cid) - header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<13>:<add> self.assertEqual(builder.remaining_space, 1236) <del> self.assertEqual(builder.remaining_space, 1237)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(bytes(8), is_client=True) <10> <11> # INITIAL, fully padded <12> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <13> self.assertEqual(builder.remaining_space, 1237) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(builder.remaining_space)) <16> self.assertTrue(builder.end_packet()) <17> self.assertEqual(builder.buffer.tell(), 1280) <18> <19> # ONE_RTT, fully padded <20> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <21> self.assertEqual(builder.remaining_space, 1253) <22> builder.start_frame(QuicFrameType.STREAM_BASE) <23> builder.buffer.push_bytes(bytes(builder.remaining_space)) <24> self.assertTrue(builder.end_packet()) <25> self.assertEqual(builder.buffer.tell(), 0) <26> <27> # check datagrams <28> datagrams, packets = builder.flush() <29> self.assertEqual(len(datagrams), 2) <30> self.assertEqual(len(datagrams[0]), 1280) <31> self.assertEqual(len(datagrams[1]), 1280) <32> self.assertEqual( <33> packets, <34> [ <35> QuicSentPacket( <36> epoch=Epoch.INITIAL, <37> in_flight=True, <38> is_ack_eliciting=True,</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 packet_number=0, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, sent_bytes=1280, ), ], ) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.tls Epoch() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: + header_size = 11 + len(self._peer_cid) + len(self._host_cid) - header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header
Modified
aiortc~aioquic
8dcde337e514e95159d3cdfd6fe2c6f4860d0770
[draft-22] first round of updates for draft 22
<13>:<add> self.assertEqual(builder.remaining_space, 1236) <del> self.assertEqual(builder.remaining_space, 1237) <16>:<add> self.assertEqual(builder.buffer.tell(), 228) <del> self.assertEqual(builder.buffer.tell(), 227) <18>:<add> self.assertEqual(builder.buffer.tell(), 244) <del> self.assertEqual(builder.buffer.tell(), 243) <22>:<add> self.assertEqual(builder.buffer.tell(), 271) <del> self.assertEqual(builder.buffer.tell(), 269) <23>:<add> self.assertEqual(builder.remaining_space, 993) <del> self.assertEqual(builder.remaining_space, 995) <26>:<add> self.assertEqual(builder.buffer.tell(), 571) <del> self.assertEqual(builder.buffer.tell(), 569) <28>:<add> self.assertEqual(builder.buffer.tell(), 587) <del> self.assertEqual(builder.buffer.tell(), 585) <32>:<add> self.assertEqual(builder.remaining_space, 666) <del> self.assertEqual(builder.remaining_space, 668)
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(bytes(8), is_client=True) <10> <11> # INITIAL <12> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <13> self.assertEqual(builder.remaining_space, 1237) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(199)) <16> self.assertEqual(builder.buffer.tell(), 227) <17> self.assertTrue(builder.end_packet()) <18> self.assertEqual(builder.buffer.tell(), 243) <19> <20> # HANDSHAKE <21> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) <22> self.assertEqual(builder.buffer.tell(), 269) <23> self.assertEqual(builder.remaining_space, 995) <24> builder.start_frame(QuicFrameType.CRYPTO) <25> builder.buffer.push_bytes(bytes(299)) <26> self.assertEqual(builder.buffer.tell(), 569) <27> self.assertTrue(builder.end_packet()) <28> self.assertEqual(builder.buffer.tell(), 585) <29> <30> # ONE_RTT <31> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <32> self.assertEqual(builder.remaining_space, 668) <33> builder.start_frame(QuicFrameType.CRYPTO) <34> builder.buffer.push_bytes(bytes(299)) <35> self.assertTrue(builder.end_packet()) <36> </s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): # offset: 1 # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 912) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, sent_bytes=243, ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, sent_bytes=342, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, sent_bytes=327, ), ], ) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.packet_builder QuicSentPacket(epoch: Epoch, in_flight: bool, is_ack_eliciting: bool, is_crypto_packet: bool, packet_number: int, sent_time: Optional[float]=None, sent_bytes: int=0, delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]]=field( default_factory=list )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.tls Epoch() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet class QuicProtocolVersion(IntEnum): NEGOTIATION = 0 DRAFT_17 = 0xFF000011 DRAFT_18 = 0xFF000012 DRAFT_19 = 0xFF000013 DRAFT_20 = 0xFF000014 + DRAFT_21 = 0xFF000015 + DRAFT_22 = 0xFF000016 ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: + header_size = 11 + len(self._peer_cid) + len(self._host_cid) - header_size = 10 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<14>:<add> self.alpn_cb: Optional[AlpnHandler] = None
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.early_data_accepted = False <7> self.handshake_extensions: List[Extension] = [] <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: Optional[List[Extension]] = None <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <15> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <16> self.update_traffic_key_cb: Callable[ <17> [Direction, Epoch, CipherSuite, bytes], None <18> ] = lambda d, e, c, s: None <19> <20> # supported parameters <21> self._cipher_suites = [ <22> CipherSuite.AES_256_GCM_SHA384, <23> CipherSuite.AES_128_GCM_SHA256, <24> CipherSuite.CHACHA20_POLY1305_SHA256, <25> ] <26> self._compression_methods = [CompressionMethod.NULL] <27> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <28> self._signature_algorithms = [ <29> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <30> SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <31> SignatureAlgorithm.RSA_PKCS1_SHA256,</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyExchangeMode(x: Union[str, bytes, bytearray], base: int) KeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) 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)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) 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)) AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] ===========unchanged ref 1=========== SessionTicketHandler = Callable[[SessionTicket], None] at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random ===========unchanged ref 2=========== self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self.early_data_accepted = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) self._new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), max_early_data_size=0xFFFFFFFF, ) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None]
aioquic.tls/Context._client_handle_encrypted_extensions
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<5>:<add> if self.alpn_cb: <add> self.alpn_cb(self.alpn_negotiated)
# module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: <0> encrypted_extensions = pull_encrypted_extensions(input_buf) <1> <2> self.alpn_negotiated = encrypted_extensions.alpn_protocol <3> self.early_data_accepted = encrypted_extensions.early_data <4> self.received_extensions = encrypted_extensions.other_extensions <5> <6> self._setup_traffic_protection( <7> Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" <8> ) <9> self.key_schedule.update_hash(input_buf.data) <10> <11> # if the server accepted our PSK we are done, other we want its certificate <12> if self._session_resumed: <13> self._set_state(State.CLIENT_EXPECT_FINISHED) <14> else: <15> self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) <16>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls Direction() Epoch() State() pull_encrypted_extensions(buf: Buffer) -> EncryptedExtensions at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.alpn_negotiated: Optional[str] = None self.early_data_accepted = False self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.alpn_cb: Optional[AlpnHandler] = None at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self.early_data_accepted = True at: aioquic.tls.EncryptedExtensions alpn_protocol: Optional[str] = None early_data: bool = False other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) at: aioquic.tls.KeySchedule update_hash(data: bytes) -> None ===========changed ref 0=========== # module: aioquic.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): self.alpn_negotiated: Optional[str] = None self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.early_data_accepted = False self.handshake_extensions: List[Extension] = [] self.key_schedule: Optional[KeySchedule] = None self.received_extensions: Optional[List[Extension]] = None self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None # callbacks + self.alpn_cb: Optional[AlpnHandler] = None self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None # supported parameters self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, </s> ===========changed ref 2=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 <s>SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO
aioquic.connection/QuicConnection._initialize
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<33>:<add> self.tls.alpn_cb = self._alpn_handler
# module: aioquic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: <0> # TLS <1> self.tls = tls.Context(is_client=self._is_client, logger=self._logger) <2> self.tls.alpn_protocols = self._configuration.alpn_protocols <3> self.tls.certificate = self._configuration.certificate <4> self.tls.certificate_private_key = self._configuration.private_key <5> self.tls.handshake_extensions = [ <6> ( <7> tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, <8> self._serialize_transport_parameters(), <9> ) <10> ] <11> self.tls.server_name = self._configuration.server_name <12> <13> # TLS session resumption <14> session_ticket = self._configuration.session_ticket <15> if ( <16> self._is_client <17> and session_ticket is not None <18> and session_ticket.is_valid <19> and session_ticket.server_name == self._configuration.server_name <20> ): <21> self.tls.session_ticket = self._configuration.session_ticket <22> <23> # parse saved QUIC transport parameters - for 0-RTT <24> if session_ticket.max_early_data_size == 0xFFFFFFFF: <25> for ext_type, ext_data in session_ticket.other_extensions: <26> if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: <27> self._parse_transport_parameters( <28> ext_data, from_session_ticket=True <29> ) <30> break <31> <32> # TLS callbacks <33> if self._session_ticket_fetcher is not None: <34> self.tls.get_session_ticket_cb = self._session_ticket_fetcher <35> if self._session_ticket_handler is not None: <36> self.tls.new_session_ticket_cb = self._session_ticket_handler <37> self.tls.update_traffic_key_cb = self._update_traffic_key <38> <39> #</s>
===========below chunk 0=========== # module: aioquic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 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=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } 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 ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0 ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection.QuicConnection _alpn_handler(alpn_protocol: 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.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._crypto_streams: Dict[tls.Epoch, QuicStream] = {} self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler ===========unchanged ref 1=========== at: aioquic.connection.QuicConnection._get_or_create_stream stream = self._streams[stream_id] = QuicStream( connection=self, stream_id=stream_id, max_stream_data_local=max_stream_data_local, max_stream_data_remote=max_stream_data_remote, ) stream = self._streams.get(stream_id, None) max_stream_data_local = self._local_max_stream_data_uni max_stream_data_local = self._local_max_stream_data_bidi_remote max_stream_data_remote = 0 max_stream_data_remote = self._remote_max_stream_data_bidi_local at: aioquic.crypto CryptoPair() at: aioquic.recovery QuicPacketSpace() at: aioquic.stream QuicStream(stream_id: Optional[int]=None, connection: Optional[Any]=None, max_stream_data_local: int=0, max_stream_data_remote: int=0) at: aioquic.tls Epoch() ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Context(is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]]=None) at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.certificate: Optional[x509.Certificate] = None self.certificate_private_key: Optional[ Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] ] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None ===========unchanged ref 2=========== self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None 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) ===========changed ref 0=========== # module: aioquic.connection class QuicConnection: + # Private + + def _alpn_handler(self, alpn_protocol: str) -> None: + """ + Callback which is invoked by the TLS engine when ALPN negotiation completes. + """ + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol)) + ===========changed ref 1=========== # module: aioquic.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: encrypted_extensions = pull_encrypted_extensions(input_buf) self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions + if self.alpn_cb: + self.alpn_cb(self.alpn_negotiated) self._setup_traffic_protection( Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" ) self.key_schedule.update_hash(input_buf.data) # if the server accepted our PSK we are done, other we want its certificate if self._session_resumed: self._set_state(State.CLIENT_EXPECT_FINISHED) else: self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE)
tests.test_connection/QuicConnectionTest.test_connect
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<2>:<add> event = client.next_event() <add> self.assertEqual(type(event), events.ProtocolNegotiated) <add> self.assertEqual(event.alpn_protocol, None) <11>:<add> event = server.next_event() <add> self.assertEqual(type(event), events.ProtocolNegotiated) <add> self.assertEqual(event.alpn_protocol, None)
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect(self): <0> with client_and_server() as (client, server): <1> # check handshake completed <2> event = client.next_event() <3> self.assertEqual(type(event), events.HandshakeCompleted) <4> self.assertEqual(event.alpn_protocol, None) <5> self.assertEqual(event.early_data_accepted, False) <6> self.assertEqual(event.session_resumed, False) <7> for i in range(7): <8> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) <9> self.assertIsNone(client.next_event()) <10> <11> event = server.next_event() <12> self.assertEqual(type(event), events.HandshakeCompleted) <13> self.assertEqual(event.alpn_protocol, None) <14> self.assertEqual(event.early_data_accepted, False) <15> self.assertEqual(event.session_resumed, False) <16> for i in range(7): <17> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) <18> self.assertIsNone(server.next_event()) <19> <20> # check each endpoint has available connection IDs for the peer <21> self.assertEqual( <22> sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] <23> ) <24> self.assertEqual( <25> sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] <26> ) <27> <28> # client closes the connection <29> client.close() <30> self.assertEqual(transfer(client, server), 1) <31> <32> # check connection closes on the client side <33> client.handle_timer(client.get_timer()) <34> event = client.next_event() <35> self.assertEqual(type(event), events.ConnectionTerminated) <36> self.assertEqual(</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect(self): # offset: 1 self.assertEqual(event.frame_type, None) self.assertEqual(event.reason_phrase, "") self.assertIsNone(client.next_event()) # check connection closes on the server side server.handle_timer(server.get_timer()) event = server.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual(event.reason_phrase, "") self.assertIsNone(server.next_event()) ===========unchanged ref 0=========== at: aioquic.events ConnectionIdIssued(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) sequence_numbers(connection_ids) transfer(sender, receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: + # Private + + def _alpn_handler(self, alpn_protocol: str) -> None: + """ + Callback which is invoked by the TLS engine when ALPN negotiation completes. + """ + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol)) + ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: encrypted_extensions = pull_encrypted_extensions(input_buf) self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions + if self.alpn_cb: + self.alpn_cb(self.alpn_negotiated) self._setup_traffic_protection( Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" ) self.key_schedule.update_hash(input_buf.data) # if the server accepted our PSK we are done, other we want its certificate if self._session_resumed: self._set_state(State.CLIENT_EXPECT_FINISHED) else: self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) ===========changed ref 3=========== # module: aioquic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self._is_client, logger=self._logger) self.tls.alpn_protocols = self._configuration.alpn_protocols self.tls.certificate = self._configuration.certificate self.tls.certificate_private_key = self._configuration.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self._configuration.server_name # TLS session resumption session_ticket = self._configuration.session_ticket if ( self._is_client and session_ticket is not None and session_ticket.is_valid and session_ticket.server_name == self._configuration.server_name ): self.tls.session_ticket = self._configuration.session_ticket # parse saved QUIC transport parameters - for 0-RTT if session_ticket.max_early_data_size == 0xFFFFFFFF: for ext_type, ext_data in session_ticket.other_extensions: if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: self._parse_transport_parameters( ext_data, from_session_ticket=True ) 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._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), </s> ===========changed ref 4=========== # module: aioquic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # offset: 1 <s>_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=4096), tls.Epoch.HANDSHAKE: Buffer(capacity=4096), tls.Epoch.ONE_RTT: Buffer(capacity=4096), } self._crypto_streams = { tls.Epoch.INITIAL: QuicStream(), tls.Epoch.HANDSHAKE: QuicStream(), tls.Epoch.ONE_RTT: QuicStream(), } 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 ) self._loss.spaces = list(self._spaces.values()) self._packet_number = 0
tests.test_connection/QuicConnectionTest.test_connect_with_alpn
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<5>:<add> event = client.next_event() <add> self.assertEqual(type(event), events.ProtocolNegotiated) <add> self.assertEqual(event.alpn_protocol, "hq-22") <13>:<add> self.assertEqual(type(event), events.ProtocolNegotiated) <add> self.assertEqual(event.alpn_protocol, "hq-22") <add> event = server.next_event()
# module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["hq-22", "h3-22"]}, <2> server_options={"alpn_protocols": ["hq-22"]}, <3> ) as (client, server): <4> # check handshake completed <5> event = client.next_event() <6> self.assertEqual(type(event), events.HandshakeCompleted) <7> self.assertEqual(event.alpn_protocol, "hq-22") <8> for i in range(7): <9> self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) <10> self.assertIsNone(client.next_event()) <11> <12> event = server.next_event() <13> self.assertEqual(type(event), events.HandshakeCompleted) <14> self.assertEqual(event.alpn_protocol, "hq-22") <15> for i in range(7): <16> self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) <17> self.assertIsNone(server.next_event()) <18>
===========unchanged ref 0=========== at: aioquic.events ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) HandshakeCompleted(alpn_protocol: Optional[str], early_data_accepted: bool, session_resumed: bool) at: aioquic.packet QuicErrorCode(x: Union[str, bytes, bytearray], base: int) QuicErrorCode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_connection.QuicConnectionTest.test_connect event = client.next_event() event = server.next_event() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertIsNone(obj: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect(self): with client_and_server() as (client, server): # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, None) event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, None) self.assertEqual(event.early_data_accepted, False) self.assertEqual(event.session_resumed, False) for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) + event = server.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, None) event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, None) self.assertEqual(event.early_data_accepted, False) self.assertEqual(event.session_resumed, False) for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event()) # check each endpoint has available connection IDs for the peer self.assertEqual( sequence_numbers(client._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] ) self.assertEqual( sequence_numbers(server._peer_cid_available), [1, 2, 3, 4, 5, 6, 7] ) # client closes the connection client.close() self.assertEqual(transfer(client, server), 1) </s> ===========changed ref 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect(self): # offset: 1 <s> # client closes the connection client.close() self.assertEqual(transfer(client, server), 1) # check connection closes on the client side client.handle_timer(client.get_timer()) event = client.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual(event.reason_phrase, "") self.assertIsNone(client.next_event()) # check connection closes on the server side server.handle_timer(server.get_timer()) event = server.next_event() self.assertEqual(type(event), events.ConnectionTerminated) self.assertEqual(event.error_code, QuicErrorCode.NO_ERROR) self.assertEqual(event.frame_type, None) self.assertEqual(event.reason_phrase, "") self.assertIsNone(server.next_event()) ===========changed ref 2=========== # module: aioquic.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 3=========== # module: aioquic.connection class QuicConnection: + # Private + + def _alpn_handler(self, alpn_protocol: str) -> None: + """ + Callback which is invoked by the TLS engine when ALPN negotiation completes. + """ + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol)) + ===========changed ref 4=========== # module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: encrypted_extensions = pull_encrypted_extensions(input_buf) self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions + if self.alpn_cb: + self.alpn_cb(self.alpn_negotiated) self._setup_traffic_protection( Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" ) self.key_schedule.update_hash(input_buf.data) # if the server accepted our PSK we are done, other we want its certificate if self._session_resumed: self._set_state(State.CLIENT_EXPECT_FINISHED) else: self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) ===========changed ref 5=========== # module: aioquic.connection class QuicConnection: def _initialize(self, peer_cid: bytes) -> None: # TLS self.tls = tls.Context(is_client=self._is_client, logger=self._logger) self.tls.alpn_protocols = self._configuration.alpn_protocols self.tls.certificate = self._configuration.certificate self.tls.certificate_private_key = self._configuration.private_key self.tls.handshake_extensions = [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, self._serialize_transport_parameters(), ) ] self.tls.server_name = self._configuration.server_name # TLS session resumption session_ticket = self._configuration.session_ticket if ( self._is_client and session_ticket is not None and session_ticket.is_valid and session_ticket.server_name == self._configuration.server_name ): self.tls.session_ticket = self._configuration.session_ticket # parse saved QUIC transport parameters - for 0-RTT if session_ticket.max_early_data_size == 0xFFFFFFFF: for ext_type, ext_data in session_ticket.other_extensions: if ext_type == tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS: self._parse_transport_parameters( ext_data, from_session_ticket=True ) 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._session_ticket_handler self.tls.update_traffic_key_cb = self._update_traffic_key # packet spaces self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), </s>
tests.test_connection/QuicConnectionTest.test_connect_with_loss_1
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
# 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 = QuicConnection(configuration=QuicConfiguration(is_client=True)) <8> client._ack_delay = 0 <9> <10> server = QuicConnection( <11> configuration=QuicConfiguration( <12> is_client=False, <13> certificate=SERVER_CERTIFICATE, <14> private_key=SERVER_PRIVATE_KEY, <15> ) <16> ) <17> server._ack_delay = 0 <18> <19> # client sends INITIAL <20> now = 0.0 <21> client.connect(SERVER_ADDR, now=now) <22> items = client.datagrams_to_send(now=now) <23> self.assertEqual(datagram_sizes(items), [1280]) <24> self.assertEqual(client.get_timer(), 1.0) <25> <26> # INITIAL is lost <27> now = 1.0 <28> client.handle_timer(now=now) <29> items = client.datagrams_to_send(now=now) <30> self.assertEqual(datagram_sizes(items), [1280]) <31> self.assertEqual(client.get_timer(), 3.0) <32> <33> # server receives INITIAL, sends INITIAL + HANDSHAKE <34> now = 1.1 <35> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <36> items = server.datagrams_to_send(now=now) <37> self.assertEqual(datagram_sizes(items), [1280, 1079]) <38> self.assertEqual(server.get_timer(), 2.1) <39> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <40> self.assertEqual(len(server._loss.spaces[1</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 1 # 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), [1280, 223]) self.assertAlmostEqual(client.get_timer(), 1.825) now = 1.3 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) server.receive_datagram(items[1][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [276]) 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), 1) 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 self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted)) now = 1.5 server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) items = server.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_1(self): # offset: 2 <s>_sizes(items), []) self.assertAlmostEqual(server.get_timer(), 61.5) # idle timeout self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted)) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY ===========unchanged ref 1=========== self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) at: tests.test_connection.QuicConnectionTest.test_connect_with_log client_log = client_log_file.getvalue() labels = [] at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: unittest.case.TestCase assertEqual(first: Any, second: 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_alpn(self): with client_and_server( client_options={"alpn_protocols": ["hq-22", "h3-22"]}, server_options={"alpn_protocols": ["hq-22"]}, ) as (client, server): # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, "hq-22") event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, "hq-22") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, "hq-22") + event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, "hq-22") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event())
tests.test_connection/QuicConnectionTest.test_connect_with_loss_2
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
# 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 = QuicConnection(configuration=QuicConfiguration(is_client=True)) <4> client._ack_delay = 0 <5> <6> server = QuicConnection( <7> configuration=QuicConfiguration( <8> is_client=False, <9> certificate=SERVER_CERTIFICATE, <10> private_key=SERVER_PRIVATE_KEY, <11> ) <12> ) <13> server._ack_delay = 0 <14> <15> # client sends INITIAL <16> now = 0.0 <17> client.connect(SERVER_ADDR, now=now) <18> items = client.datagrams_to_send(now=now) <19> self.assertEqual(datagram_sizes(items), [1280]) <20> self.assertEqual(client.get_timer(), 1.0) <21> <22> # server receives INITIAL, sends INITIAL + HANDSHAKE but second datagram is lost <23> now = 0.1 <24> server.receive_datagram(items[0][0], CLIENT_ADDR, now=now) <25> items = server.datagrams_to_send(now=now) <26> self.assertEqual(datagram_sizes(items), [1280, 1079]) <27> self.assertEqual(server.get_timer(), 1.1) <28> self.assertEqual(len(server._loss.spaces[0].sent_packets), 1) <29> self.assertEqual(len(server._loss.spaces[1].sent_packets), 2) <30> <31> #  client only receives first datagram and sends ACKS <32> now = 0.2 <33> client.receive_datagram(items[0][0], SERVER_ADDR, now=now) <34> items = client.datagrams_to_send(now=now) <35> self.assertEqual(datagram_sizes(items), [97]) <36> self.assertAlmostEqual(client</s>
===========below chunk 0=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 1 #  client PTO - padded HANDSHAKE now = client.get_timer() # ~0.625 client.handle_timer(now=now) items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [1280]) self.assertAlmostEqual(client.get_timer(), 1.25) # server receives padding, discards INITIAL 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), []) 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), 2) # 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, 900]) 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), 2) # 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</s> ===========below chunk 1=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_loss_2(self): # offset: 2 <s> items = client.datagrams_to_send(now=now) self.assertEqual(datagram_sizes(items), [334]) self.assertAlmostEqual(client.get_timer(), 2.45) self.assertTrue(isinstance(client.next_event(), events.HandshakeCompleted)) 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), [228]) self.assertAlmostEqual(server.get_timer(), 1.825) self.assertTrue(isinstance(server.next_event(), events.HandshakeCompleted)) 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: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] handle_timer(now: float) -> None receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.connection.QuicConnection.__init__ self._ack_delay = K_GRANULARITY self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) at: aioquic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] at: aioquic.recovery.QuicPacketSpace.__init__ self.sent_packets: Dict[int, QuicSentPacket] = {} at: tests.test_connection CLIENT_ADDR = ("1.2.3.4", 1234) SERVER_ADDR = ("2.3.4.5", 4433) ===========unchanged ref 1=========== at: tests.test_connection.QuicConnectionTest.test_connect_with_loss_1 datagram_sizes(items) client = QuicConnection(configuration=QuicConfiguration(is_client=True)) server = QuicConnection( configuration=QuicConfiguration( is_client=False, certificate=SERVER_CERTIFICATE, private_key=SERVER_PRIVATE_KEY, ) ) at: tests.utils SERVER_CERTIFICATE = x509.load_pem_x509_certificate( load("ssl_cert.pem"), backend=default_backend() ) SERVER_PRIVATE_KEY = serialization.load_pem_private_key( load("ssl_key.pem"), password=None, backend=default_backend() ) at: unittest.case.TestCase assertEqual(first: Any, second: 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
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
53fbc57b0113e1eedf64954d577ca7c0515c5f01
[connection] add a ProtocolNegotiated event
<11>:<add> elif isinstance(event, aioquic.events.ProtocolNegotiated): <del> elif isinstance(event, aioquic.events.HandshakeCompleted):
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.events.ConnectionTerminated): <4> # remove the connection <5> for cid, conn in list(self._connections.items()): <6> if conn == connection: <7> del self._connections[cid] <8> self._http.pop(connection, None) <9> self._timer.pop(connection, None) <10> return <11> elif isinstance(event, aioquic.events.HandshakeCompleted): <12> if event.alpn_protocol == "h3-22": <13> self._http[connection] = H3Connection(connection) <14> elif event.alpn_protocol == "hq-22": <15> self._http[connection] = H0Connection(connection) <16> elif isinstance(event, aioquic.events.ConnectionIdIssued): <17> self._connections[event.connection_id] = connection <18> elif isinstance(event, aioquic.events.ConnectionIdRetired): <19> assert self._connections[event.connection_id] == connection <20> del self._connections[event.connection_id] <21> <22> #  pass event to the HTTP layer <23> http = self._http.get(connection) <24> if http is not None: <25> for http_event in http.handle_event(event): <26> handle_http_event(http, http_event) <27> <28> event = connection.next_event() <29> <30> # send datagrams <31> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <32> self._transport.sendto(data, addr) <33> <34> # re-arm timer <35> next_timer_at = connection.get_timer() <36> (timer, timer_at) = self._timer.get(connection, (None, None)) <37> if timer is not None and timer</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 timer.cancel() timer = None if timer is None and timer_at is not None: timer = self._loop.call_at( next_timer_at, partial(self._handle_timer, connection) ) self._timer[connection] = (timer, next_timer_at) ===========unchanged ref 0=========== at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.Event] at: aioquic.events ConnectionIdIssued(connection_id: bytes) ConnectionIdRetired(connection_id: bytes) ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] at: asyncio.events.AbstractEventLoop call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server H0Connection(quic: QuicConnection) handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None at: examples.http3-server.H0Connection handle_event(event: aioquic.events.Event) at: examples.http3-server.HttpServer _handle_timer(connection: QuicConnection) -> None ===========unchanged ref 1=========== at: examples.http3-server.HttpServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() 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.tls + AlpnHandler = Callable[[str], None] SessionTicketFetcher = Callable[[bytes], Optional[SessionTicket]] SessionTicketHandler = Callable[[SessionTicket], None] ===========changed ref 1=========== # module: aioquic.connection class QuicConnection: + # Private + + def _alpn_handler(self, alpn_protocol: str) -> None: + """ + Callback which is invoked by the TLS engine when ALPN negotiation completes. + """ + self._events.append(events.ProtocolNegotiated(alpn_protocol=alpn_protocol)) + ===========changed ref 2=========== # module: aioquic.tls class Context: def _client_handle_encrypted_extensions(self, input_buf: Buffer) -> None: encrypted_extensions = pull_encrypted_extensions(input_buf) self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions + if self.alpn_cb: + self.alpn_cb(self.alpn_negotiated) self._setup_traffic_protection( Direction.ENCRYPT, Epoch.HANDSHAKE, b"c hs traffic" ) self.key_schedule.update_hash(input_buf.data) # if the server accepted our PSK we are done, other we want its certificate if self._session_resumed: self._set_state(State.CLIENT_EXPECT_FINISHED) else: self._set_state(State.CLIENT_EXPECT_CERTIFICATE_REQUEST_OR_CERTIFICATE) ===========changed ref 3=========== # module: tests.test_connection class QuicConnectionTest(TestCase): def test_connect_with_alpn(self): with client_and_server( client_options={"alpn_protocols": ["hq-22", "h3-22"]}, server_options={"alpn_protocols": ["hq-22"]}, ) as (client, server): # check handshake completed + event = client.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, "hq-22") event = client.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, "hq-22") for i in range(7): self.assertEqual(type(client.next_event()), events.ConnectionIdIssued) self.assertIsNone(client.next_event()) event = server.next_event() + self.assertEqual(type(event), events.ProtocolNegotiated) + self.assertEqual(event.alpn_protocol, "hq-22") + event = server.next_event() self.assertEqual(type(event), events.HandshakeCompleted) self.assertEqual(event.alpn_protocol, "hq-22") for i in range(7): self.assertEqual(type(server.next_event()), events.ConnectionIdIssued) self.assertIsNone(server.next_event())
examples.server/SessionTicketStore.__init__
Modified
aiortc~aioquic
72fb62a0ad286f5876e7f725f754be59b6460a67
[examples] add type definitions for examples
<0>:<add> self.tickets: Dict[bytes, SessionTicket] = {} <del> self.tickets = {}
# module: examples.server class SessionTicketStore: + def __init__(self) -> None: - def __init__(self): <0> self.tickets = {} <1>
tests.test_h3/h3_transfer
Modified
aiortc~aioquic
1d6ed5fe208f4987cf99d3ad14f74f73e9eb7d6e
[http3] remove H3Connection.handle_events
<0>:<add> quic_receiver = h3_receiver._quic <add> transfer(quic_sender, quic_receiver) <del> transfer(quic_sender, h3_receiver._quic) <1>:<del> return h3_receiver.handle_events()
# module: tests.test_h3 def h3_transfer(quic_sender, h3_receiver): <0> transfer(quic_sender, h3_receiver._quic) <1> return h3_receiver.handle_events() <2>
===========unchanged ref 0=========== at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: tests.test_connection transfer(sender, receiver) ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: - def handle_events(self) -> List[Event]: - """ - Handle events from the QUIC connection and return HTTP events. - """ - http_events: List[Event] = [] - - # process QUIC events - event = self._quic.next_event() - while event is not None: - http_events.extend(self.handle_event(event)) - event = self._quic.next_event() - - return http_events -
examples.http3-client/run
Modified
aiortc~aioquic
1d6ed5fe208f4987cf99d3ad14f74f73e9eb7d6e
[http3] remove H3Connection.handle_events
# module: examples.http3-client def run(url: str, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-22"], is_client=True, server_name=server_name, **kwargs <18> ), <19> session_ticket_handler=save_session_ticket, <20> ) <21> quic.connect(server_addr, now=time.time()) <22> <23> # send request <24> http = H3Connection(quic) <25> stream_id = quic.get_next_available_stream_id() <26> http.send_headers( <27> stream_id=stream_id, <28> headers=[ <29> (b":method", b"GET"), <30> (b":scheme", parsed.scheme.encode("utf8")), <31> (b":authority", parsed.netloc.encode("utf8")), <32> (b":path", parsed.path.encode("utf8")), <33> ], <34> ) <35> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <36> for data, addr in quic.datagrams_to_send(now=time.time()): <37> sock.sendto(data, addr) <38> <39> # handle events <40> stream_ended = False <41> while not stream_ended: <42> </s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, **kwargs) -> None: # offset: 1 quic.receive_datagram(data, addr, now=time.time()) for event in http.handle_events(): print(event) if isinstance(event, (DataReceived, ResponseReceived)): stream_ended = event.stream_ended for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) ===========unchanged ref 1=========== at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client save_session_ticket(ticket) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: tests.test_h3 def h3_transfer(quic_sender, h3_receiver): + quic_receiver = h3_receiver._quic + transfer(quic_sender, quic_receiver) - transfer(quic_sender, h3_receiver._quic) - return h3_receiver.handle_events() ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: - def handle_events(self) -> List[Event]: - """ - Handle events from the QUIC connection and return HTTP events. - """ - http_events: List[Event] = [] - - # process QUIC events - event = self._quic.next_event() - while event is not None: - http_events.extend(self.handle_event(event)) - event = self._quic.next_event() - - return http_events -
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
e12e77d0cf5414b58a616305e4f7ad64211f5ec6
[http0] add support for client role
<0>:<add> http_events: List[Event] = [] <del> http_events = [] <6>:<del> method, path = event.data.rstrip().split(b" ", 1) <7>:<del> cls = ResponseReceived if self._is_client else RequestReceived <8>:<add> if self._is_client: <add> http_events.append( <del> http_events.append( <9>:<add> ResponseReceived( <add> headers=[], stream_ended=False, stream_id=event.stream_id <add> ) <del> cls( <10>:<del> headers=[(b":method", method), (b":path", path)], <11>:<del> stream_ended=event.end_stream, <12>:<del> stream_id=event.stream_id, <14>:<add> http_events.append( <add> DataReceived( <add> data=event.data, <add> stream_ended=event.end_stream, <add> stream_id=event.stream_id, <add> ) <add> ) <del> ) <15>:<add> <add> else: <add> method, path = event.data.rstrip().split(b" ", 1) <add> http_events.append( <add> RequestReceived( <add> headers=[(b":method", method), (b":path", path)], <add> stream_ended=event.end_stream, <add> stream_id=event.stream_id, <add> ) <add> )
# module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: aioquic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event): <0> http_events = [] <1> <2> if ( <3> isinstance(event, aioquic.events.StreamDataReceived) <4> and (event.stream_id % 4) == 0 <5> ): <6> method, path = event.data.rstrip().split(b" ", 1) <7> cls = ResponseReceived if self._is_client else RequestReceived <8> http_events.append( <9> cls( <10> headers=[(b":method", method), (b":path", path)], <11> stream_ended=event.end_stream, <12> stream_id=event.stream_id, <13> ) <14> ) <15> <16> return http_events <17>
===========unchanged ref 0=========== at: aioquic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.h0.connection.H0Connection.__init__ self._is_client = quic.configuration.is_client at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: typing List = _alias(list, 1, inst=False, name='List')
aioquic.h0.connection/H0Connection.send_headers
Modified
aiortc~aioquic
e12e77d0cf5414b58a616305e4f7ad64211f5ec6
[http0] add support for client role
<0>:<add> if self._is_client: <add> headers_dict = dict(headers) <add> self._quic.send_stream_data( <add> stream_id, <add> headers_dict[b":method"] + b" " + headers_dict[b":path"] + b"\r\n", <add> False, <add> ) <del> # HTTP/0.9 has no concept of headers. <1>:<del> pass
# module: aioquic.h0.connection class H0Connection: def send_headers(self, stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None: <0> # HTTP/0.9 has no concept of headers. <1> pass <2>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection.handle_event http_events: List[Event] = [] at: aioquic.h3.events RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ===========changed ref 0=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: aioquic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event): + http_events: List[Event] = [] - http_events = [] if ( isinstance(event, aioquic.events.StreamDataReceived) and (event.stream_id % 4) == 0 ): - method, path = event.data.rstrip().split(b" ", 1) - cls = ResponseReceived if self._is_client else RequestReceived + if self._is_client: + http_events.append( - http_events.append( + ResponseReceived( + headers=[], stream_ended=False, stream_id=event.stream_id + ) - cls( - headers=[(b":method", method), (b":path", path)], - stream_ended=event.end_stream, - stream_id=event.stream_id, ) + http_events.append( + DataReceived( + data=event.data, + stream_ended=event.end_stream, + stream_id=event.stream_id, + ) + ) - ) + + else: + method, path = event.data.rstrip().split(b" ", 1) + http_events.append( + RequestReceived( + headers=[(b":method", method), (b":path", path)], + stream_ended=event.end_stream, + stream_id=event.stream_id, + ) + ) return http_events
examples.http3-client/run
Modified
aiortc~aioquic
17fd217f8ab3c56131db1e578537f441b7d96dfe
[examples] make HTTP/3 client also capable of making HTTP/0.9 requests
<17>:<add> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <add> is_client=True, <add> server_name=server_name, <add> **kwargs <del> alpn_protocols=["h3-22"], is_client=True, server_name=server_name, **kwargs <24>:<add> http: HttpConnection <add> if legacy_http: <add> http = H0Connection(quic) <add> else: <add> http = H3Connection(quic) <del> http = H3Connection(quic)
# module: examples.http3-client + def run(url: str, legacy_http: bool, **kwargs) -> None: - def run(url: str, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["h3-22"], is_client=True, server_name=server_name, **kwargs <18> ), <19> session_ticket_handler=save_session_ticket, <20> ) <21> quic.connect(server_addr, now=time.time()) <22> <23> # send request <24> http = H3Connection(quic) <25> stream_id = quic.get_next_available_stream_id() <26> http.send_headers( <27> stream_id=stream_id, <28> headers=[ <29> (b":method", b"GET"), <30> (b":scheme", parsed.scheme.encode("utf8")), <31> (b":authority", parsed.netloc.encode("utf8")), <32> (b":path", parsed.path.encode("utf8")), <33> ], <34> ) <35> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <36> for data, addr in quic.datagrams_to_send(now=time.time()): <37> sock.sendto(data, addr) <38> <39> #</s>
===========below chunk 0=========== # module: examples.http3-client + def run(url: str, legacy_http: bool, **kwargs) -> None: - def run(url: str, **kwargs) -> None: # offset: 1 stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): print(http_event) if isinstance(http_event, (DataReceived, ResponseReceived)): stream_ended = http_event.stream_ended event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: _pickle dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None ===========unchanged ref 1=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] save_session_ticket(ticket) args = parser.parse_args() at: pickle dump, dumps, load, loads = _dump, _dumps, _load, _loads at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int ===========unchanged ref 2=========== at: time time() -> float at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: examples.http3-client logger = logging.getLogger("client") + HttpConnection = Union[H0Connection, H3Connection] +
aioquic.h0.connection/H0Connection.__init__
Modified
aiortc~aioquic
8acade9e4b7fa9e45ebb90a820f4fc09e0edcb3f
[http0] add some tests
<0>:<add> self._headers_received: Dict[int, bool] = {}
# module: aioquic.h0.connection class H0Connection: def __init__(self, quic: QuicConnection): <0> self._is_client = quic.configuration.is_client <1> self._quic = quic <2>
===========unchanged ref 0=========== at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
8acade9e4b7fa9e45ebb90a820f4fc09e0edcb3f
[http0] add some tests
<6>:<add> data = event.data <add> if not self._headers_received.get(event.stream_id, False): <add> if self._is_client: <del> if self._is_client: <7>:<add> http_events.append( <del> http_events.append( <8>:<add> ResponseReceived( <del> ResponseReceived( <9>:<add> headers=[], stream_ended=False, stream_id=event.stream_id <del> headers=[], stream_ended=False, stream_id=event.stream_id <10>:<add> ) <11>:<add> else: <add> method, path = data.rstrip().split(b" ", 1) <add> http_events.append( <add> RequestReceived( <add> headers=[(b":method", method), (b":path", path)], <add> stream_ended=False, <add> stream_id=event.stream_id, <add> ) <add> ) <add> data = b"" <add> self._headers_received[event.stream_id] = True <add> <add> http_events.append( <add> DataReceived( <add> data=data, stream_ended=event.end_stream, stream_id=event.stream_id <12>:<del> http_events.append( <13>:<del> DataReceived(
# module: aioquic.h0.connection class H0Connection: def handle_event(self, event: aioquic.events.Event) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if ( <3> isinstance(event, aioquic.events.StreamDataReceived) <4> and (event.stream_id % 4) == 0 <5> ): <6> if self._is_client: <7> http_events.append( <8> ResponseReceived( <9> headers=[], stream_ended=False, stream_id=event.stream_id <10> ) <11> ) <12> http_events.append( <13> DataReceived( <14> data=event.data, <15> stream_ended=event.end_stream, <16> stream_id=event.stream_id, <17> ) <18> ) <19> <20> else: <21> method, path = event.data.rstrip().split(b" ", 1) <22> http_events.append( <23> RequestReceived( <24> headers=[(b":method", method), (b":path", path)], <25> stream_ended=event.end_stream, <26> stream_id=event.stream_id, <27> ) <28> ) <29> <30> return http_events <31>
===========unchanged ref 0=========== at: aioquic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.h0.connection.H0Connection.__init__ self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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] ===========changed ref 0=========== # module: aioquic.h0.connection class H0Connection: def __init__(self, quic: QuicConnection): + self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client self._quic = quic
aioquic.connection/QuicConnection._replenish_connection_ids
Modified
aiortc~aioquic
afd57a7cde06c503216d3a49f81311bcac784f11
[connection] cap the number of connection IDs we offer
<3>:<add> while len(self._host_cids) < min(8, self._remote_active_connection_id_limit): <del> while len(self._host_cids) < self._remote_active_connection_id_limit:
# module: aioquic.connection class QuicConnection: def _replenish_connection_ids(self) -> None: <0> """ <1> Generate new connection IDs. <2> """ <3> while len(self._host_cids) < self._remote_active_connection_id_limit: <4> self._host_cids.append( <5> QuicConnectionId( <6> cid=os.urandom(8), <7> sequence_number=self._host_cid_seq, <8> stateless_reset_token=os.urandom(16), <9> ) <10> ) <11> self._host_cid_seq += 1 <12>
===========unchanged ref 0=========== at: aioquic.connection QuicConnectionId(cid: bytes, sequence_number: int, stateless_reset_token: bytes=b"", was_sent: bool=False) at: aioquic.connection.QuicConnection.__init__ self._host_cids = [ QuicConnectionId( cid=os.urandom(8), sequence_number=0, stateless_reset_token=os.urandom(16), was_sent=True, ) ] self._host_cid_seq = 1 self._remote_active_connection_id_limit = 0 at: aioquic.connection.QuicConnection._parse_transport_parameters self._remote_active_connection_id_limit = ( quic_transport_parameters.active_connection_id_limit ) at: aioquic.connection.QuicConnectionId cid: bytes sequence_number: int stateless_reset_token: bytes = b"" was_sent: bool = False at: os urandom(size: int, /) -> bytes
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
278deb59892219d7495e4b6e3adbcadf8c291702
[http3] handle data on encoder / decoder streams
<32>:<add> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: <add> # fetch next frame <del> # fetch next frame <33>:<add> try: <del> try: <34>:<add> frame_type = buf.pull_uint_var() <del> frame_type = buf.pull_uint_var() <35>:<add> frame_length = buf.pull_uint_var() <del> frame_length = buf.pull_uint_var() <36>:<add> frame_data = buf.pull_bytes(frame_length) <del> frame_data = buf.pull_bytes(frame_length) <37>:<add> except BufferReadError: <del> except BufferReadError: <38>:<add> break <del> break <39>:<add> consumed = buf.tell() <del> consumed = buf.tell() <41>:<add> if (stream_id % 4) == 0: <del> if (stream_id % 4) == 0: <42>:<add> # client-initiated bidirectional streams carry requests and responses <del> #
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if ( <12> stream_is_unidirectional(stream_id) <13> and stream_id not in self._stream_types <14> ): <15> try: <16> stream_type = buf.pull_uint_var() <17> except BufferReadError: <18> break <19> consumed = buf.tell() <20> <21> if stream_type == StreamType.CONTROL: <22> assert self._peer_control_stream_id is None <23> self._peer_control_stream_id = stream_id <24> elif stream_type == StreamType.QPACK_DECODER: <25> assert self._peer_decoder_stream_id is None <26> self._peer_decoder_stream_id = stream_id <27> elif stream_type == StreamType.QPACK_ENCODER: <28> assert self._peer_encoder_stream_id is None <29> self._peer_encoder_stream_id = stream_id <30> self._stream_types[stream_id] = stream_type <31> <32> # fetch next frame <33> try: <34> frame_type = buf.pull_uint_var() <35> frame_length = buf.pull_uint_var() <36> frame_data = buf.pull_bytes(frame_length) <37> except BufferReadError: <38> break <39> consumed = buf.tell() <40> <41> if (stream_id % 4) == 0: <42> #</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: control, headers = self._decoder.feed_header(stream_id, frame_data) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get(Setting.QPACK_BLOCKED_STREAMS, 0), ) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ===========unchanged ref 1=========== ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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]
aioquic.h3.connection/H3Connection.send_headers
Modified
aiortc~aioquic
96099bc125790476e7fb26685a0c485fc3075163
[http3] send encoder and decoder stream data
<7>:<add> encoder, header = self._encoder.encode(stream_id, 0, headers) <del> control, header = self._encoder.encode(stream_id, 0, headers) <8>:<del> self._quic.send_stream_data( <9>:<del> stream_id, encode_frame(FrameType.HEADERS, header), False <10>:<del> ) <11>:<add> self._quic.send_stream_data(self._local_encoder_stream_id, encoder) <add> self._quic.send_stream_data(stream_id, encode_frame(FrameType.HEADERS, header))
# module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: <0> """ <1> Send headers on the given stream. <2> <3> To retrieve datagram which need to be sent over the network call the QUIC <4> connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` <5> method. <6> """ <7> control, header = self._encoder.encode(stream_id, 0, headers) <8> self._quic.send_stream_data( <9> stream_id, encode_frame(FrameType.HEADERS, header), False <10> ) <11>
===========unchanged ref 0=========== at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) encode_frame(frame_type: int, frame_data: bytes) -> bytes at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic self._encoder = Encoder() self._local_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) at: aioquic.h3.events Headers = List[Tuple[bytes, bytes]]
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
96099bc125790476e7fb26685a0c485fc3075163
[http3] send encoder and decoder stream data
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if ( <12> stream_is_unidirectional(stream_id) <13> and stream_id not in self._stream_types <14> ): <15> try: <16> stream_type = buf.pull_uint_var() <17> except BufferReadError: <18> break <19> consumed = buf.tell() <20> <21> if stream_type == StreamType.CONTROL: <22> assert self._peer_control_stream_id is None <23> self._peer_control_stream_id = stream_id <24> elif stream_type == StreamType.QPACK_DECODER: <25> assert self._peer_decoder_stream_id is None <26> self._peer_decoder_stream_id = stream_id <27> elif stream_type == StreamType.QPACK_ENCODER: <28> assert self._peer_encoder_stream_id is None <29> self._peer_encoder_stream_id = stream_id <30> self._stream_types[stream_id] = stream_type <31> <32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: <33> # fetch next frame <34> try: <35> frame_type = buf.pull_uint_var() <36> frame_length = buf.pull_uint_var() <37> frame_data = buf.pull_bytes(frame_length) <38> except BufferReadError: <39> break <40> </s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: control, headers = self._decoder.feed_header( stream_id, frame_data ) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get( Setting.QPACK_BLOCKED_STREAMS, 0 ), ) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: self._decoder.feed_encoder(data) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 2 <s> buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_decoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== at: aioquic.h3.connection.H3Connection._init_connection self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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] ===========changed ref 0=========== # module: aioquic.h3.connection class H3Connection: def send_headers(self, stream_id: int, headers: Headers) -> None: """ Send headers on the given stream. To retrieve datagram which need to be sent over the network call the QUIC connection's :meth:`~aioquic.connection.QuicConnection.datagrams_to_send` method. """ + encoder, header = self._encoder.encode(stream_id, 0, headers) - control, header = self._encoder.encode(stream_id, 0, headers) - self._quic.send_stream_data( - stream_id, encode_frame(FrameType.HEADERS, header), False - ) + self._quic.send_stream_data(self._local_encoder_stream_id, encoder) + self._quic.send_stream_data(stream_id, encode_frame(FrameType.HEADERS, header))
tests.test_h3/H3ConnectionTest.test_connect
Modified
aiortc~aioquic
c1db156be227ef336f3233f50327ec0fa96faef1
[http3] test using dynamic tables
<7>:<add> # make first request <del> # send request <8>:<del> stream_id = quic_client.get_next_available_stream_id() <9>:<del> h3_client.send_headers( <10>:<del> stream_id=stream_id, <11>:<del> headers=[ <12>:<del> (b":method", b"GET"), <13>:<del> (b":scheme", b"https"), <14>:<del> (b":authority", b"localhost"), <15>:<del> (b":path", b"/"), <16>:<del> ], <17>:<del> ) <18>:<del> h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19>:<add> self._make_request(h3_client, h3_server) <20>:<add> # make second request <del> # receive request <21>:<del> events = h3_transfer(quic_client, h3_server) <22>:<del> self.assertEqual(len(events), 2) <23>:<add> self._make_request(h3_client, h3_server) <24>:<del> self.assertTrue(isinstance(events[0], RequestReceived)) <25>:<del> self.assertEqual( <26>:<del> events[0].headers, <27>:<del> [ <28>:<del> (b":method", b"GET"), <29>:<del> (b":scheme", b"https"), <30>:<del> (b":authority", b"localhost"), <31>:<del> (b":path", b"/"), <32>:<del> ], <33>:<del> ) <34>:<del> self.assertEqual(events[0].stream_id, stream_id) <35>:<del> self.assertEqual(events[0].stream_ended, False) <36>:<add> # make third request -> dynamic table <add> self._make_request(h3_client, h3_server) <37>:<del> self.assertTrue(isinstance(events[1], DataReceived)) <38>:<del> self.assertEqual(events[1].data, b"") <39>:<del> self.assertEqual(events[1].stream_id,
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-22"]}, <2> server_options={"alpn_protocols": ["h3-22"]}, <3> ) as (quic_client, quic_server): <4> h3_client = H3Connection(quic_client) <5> h3_server = H3Connection(quic_server) <6> <7> # send request <8> stream_id = quic_client.get_next_available_stream_id() <9> h3_client.send_headers( <10> stream_id=stream_id, <11> headers=[ <12> (b":method", b"GET"), <13> (b":scheme", b"https"), <14> (b":authority", b"localhost"), <15> (b":path", b"/"), <16> ], <17> ) <18> h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) <19> <20> # receive request <21> events = h3_transfer(quic_client, h3_server) <22> self.assertEqual(len(events), 2) <23> <24> self.assertTrue(isinstance(events[0], RequestReceived)) <25> self.assertEqual( <26> events[0].headers, <27> [ <28> (b":method", b"GET"), <29> (b":scheme", b"https"), <30> (b":authority", b"localhost"), <31> (b":path", b"/"), <32> ], <33> ) <34> self.assertEqual(events[0].stream_id, stream_id) <35> self.assertEqual(events[0].stream_ended, False) <36> <37> self.assertTrue(isinstance(events[1], DataReceived)) <38> self.assertEqual(events[1].data, b"") <39> self.assertEqual(events[1].stream_id,</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_connect(self): # offset: 1 self.assertEqual(events[1].stream_ended, True) # send response h3_server.send_headers( stream_id=stream_id, headers=[ (b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"), ], ) h3_server.send_data( stream_id=stream_id, data=b"<html><body>hello</body></html>", end_stream=True, ) # receive response events = h3_transfer(quic_server, h3_client) self.assertEqual(len(events), 2) self.assertTrue(isinstance(events[0], ResponseReceived)) self.assertEqual( events[0].headers, [(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8")], ) 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"<html><body>hello</body></html>") self.assertEqual(events[1].stream_id, stream_id) self.assertEqual(events[1].stream_ended, True) ===========unchanged ref 0=========== at: aioquic.connection.QuicConnection get_next_available_stream_id(is_unidirectional=False) -> int at: aioquic.h3.connection.H3Connection send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.connection.H3Connection.__init__ self._quic = quic at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): + def _make_request(self, h3_client, h3_server): + quic_client = h3_client._quic + quic_server = h3_server._quic + + # send request + stream_id = quic_client.get_next_available_stream_id() + h3_client.send_headers( + stream_id=stream_id, + headers=[ + (b":method", b"GET"), + (b":scheme", b"https"), + (b":authority", b"localhost"), + (b":path", b"/"), + (b"x-foo", b"client"), + ], + ) + h3_client.send_data(stream_id=stream_id, data=b"", end_stream=True) + + # receive request + events = h3_transfer(quic_client, h3_server) + self.assertEqual(len(events), 2) + + self.assertTrue(isinstance(events[0], RequestReceived)) + self.assertEqual( + events[0].headers, + [ + (b":method", b"GET"), + (b":scheme", b"https"), + (b":authority", b"localhost"), + (b":path", b"/"), + (b"x-foo", b"client"), + ], + ) + 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) + + #</s> ===========changed ref 1=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): + def _make_request(self, h3_client, h3_server): # offset: 1 <s>id, stream_id) + self.assertEqual(events[1].stream_ended, True) + + # send response + h3_server.send_headers( + stream_id=stream_id, + headers=[ + (b":status", b"200"), + (b"content-type", b"text/html; charset=utf-8"), + (b"x-foo", b"server"), + ], + ) + h3_server.send_data( + stream_id=stream_id, + data=b"<html><body>hello</body></html>", + end_stream=True, + ) + + # receive response + events = h3_transfer(quic_server, h3_client) + self.assertEqual(len(events), 2) + + self.assertTrue(isinstance(events[0], ResponseReceived)) + self.assertEqual( + events[0].headers, + [ + (b":status", b"200"), + (b"content-type", b"text/html; charset=utf-8"), + (b"x-foo", b"server"), + ], + ) + 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"<html><body>hello</body></html>") + self.assertEqual(events[1].stream_id, stream_id) + self.assertEqual(events
examples.http3-client/run
Modified
aiortc~aioquic
23e7979dafbd1b6383d909d9df1e704e6b4e8530
[examples] add server and user-agent headers
<40>:<add> (b"user-agent", b"aioquic"),
# module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <18> is_client=True, <19> server_name=server_name, <20> **kwargs <21> ), <22> session_ticket_handler=save_session_ticket, <23> ) <24> quic.connect(server_addr, now=time.time()) <25> <26> # send request <27> http: HttpConnection <28> if legacy_http: <29> http = H0Connection(quic) <30> else: <31> http = H3Connection(quic) <32> stream_id = quic.get_next_available_stream_id() <33> http.send_headers( <34> stream_id=stream_id, <35> headers=[ <36> (b":method", b"GET"), <37> (b":scheme", parsed.scheme.encode("utf8")), <38> (b":authority", parsed.netloc.encode("utf8")), <39> (b":path", parsed.path.encode("utf8")), <40> ], <41> ) <42> http.send_data(stream_id=stream_id, data=b"", end_stream=True) <43> for data, addr in</s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): print(http_event) if isinstance(http_event, (DataReceived, ResponseReceived)): stream_ended = http_event.stream_ended event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None ===========unchanged ref 1=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] save_session_ticket(ticket) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: time time() -> float ===========unchanged ref 2=========== at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes
examples.http3-server/send_response
Modified
aiortc~aioquic
23e7979dafbd1b6383d909d9df1e704e6b4e8530
[examples] add server and user-agent headers
<8>:<add> (b"server", b"aioquic"),
# module: examples.http3-server def send_response( connection: HttpConnection, stream_id: int, data: bytes = b"", content_type: str = "text/html", status_code: int = 200, ) -> None: <0> """ <1> Send an HTTP response on a connection and stream. <2> """ <3> connection.send_headers( <4> stream_id=stream_id, <5> headers=[ <6> (b":status", str(status_code).encode("ascii")), <7> (b"content-type", content_type.encode("ascii")), <8> ], <9> ) <10> connection.send_data(stream_id=stream_id, data=data, end_stream=True) <11>
===========unchanged ref 0=========== at: aioquic.h0.connection.H0Connection send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection.H3Connection send_headers(stream_id: int, headers: Headers) -> None at: examples.http3-server HttpConnection = Union[H0Connection, H3Connection] ===========changed ref 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # parse URL parsed = urlparse(url) assert parsed.scheme == "https", "Only HTTPS URLs are supported." if ":" in parsed.netloc: server_name, port_str = parsed.netloc.split(":") port = int(port_str) else: server_name = parsed.netloc port = 443 # prepare socket server_addr = (socket.gethostbyname(server_name), port) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # prepare QUIC connection quic = QuicConnection( configuration=QuicConfiguration( alpn_protocols=["hq-22" if legacy_http else "h3-22"], is_client=True, server_name=server_name, **kwargs ), session_ticket_handler=save_session_ticket, ) quic.connect(server_addr, now=time.time()) # send request http: HttpConnection if legacy_http: http = H0Connection(quic) else: http = H3Connection(quic) stream_id = quic.get_next_available_stream_id() http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", parsed.scheme.encode("utf8")), (b":authority", parsed.netloc.encode("utf8")), (b":path", parsed.path.encode("utf8")), + (b"user-agent", b"aioquic"), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data</s> ===========changed ref 1=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 <s> data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): print(http_event) if isinstance(http_event, (DataReceived, ResponseReceived)): stream_ended = http_event.stream_ended event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr)
aioquic.tls/pull_client_hello
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<35>:<add> hello.psk_key_exchange_modes = pull_list( <del> hello.key_exchange_modes = pull_list( <36>:<add> buf, 1, partial(pull_psk_key_exchange_mode, buf) <del> buf, 1, partial(pull_key_exchange_mode, buf)
# module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> client_random = buf.pull_bytes(32) <4> <5> hello = ClientHello( <6> random=client_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), <9> compression_methods=pull_list( <10> buf, 1, partial(pull_compression_method, buf) <11> ), <12> ) <13> <14> # extensions <15> after_psk = False <16> <17> def pull_extension() -> None: <18> # pre_shared_key MUST be last <19> nonlocal after_psk <20> assert not after_psk <21> <22> extension_type = buf.pull_uint16() <23> extension_length = buf.pull_uint16() <24> if extension_type == ExtensionType.KEY_SHARE: <25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) <26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS: <27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) <28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: <29> hello.signature_algorithms = pull_list( <30> buf, 2, partial(pull_signature_algorithm, buf) <31> ) <32> elif extension_type == ExtensionType.SUPPORTED_GROUPS: <33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) <34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: <35> hello.key_exchange_modes = pull_list( <36> buf, 1, partial(pull_key_exchange_mode, buf) <37> </s>
===========below chunk 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_bytes(length: int) -> bytes pull_uint8() -> int pull_uint16() -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) pull_cipher_suite(buf: Buffer) -> CipherSuite pull_compression_method(buf: Buffer) -> CompressionMethod pull_group(buf: Buffer) -> Group pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm pull_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T] pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry pull_alpn_protocol(buf: Buffer) -> str pull_psk_identity(buf: Buffer) -> PskIdentity pull_psk_binder(buf: Buffer) -> bytes OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() ===========changed ref 0=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) + ===========changed ref 1=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 2=========== # module: aioquic.tls - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode: - return KeyExchangeMode(buf.pull_uint8()) - ===========changed ref 3=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 4=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 -
aioquic.tls/push_client_hello
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<22>:<add> if hello.psk_key_exchange_modes is not None: <add> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): <del> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): <23>:<add> push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) <del> push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes)
# module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: <0> buf.push_uint8(HandshakeType.CLIENT_HELLO) <1> with push_block(buf, 3): <2> buf.push_uint16(TLS_VERSION_1_2) <3> buf.push_bytes(hello.random) <4> push_opaque(buf, 1, hello.session_id) <5> push_list(buf, 2, buf.push_uint16, hello.cipher_suites) <6> push_list(buf, 1, buf.push_uint8, hello.compression_methods) <7> <8> # extensions <9> with push_block(buf, 2): <10> with push_extension(buf, ExtensionType.KEY_SHARE): <11> push_list(buf, 2, partial(push_key_share, buf), hello.key_share) <12> <13> with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): <14> push_list(buf, 1, buf.push_uint16, hello.supported_versions) <15> <16> with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): <17> push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) <18> <19> with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): <20> push_list(buf, 2, buf.push_uint16, hello.supported_groups) <21> <22> with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): <23> push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) <24> <25> if hello.server_name is not None: <26> with push_extension(buf, ExtensionType.SERVER_NAME): <27> with push_block(buf, 2): <28> buf.push_uint8(0) <29> push_opaque(buf, 2, hello.server_name.encode("ascii")) <30> <31> if hello.alpn_protocols is not None: <32> with push_extension(buf, Extension</s>
===========below chunk 0=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 push_list( buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols ) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): buf.push_bytes(extension_value) if hello.early_data: with push_extension(buf, ExtensionType.EARLY_DATA): pass # pre_shared_key MUST be last if hello.pre_shared_key is not None: with push_extension(buf, ExtensionType.PRE_SHARED_KEY): push_list( buf, 2, partial(push_psk_identity, buf), hello.pre_shared_key.identities, ) push_list( buf, 2, partial(push_psk_binder, buf), hello.pre_shared_key.binders, ) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer push_bytes(value: bytes) -> None push_uint8(value: int) -> None push_uint16(value: int) -> None at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) HandshakeType(x: Union[str, bytes, bytearray], base: int) push_block(buf: Buffer, capacity: int) -> Generator push_list(buf: Buffer, capacity: int, func: Callable[[T], None], values: Sequence[T]) -> None push_opaque(buf: Buffer, capacity: int, value: bytes) -> None push_extension(buf: Buffer, extension_type: int) -> Generator push_key_share(buf: Buffer, value: KeyShareEntry) -> None push_alpn_protocol(buf: Buffer, protocol: str) -> None push_psk_identity(buf: Buffer, entry: PskIdentity) -> None push_psk_binder(buf: Buffer, binder: bytes) -> None ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() ===========changed ref 0=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) + ===========changed ref 2=========== # module: aioquic.tls - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode: - return KeyExchangeMode(buf.pull_uint8()) - ===========changed ref 3=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 4=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 -
aioquic.tls/negotiate
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<5>:<add> if exc is not None: <add> raise exc <del> raise exc <6>:<add> return None
# module: aioquic.tls + def negotiate( + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T: + ) -> T: <0> if offered is not None: <1> for c in supported: <2> if c in offered: <3> return c <4> <5> raise exc <6>
===========unchanged ref 0=========== at: aioquic.tls T = TypeVar("T") Alert(*args: object) at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) + ===========changed ref 1=========== # module: aioquic.tls - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode: - return KeyExchangeMode(buf.pull_uint8()) - ===========changed ref 2=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 3=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 4=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 5=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: buf.push_uint8(HandshakeType.CLIENT_HELLO) with push_block(buf, 3): buf.push_uint16(TLS_VERSION_1_2) buf.push_bytes(hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, buf.push_uint16, hello.cipher_suites) push_list(buf, 1, buf.push_uint8, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, partial(push_key_share, buf), hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, buf.push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, buf.push_uint16, hello.supported_groups) + if hello.psk_key_exchange_modes is not None: + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque</s> ===========changed ref 6=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 <s>NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque(buf, 2, hello.server_name.encode("ascii")) if hello.alpn_protocols is not None: with push_extension(buf, ExtensionType.ALPN): push_list( buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols ) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): buf.push_bytes(extension_value) if hello.early_data: with push_extension(buf, ExtensionType.EARLY_DATA): pass # pre_shared_key MUST be last if hello.pre_shared_key is not None: with push_extension(buf, ExtensionType.PRE_SHARED_KEY): push_list( buf, 2, partial(push_psk_identity, buf), hello.pre_shared_key.identities, ) push_list( buf, 2, partial(push_psk_binder, buf), hello.pre_shared_key.binders, ) ===========changed ref 7=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), compression_methods=pull_list( buf, 1, partial(pull_compression_method, buf) ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list( buf, 2, partial(pull_signature_algorithm, buf) ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: + hello.psk_key_exchange_modes = pull_list( - hello.key_exchange_modes = pull_list( + buf, 1, partial(pull_psk_key_exchange_mode, buf) - buf, 1, partial(pull_key_exchange_mode,</s>
aioquic.tls/Context.__init__
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<28>:<add> self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] <del> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE]
# module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): <0> self.alpn_negotiated: Optional[str] = None <1> self.alpn_protocols: Optional[List[str]] = None <2> self.certificate: Optional[x509.Certificate] = None <3> self.certificate_private_key: Optional[ <4> Union[dsa.DSAPublicKey, ec.EllipticCurvePublicKey, rsa.RSAPublicKey] <5> ] = None <6> self.early_data_accepted = False <7> self.handshake_extensions: List[Extension] = [] <8> self.key_schedule: Optional[KeySchedule] = None <9> self.received_extensions: Optional[List[Extension]] = None <10> self.session_ticket: Optional[SessionTicket] = None <11> self.server_name: Optional[str] = None <12> <13> # callbacks <14> self.alpn_cb: Optional[AlpnHandler] = None <15> self.get_session_ticket_cb: Optional[SessionTicketFetcher] = None <16> self.new_session_ticket_cb: Optional[SessionTicketHandler] = None <17> self.update_traffic_key_cb: Callable[ <18> [Direction, Epoch, CipherSuite, bytes], None <19> ] = lambda d, e, c, s: None <20> <21> # supported parameters <22> self._cipher_suites = [ <23> CipherSuite.AES_256_GCM_SHA384, <24> CipherSuite.AES_128_GCM_SHA256, <25> CipherSuite.CHACHA20_POLY1305_SHA256, <26> ] <27> self._compression_methods = [CompressionMethod.NULL] <28> self._key_exchange_modes = [KeyExchangeMode.PSK_DHE_KE] <29> self._signature_algorithms = [ <30> SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <31> SignatureAlgorithm.ECDSA_SECP256R1</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def __init__( self, is_client: bool, logger: Optional[Union[logging.Logger, logging.LoggerAdapter]] = None, ): # offset: 1 SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] # state self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._new_session_ticket: Optional[NewSessionTicket] = None self._peer_certificate: Optional[x509.Certificate] = None self._receive_buffer = b"" self._session_resumed = False self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.__logger = logger self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None if is_client: self.client_random = os.urandom(32) self.session_id = os.urandom(32) self.state = State.CLIENT_HANDSHAKE_START else: self.client_random = None self.session_id = None self.state = State.SERVER_EXPECT_CLIENT_HELLO ===========unchanged ref 0=========== at: aioquic.tls TLS_VERSION_1_3 = 0x0304 Direction() Epoch() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) 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)) KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) 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)) AlpnHandler = Callable[[str], None] ===========unchanged ref 1=========== at: aioquic.tls.Context._client_handle_certificate self._peer_certificate = x509.load_der_x509_certificate( certificate.certificates[0][0], backend=default_backend() ) at: aioquic.tls.Context._client_handle_encrypted_extensions self.alpn_negotiated = encrypted_extensions.alpn_protocol self.early_data_accepted = encrypted_extensions.early_data self.received_extensions = encrypted_extensions.other_extensions at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) self._session_resumed = True self._key_schedule_psk = None self._key_schedule_proxy = None at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.alpn_negotiated = negotiate( self.alpn_protocols, peer_hello.alpn_protocols, AlertHandshakeFailure("No common ALPN protocols"), ) self.client_random = peer_hello.random ===========unchanged ref 2=========== self.session_id = peer_hello.session_id self.received_extensions = peer_hello.other_extensions self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self.early_data_accepted = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) self._new_session_ticket = NewSessionTicket( ticket_lifetime=86400, ticket_age_add=struct.unpack("I", os.urandom(4))[0], ticket_nonce=b"", ticket=os.urandom(64), max_early_data_size=0xFFFFFFFF, ) at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.Context.handle_message self._receive_buffer += input_data self._receive_buffer = self._receive_buffer[message_length:] at: logging Logger(name: str, level: _Level=...) LoggerAdapter(logger: Logger, extra: Mapping[str, Any]) at: os urandom(size: int, /) -> bytes at: typing Callable = _CallableType(collections.abc.Callable, 2) List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: aioquic.tls + def negotiate( + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T: + ) -> T: if offered is not None: for c in supported: if c in offered: return c + if exc is not None: + raise exc - raise exc + return None ===========changed ref 1=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) +
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<23>:<del> key_exchange_modes=self._key_exchange_modes, <25>:<add> psk_key_exchange_modes=self._psk_key_exchange_modes <add> if (self.session_ticket or self.new_session_ticket_cb is not None) <add> else None,
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_exchange_modes=self._key_exchange_modes, <24> key_share=key_share, <25> server_name=self.server_name, <26> signature_algorithms=self._signature_algorithms, <27> supported_groups=supported_groups, <28> supported_versions=self._supported_versions, <29> other_extensions=self.handshake_extensions, <30> ) <31> <32> # PSK <33> if self.session_ticket and self.session_ticket.is_valid: <34> self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) <35> self._key_schedule_psk.</s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # update hello if self.session_ticket.max_early_data_size is not None: hello.early_data = True hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) # serialize hello without binder tmp_buf = Buffer(capacity=1024) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) # calculate early data key if hello.early_data: early_key = self._key_schedule_psk.derive_secret(b"c e traffic") self.update_traffic_key_cb( Direction.ENCRYPT, Epoch.ZERO_RTT, self._key_schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 2 <s>.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Direction() Epoch() Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) KeyShareEntry = Tuple[Group, bytes] OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None KeySchedule(cipher_suite: CipherSuite) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry at: aioquic.tls.ClientHello early_data: bool = False ===========unchanged ref 1=========== pre_shared_key: Optional[OfferedPsks] = None at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None self.client_random = None self.client_random = os.urandom(32) self.session_id = None self.session_id = os.urandom(32)
tests.test_tls/ContextTest._handshake
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<5>:<add> self.assertGreaterEqual(len(server_input), 213) <del> self.assertGreaterEqual(len(server_input), 219)
# module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): <0> # send client hello <1> client_buf = create_buffers() <2> client.handle_message(b"", client_buf) <3> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <4> server_input = merge_buffers(client_buf) <5> self.assertGreaterEqual(len(server_input), 219) <6> self.assertLessEqual(len(server_input), 264) <7> reset_buffers(client_buf) <8> <9> # handle client hello <10> # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <11> server_buf = create_buffers() <12> server.handle_message(server_input, server_buf) <13> self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) <14> client_input = merge_buffers(server_buf) <15> self.assertGreaterEqual(len(client_input), 600) <16> self.assertLessEqual(len(client_input), 2316) <17> <18> reset_buffers(server_buf) <19> <20> # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) <21> # send finished <22> client.handle_message(client_input, client_buf) <23> self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) <24> server_input = merge_buffers(client_buf) <25> self.assertEqual(len(server_input), 52) <26> reset_buffers(client_buf) <27> <28> # handle finished <29> server.handle_message(server_input, server_buf) <30> self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) <31> client_input = merge_buffers(server_buf) <32> self.assertEqual(len(client_input), 0) <33> <34> # check keys match <35> self.assertEqual(client._dec_key, server._enc_</s>
===========below chunk 0=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # offset: 1 self.assertEqual(client._enc_key, server._dec_key) # check cipher suite self.assertEqual( client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) self.assertEqual( server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) ===========unchanged ref 0=========== at: aioquic.tls State() CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) at: aioquic.tls.Context handle_message(input_data: bytes, output_buf: Dict[Epoch, Buffer]) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._enc_key: Optional[bytes] = None self._dec_key: Optional[bytes] = None self.state = State.CLIENT_HANDSHAKE_START self.state = State.SERVER_EXPECT_CLIENT_HELLO at: aioquic.tls.Context._client_handle_finished self._enc_key = next_enc_key at: aioquic.tls.Context._client_handle_hello self.key_schedule = self._key_schedule_psk self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) at: aioquic.tls.Context._server_handle_finished self._dec_key = self._next_dec_key at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) at: aioquic.tls.Context._set_state self.state = state at: aioquic.tls.Context._setup_traffic_protection self._enc_key = key self._dec_key = key at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str ===========unchanged ref 1=========== _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertGreaterEqual(a: Any, b: Any, msg: Any=...) -> None assertLessEqual(a: Any, b: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode: - return KeyExchangeMode(buf.pull_uint8()) - ===========changed ref 1=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) + ===========changed ref 2=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 3=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 4=========== # module: aioquic.tls + def negotiate( + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T: + ) -> T: if offered is not None: for c in supported: if c in offered: return c + if exc is not None: + raise exc - raise exc + return None ===========changed ref 5=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 6=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: buf.push_uint8(HandshakeType.CLIENT_HELLO) with push_block(buf, 3): buf.push_uint16(TLS_VERSION_1_2) buf.push_bytes(hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, buf.push_uint16, hello.cipher_suites) push_list(buf, 1, buf.push_uint8, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, partial(push_key_share, buf), hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, buf.push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, buf.push_uint16, hello.supported_groups) + if hello.psk_key_exchange_modes is not None: + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque</s>
tests.test_tls/ContextTest.test_handshake_with_alpn_fail
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<11>:<add> self.assertEqual(len(server_input), 258) <del> self.assertEqual(len(server_input), 264)
# module: tests.test_tls class ContextTest(TestCase): def test_handshake_with_alpn_fail(self): <0> client = self.create_client() <1> client.alpn_protocols = ["hq-20"] <2> <3> server = self.create_server() <4> server.alpn_protocols = ["h3-20"] <5> <6> # send client hello <7> client_buf = create_buffers() <8> client.handle_message(b"", client_buf) <9> self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) <10> server_input = merge_buffers(client_buf) <11> self.assertEqual(len(server_input), 264) <12> reset_buffers(client_buf) <13> <14> # handle client hello <15> # send server hello, encrypted extensions, certificate, certificate verify, finished <16> server_buf = create_buffers() <17> with self.assertRaises(tls.AlertHandshakeFailure) as cm: <18> server.handle_message(server_input, server_buf) <19> self.assertEqual(str(cm.exception), "No common ALPN protocols") <20>
===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) State() at: tests.test_tls create_buffers() merge_buffers(buffers) reset_buffers(buffers) at: tests.test_tls.ContextTest create_client() create_server() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertRaises(expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], msg: Any=...) -> _AssertRaisesContext[_E] assertRaises(expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None at: unittest.case._AssertRaisesContext.__exit__ self.exception = exc_value.with_traceback(None) ===========changed ref 0=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # send client hello client_buf = create_buffers() client.handle_message(b"", client_buf) self.assertEqual(client.state, State.CLIENT_EXPECT_SERVER_HELLO) server_input = merge_buffers(client_buf) + self.assertGreaterEqual(len(server_input), 213) - self.assertGreaterEqual(len(server_input), 219) self.assertLessEqual(len(server_input), 264) reset_buffers(client_buf) # handle client hello # send server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) server_buf = create_buffers() server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_EXPECT_FINISHED) client_input = merge_buffers(server_buf) self.assertGreaterEqual(len(client_input), 600) self.assertLessEqual(len(client_input), 2316) reset_buffers(server_buf) # handle server hello, encrypted extensions, certificate, certificate verify, finished, (session ticket) # send finished client.handle_message(client_input, client_buf) self.assertEqual(client.state, State.CLIENT_POST_HANDSHAKE) server_input = merge_buffers(client_buf) self.assertEqual(len(server_input), 52) reset_buffers(client_buf) # handle finished server.handle_message(server_input, server_buf) self.assertEqual(server.state, State.SERVER_POST_HANDSHAKE) client_input = merge_buffers(server_buf) self.assertEqual(len(client_input), 0) # check keys match self.assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._</s> ===========changed ref 1=========== # module: tests.test_tls class ContextTest(TestCase): def _handshake(self, client, server): # offset: 1 <s>assertEqual(client._dec_key, server._enc_key) self.assertEqual(client._enc_key, server._dec_key) # check cipher suite self.assertEqual( client.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) self.assertEqual( server.key_schedule.cipher_suite, tls.CipherSuite.AES_256_GCM_SHA384 ) ===========changed ref 2=========== # module: aioquic.tls - def pull_key_exchange_mode(buf: Buffer) -> KeyExchangeMode: - return KeyExchangeMode(buf.pull_uint8()) - ===========changed ref 3=========== # module: aioquic.tls + def pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode: + return PskKeyExchangeMode(buf.pull_uint8()) + ===========changed ref 4=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 5=========== # module: aioquic.tls - class KeyExchangeMode(IntEnum): - PSK_KE = 0 - PSK_DHE_KE = 1 - ===========changed ref 6=========== # module: aioquic.tls + def negotiate( + supported: List[T], offered: Optional[List[T]], exc: Optional[Alert] = None - def negotiate(supported: List[T], offered: Optional[List[T]], exc: Alert) -> T: + ) -> T: if offered is not None: for c in supported: if c in offered: return c + if exc is not None: + raise exc - raise exc + return None ===========changed ref 7=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 8=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: buf.push_uint8(HandshakeType.CLIENT_HELLO) with push_block(buf, 3): buf.push_uint16(TLS_VERSION_1_2) buf.push_bytes(hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, buf.push_uint16, hello.cipher_suites) push_list(buf, 1, buf.push_uint8, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, partial(push_key_share, buf), hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, buf.push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, buf.push_uint16, hello.supported_groups) + if hello.psk_key_exchange_modes is not None: + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque</s>
tests.test_tls/TlsTest.test_pull_client_hello
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<28>:<del> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])
# module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello(self): <0> buf = Buffer(data=load("tls_client_hello.bin")) <1> hello = pull_client_hello(buf) <2> self.assertTrue(buf.eof()) <3> <4> self.assertEqual( <5> hello.random, <6> binascii.unhexlify( <7> "18b2b23bf3e44b5d52ccfe7aecbc5ff14eadc3d349fabf804d71f165ae76e7d5" <8> ), <9> ) <10> self.assertEqual( <11> hello.session_id, <12> binascii.unhexlify( <13> "9aee82a2d186c1cb32a329d9dcfe004a1a438ad0485a53c6bfcf55c132a23235" <14> ), <15> ) <16> self.assertEqual( <17> hello.cipher_suites, <18> [ <19> tls.CipherSuite.AES_256_GCM_SHA384, <20> tls.CipherSuite.AES_128_GCM_SHA256, <21> tls.CipherSuite.CHACHA20_POLY1305_SHA256, <22> ], <23> ) <24> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL]) <25> <26> # extensions <27> self.assertEqual(hello.alpn_protocols, None) <28> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE]) <29> self.assertEqual( <30> hello.key_share, <31> [ <32> ( <33> tls.Group.SECP256R1, <34> binascii.unhexlify( <35> "047bfea344467535054263b75def60cffa82405a211b68d1eb8d1d944e67aef8" <36> "93c7665a54</s>
===========below chunk 0=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello(self): # offset: 1 "b0" ), ) ], ) self.assertEqual(hello.server_name, None) self.assertEqual( hello.signature_algorithms, [ tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA1, ], ) self.assertEqual(hello.supported_groups, [tls.Group.SECP256R1]) self.assertEqual( hello.supported_versions, [ tls.TLS_VERSION_1_3, tls.TLS_VERSION_1_3_DRAFT_28, tls.TLS_VERSION_1_3_DRAFT_27, tls.TLS_VERSION_1_3_DRAFT_26, ], ) self.assertEqual( hello.other_extensions, [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ], ) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool at: aioquic.tls TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_client_hello(buf: Buffer) -> ClientHello at: binascii unhexlify(hexstr: _Ascii, /) -> bytes ===========unchanged ref 1=========== at: tests.test_tls CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff0000110031000500048010000000060004801000000007000480100000000" b"4000481000000000100024258000800024064000a00010a" ) at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), compression_methods=pull_list( buf, 1, partial(pull_compression_method, buf) ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list( buf, 2, partial(pull_signature_algorithm, buf) ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: + hello.psk_key_exchange_modes = pull_list( - hello.key_exchange_modes = pull_list( + buf, 1, partial(pull_psk_key_exchange_mode, buf) - buf, 1, partial(pull_key_exchange_mode,</s> ===========changed ref 1=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 <s>pull_psk_key_exchange_mode, buf) - buf, 1, partial(pull_key_exchange_mode, buf) ) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello
tests.test_tls/TlsTest.test_pull_client_hello_with_alpn
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<25>:<del> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])
# module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): <0> buf = Buffer(data=load("tls_client_hello_with_alpn.bin")) <1> hello = pull_client_hello(buf) <2> self.assertTrue(buf.eof()) <3> <4> self.assertEqual( <5> hello.random, <6> binascii.unhexlify( <7> "ed575c6fbd599c4dfaabd003dca6e860ccdb0e1782c1af02e57bf27cb6479b76" <8> ), <9> ) <10> self.assertEqual(hello.session_id, b"") <11> self.assertEqual( <12> hello.cipher_suites, <13> [ <14> tls.CipherSuite.AES_128_GCM_SHA256, <15> tls.CipherSuite.AES_256_GCM_SHA384, <16> tls.CipherSuite.CHACHA20_POLY1305_SHA256, <17> tls.CipherSuite.EMPTY_RENEGOTIATION_INFO_SCSV, <18> ], <19> ) <20> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL]) <21> <22> # extensions <23> self.assertEqual(hello.alpn_protocols, ["h3-19"]) <24> self.assertEqual(hello.early_data, False) <25> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE]) <26> self.assertEqual( <27> hello.key_share, <28> [ <29> ( <30> tls.Group.SECP256R1, <31> binascii.unhexlify( <32> "048842315c437bb0ce2929c816fee4e942ec5cb6db6a6b9bf622680188ebb0d4" <33> "b652e69033f71686aa01cbc79155866e264c9</s>
===========below chunk 0=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_alpn(self): # offset: 1 "22" ), ) ], ) self.assertEqual(hello.server_name, "cloudflare-quic.com") self.assertEqual( hello.signature_algorithms, [ tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, tls.SignatureAlgorithm.ECDSA_SECP384R1_SHA384, tls.SignatureAlgorithm.ECDSA_SECP521R1_SHA512, tls.SignatureAlgorithm.ED25519, tls.SignatureAlgorithm.ED448, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA256, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA384, tls.SignatureAlgorithm.RSA_PSS_PSS_SHA512, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA384, tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA512, tls.SignatureAlgorithm.RSA_PKCS1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA384, tls.SignatureAlgorithm.RSA_PKCS1_SHA512, ], ) self.assertEqual( hello.supported_groups, [ tls.Group.SECP256R1, tls.Group.X25519, tls.Group.SECP384R1, tls.Group.SECP521R1, ], ) self.assertEqual(hello.supported_versions, [tls.TLS_VERSION_1_3]) # serialize buf = Buffer(1000) push_client_hello(buf, hello) self.assertEqual(len(buf.data), len(load("tls_client_hello_with_alpn.bin"))) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool at: aioquic.tls TLS_VERSION_1_3 = 0x0304 CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_client_hello(buf: Buffer) -> ClientHello at: binascii unhexlify(hexstr: _Ascii, /) -> bytes at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), compression_methods=pull_list( buf, 1, partial(pull_compression_method, buf) ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list( buf, 2, partial(pull_signature_algorithm, buf) ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: + hello.psk_key_exchange_modes = pull_list( - hello.key_exchange_modes = pull_list( + buf, 1, partial(pull_psk_key_exchange_mode, buf) - buf, 1, partial(pull_key_exchange_mode,</s> ===========changed ref 1=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 <s>pull_psk_key_exchange_mode, buf) - buf, 1, partial(pull_key_exchange_mode, buf) ) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello
tests.test_tls/TlsTest.test_pull_client_hello_with_sni
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<28>:<del> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE])
# module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_sni(self): <0> buf = Buffer(data=load("tls_client_hello_with_sni.bin")) <1> hello = pull_client_hello(buf) <2> self.assertTrue(buf.eof()) <3> <4> self.assertEqual( <5> hello.random, <6> binascii.unhexlify( <7> "987d8934140b0a42cc5545071f3f9f7f61963d7b6404eb674c8dbe513604346b" <8> ), <9> ) <10> self.assertEqual( <11> hello.session_id, <12> binascii.unhexlify( <13> "26b19bdd30dbf751015a3a16e13bd59002dfe420b799d2a5cd5e11b8fa7bcb66" <14> ), <15> ) <16> self.assertEqual( <17> hello.cipher_suites, <18> [ <19> tls.CipherSuite.AES_256_GCM_SHA384, <20> tls.CipherSuite.AES_128_GCM_SHA256, <21> tls.CipherSuite.CHACHA20_POLY1305_SHA256, <22> ], <23> ) <24> self.assertEqual(hello.compression_methods, [tls.CompressionMethod.NULL]) <25> <26> # extensions <27> self.assertEqual(hello.alpn_protocols, None) <28> self.assertEqual(hello.key_exchange_modes, [tls.KeyExchangeMode.PSK_DHE_KE]) <29> self.assertEqual( <30> hello.key_share, <31> [ <32> ( <33> tls.Group.SECP256R1, <34> binascii.unhexlify( <35> "04b62d70f907c814cd65d0f73b8b991f06b70c77153f548410a191d2b19764a2" <36> </s>
===========below chunk 0=========== # module: tests.test_tls class TlsTest(TestCase): def test_pull_client_hello_with_sni(self): # offset: 1 "40" ), ) ], ) self.assertEqual(hello.server_name, "cloudflare-quic.com") self.assertEqual( hello.signature_algorithms, [ tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA256, tls.SignatureAlgorithm.RSA_PKCS1_SHA1, ], ) self.assertEqual(hello.supported_groups, [tls.Group.SECP256R1]) self.assertEqual( hello.supported_versions, [ tls.TLS_VERSION_1_3, tls.TLS_VERSION_1_3_DRAFT_28, tls.TLS_VERSION_1_3_DRAFT_27, tls.TLS_VERSION_1_3_DRAFT_26, ], ) self.assertEqual( hello.other_extensions, [ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ], ) # serialize buf = Buffer(1000) push_client_hello(buf, hello) self.assertEqual(buf.data, load("tls_client_hello_with_sni.bin")) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool at: aioquic.tls TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_client_hello(buf: Buffer) -> ClientHello push_client_hello(buf: Buffer, hello: ClientHello) -> None at: binascii unhexlify(hexstr: _Ascii, /) -> bytes ===========unchanged ref 1=========== at: tests.test_tls CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff0000110031000500048010000000060004801000000007000480100000000" b"4000481000000000100024258000800024064000a00010a" ) at: tests.test_tls.TlsTest.test_pull_client_hello_with_psk hello = pull_client_hello(buf) at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: buf.push_uint8(HandshakeType.CLIENT_HELLO) with push_block(buf, 3): buf.push_uint16(TLS_VERSION_1_2) buf.push_bytes(hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, buf.push_uint16, hello.cipher_suites) push_list(buf, 1, buf.push_uint8, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, partial(push_key_share, buf), hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, buf.push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, buf.push_uint16, hello.supported_groups) + if hello.psk_key_exchange_modes is not None: + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque</s> ===========changed ref 1=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: # offset: 1 <s>NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque(buf, 2, hello.server_name.encode("ascii")) if hello.alpn_protocols is not None: with push_extension(buf, ExtensionType.ALPN): push_list( buf, 2, partial(push_alpn_protocol, buf), hello.alpn_protocols ) for extension_type, extension_value in hello.other_extensions: with push_extension(buf, extension_type): buf.push_bytes(extension_value) if hello.early_data: with push_extension(buf, ExtensionType.EARLY_DATA): pass # pre_shared_key MUST be last if hello.pre_shared_key is not None: with push_extension(buf, ExtensionType.PRE_SHARED_KEY): push_list( buf, 2, partial(push_psk_identity, buf), hello.pre_shared_key.identities, ) push_list( buf, 2, partial(push_psk_binder, buf), hello.pre_shared_key.binders, )
tests.test_tls/TlsTest.test_push_client_hello
Modified
aiortc~aioquic
0ba9b1c08cda47da8e51f68e96caeae600658679
[tls] make PSK support optional
<13>:<del> key_exchange_modes=[tls.KeyExchangeMode.PSK_DHE_KE], <24>:<add> psk_key_exchange_modes=[tls.PskKeyExchangeMode.PSK_DHE_KE],
# module: tests.test_tls class TlsTest(TestCase): def test_push_client_hello(self): <0> hello = ClientHello( <1> random=binascii.unhexlify( <2> "18b2b23bf3e44b5d52ccfe7aecbc5ff14eadc3d349fabf804d71f165ae76e7d5" <3> ), <4> session_id=binascii.unhexlify( <5> "9aee82a2d186c1cb32a329d9dcfe004a1a438ad0485a53c6bfcf55c132a23235" <6> ), <7> cipher_suites=[ <8> tls.CipherSuite.AES_256_GCM_SHA384, <9> tls.CipherSuite.AES_128_GCM_SHA256, <10> tls.CipherSuite.CHACHA20_POLY1305_SHA256, <11> ], <12> compression_methods=[tls.CompressionMethod.NULL], <13> key_exchange_modes=[tls.KeyExchangeMode.PSK_DHE_KE], <14> key_share=[ <15> ( <16> tls.Group.SECP256R1, <17> binascii.unhexlify( <18> "047bfea344467535054263b75def60cffa82405a211b68d1eb8d1d944e67aef8" <19> "93c7665a5473d032cfaf22a73da28eb4aacae0017ed12557b5791f98a1e84f15" <20> "b0" <21> ), <22> ) <23> ], <24> signature_algorithms=[ <25> tls.SignatureAlgorithm.RSA_PSS_RSAE_SHA256, <26> tls.SignatureAlgorithm.ECDSA_SECP256R1_SHA256, <27> tls.SignatureAlgorithm.RSA_PKCS1_SHA256, <28> tls.SignatureAlgorithm.RSA_PKCS1_SHA1, <29> ], <30> </s>
===========below chunk 0=========== # module: tests.test_tls class TlsTest(TestCase): def test_push_client_hello(self): # offset: 1 supported_versions=[ tls.TLS_VERSION_1_3, tls.TLS_VERSION_1_3_DRAFT_28, tls.TLS_VERSION_1_3_DRAFT_27, tls.TLS_VERSION_1_3_DRAFT_26, ], other_extensions=[ ( tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS, CLIENT_QUIC_TRANSPORT_PARAMETERS, ) ], ) buf = Buffer(1000) push_client_hello(buf, hello) self.assertEqual(buf.data, load("tls_client_hello.bin")) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic.tls TLS_VERSION_1_3 = 0x0304 TLS_VERSION_1_3_DRAFT_28 = 0x7F1C TLS_VERSION_1_3_DRAFT_27 = 0x7F1B TLS_VERSION_1_3_DRAFT_26 = 0x7F1A CipherSuite(x: Union[str, bytes, bytearray], base: int) CipherSuite(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) CompressionMethod(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) PskKeyExchangeMode(x: Union[str, bytes, bytearray], base: int) PskKeyExchangeMode(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) SignatureAlgorithm(x: Union[str, bytes, bytearray], base: int) SignatureAlgorithm(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[CipherSuite], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: binascii unhexlify(hexstr: _Ascii, /) -> bytes ===========unchanged ref 2=========== at: tests.test_tls CLIENT_QUIC_TRANSPORT_PARAMETERS = binascii.unhexlify( b"ff0000110031000500048010000000060004801000000007000480100000000" b"4000481000000000100024258000800024064000a00010a" ) at: tests.test_tls.TlsTest.test_pull_client_hello_with_sni hello = pull_client_hello(buf) at: tests.utils load(name) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False - key_exchange_modes: Optional[List[KeyExchangeMode]] = None key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None + psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls def push_client_hello(buf: Buffer, hello: ClientHello) -> None: buf.push_uint8(HandshakeType.CLIENT_HELLO) with push_block(buf, 3): buf.push_uint16(TLS_VERSION_1_2) buf.push_bytes(hello.random) push_opaque(buf, 1, hello.session_id) push_list(buf, 2, buf.push_uint16, hello.cipher_suites) push_list(buf, 1, buf.push_uint8, hello.compression_methods) # extensions with push_block(buf, 2): with push_extension(buf, ExtensionType.KEY_SHARE): push_list(buf, 2, partial(push_key_share, buf), hello.key_share) with push_extension(buf, ExtensionType.SUPPORTED_VERSIONS): push_list(buf, 1, buf.push_uint16, hello.supported_versions) with push_extension(buf, ExtensionType.SIGNATURE_ALGORITHMS): push_list(buf, 2, buf.push_uint16, hello.signature_algorithms) with push_extension(buf, ExtensionType.SUPPORTED_GROUPS): push_list(buf, 2, buf.push_uint16, hello.supported_groups) + if hello.psk_key_exchange_modes is not None: + with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): - with push_extension(buf, ExtensionType.PSK_KEY_EXCHANGE_MODES): + push_list(buf, 1, buf.push_uint8, hello.psk_key_exchange_modes) - push_list(buf, 1, buf.push_uint8, hello.key_exchange_modes) if hello.server_name is not None: with push_extension(buf, ExtensionType.SERVER_NAME): with push_block(buf, 2): buf.push_uint8(0) push_opaque</s>
docs.http_client/http_client
Modified
aiortc~aioquic
d9f0026d04752d629421b8fa9518f0b06a49980e
[examples] output HTTP response to stdout
<6>:<add> sys.stdout.buffer.write(response) <del> print(response.decode("utf8"))
# module: docs.http_client def http_client(host, port): <0> async with connect(host, port) as connection: <1> reader, writer = await connection.create_stream() <2> writer.write(b"GET /\r\n") <3> writer.write_eof() <4> <5> response = await reader.read() <6> print(response.decode("utf8")) <7>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: asyncio.streams.StreamReader _source_traceback = None read(n: int=...) -> bytes at: asyncio.streams.StreamWriter write(data: bytes) -> None write_eof() -> None
examples.http3-client/run
Modified
aiortc~aioquic
d9f0026d04752d629421b8fa9518f0b06a49980e
[examples] output HTTP response to stdout
# module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <18> is_client=True, <19> server_name=server_name, <20> **kwargs <21> ), <22> session_ticket_handler=save_session_ticket, <23> ) <24> quic.connect(server_addr, now=time.time()) <25> <26> # send request <27> http: HttpConnection <28> if legacy_http: <29> http = H0Connection(quic) <30> else: <31> http = H3Connection(quic) <32> stream_id = quic.get_next_available_stream_id() <33> http.send_headers( <34> stream_id=stream_id, <35> headers=[ <36> (b":method", b"GET"), <37> (b":scheme", parsed.scheme.encode("utf8")), <38> (b":authority", parsed.netloc.encode("utf8")), <39> (b":path", parsed.path.encode("utf8")), <40> (b"user-agent", b"aioquic"), <41> ], <42> ) <43> http.send_data(stream_id=stream_id, data</s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): print(http_event) if isinstance(http_event, (DataReceived, ResponseReceived)): stream_ended = http_event.stream_ended event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.h0.connection H0Connection(quic: QuicConnection) ===========unchanged ref 1=========== at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] save_session_ticket(ticket) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.TextIO __slots__ = () ===========unchanged ref 2=========== at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: docs.http_client def http_client(host, port): async with connect(host, port) as connection: reader, writer = await connection.create_stream() writer.write(b"GET /\r\n") writer.write_eof() response = await reader.read() + sys.stdout.buffer.write(response) - print(response.decode("utf8"))
examples.client/run
Modified
aiortc~aioquic
d9f0026d04752d629421b8fa9518f0b06a49980e
[examples] output HTTP response to stdout
<19>:<add> sys.stdout.buffer.write(response) <del> print(response.decode("utf8"))
# module: examples.client def run(url, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> async with connect(server_name, port, **kwargs) as connection: <11> # perform HTTP/0.9 request <12> reader, writer = await connection.create_stream() <13> writer.write(("GET %s\r\n" % parsed.path).encode("utf8")) <14> writer.write_eof() <15> <16> start = time.time() <17> response = await reader.read() <18> elapsed = time.time() - start <19> print(response.decode("utf8")) <20> <21> octets = len(response) <22> logger.info( <23> "Received %d bytes in %.1f s (%.3f Mbps)" <24> % (octets, elapsed, octets * 8 / elapsed / 1000000) <25> ) <26>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol create_stream(is_unidirectional: bool=False) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter] at: asyncio.streams.StreamReader _source_traceback = None read(n: int=...) -> bytes at: asyncio.streams.StreamWriter write(data: bytes) -> None write_eof() -> None at: examples.client logger = logging.getLogger("client") at: logging.Logger info(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: sys stdout: TextIO at: time time() -> float at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.TextIO __slots__ = () at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: docs.http_client def http_client(host, port): async with connect(host, port) as connection: reader, writer = await connection.create_stream() writer.write(b"GET /\r\n") writer.write_eof() response = await reader.read() + sys.stdout.buffer.write(response) - print(response.decode("utf8")) ===========changed ref 1=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # parse URL parsed = urlparse(url) assert parsed.scheme == "https", "Only HTTPS URLs are supported." if ":" in parsed.netloc: server_name, port_str = parsed.netloc.split(":") port = int(port_str) else: server_name = parsed.netloc port = 443 # prepare socket server_addr = (socket.gethostbyname(server_name), port) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # prepare QUIC connection quic = QuicConnection( configuration=QuicConfiguration( alpn_protocols=["hq-22" if legacy_http else "h3-22"], is_client=True, server_name=server_name, **kwargs ), session_ticket_handler=save_session_ticket, ) quic.connect(server_addr, now=time.time()) # send request http: HttpConnection if legacy_http: http = H0Connection(quic) else: http = H3Connection(quic) stream_id = quic.get_next_available_stream_id() http.send_headers( stream_id=stream_id, headers=[ (b":method", b"GET"), (b":scheme", parsed.scheme.encode("utf8")), (b":authority", parsed.netloc.encode("utf8")), (b":path", parsed.path.encode("utf8")), (b"user-agent", b"aioquic"), ], ) http.send_data(stream_id=stream_id, data=b"", end_stream=True) for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data,</s> ===========changed ref 2=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 <s>, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): - print(http_event) + if isinstance(http_event, ResponseReceived): - if isinstance(http_event, (DataReceived, ResponseReceived)): stream_ended = http_event.stream_ended + headers = b"" + for k, v in http_event.headers: + headers += k + b": " + v + b"\r\n" + if headers: + sys.stderr.buffer.write(headers + b"\r\n") + if isinstance(http_event, DataReceived): + stream_ended = http_event.stream_ended + sys.stdout.buffer.write(http_event.data) event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr)
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
4678fdd22323723bd6bc0e5016fdb7ed264722a7
[http3] ensure table size update gets sent
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if ( <12> stream_is_unidirectional(stream_id) <13> and stream_id not in self._stream_types <14> ): <15> try: <16> stream_type = buf.pull_uint_var() <17> except BufferReadError: <18> break <19> consumed = buf.tell() <20> <21> if stream_type == StreamType.CONTROL: <22> assert self._peer_control_stream_id is None <23> self._peer_control_stream_id = stream_id <24> elif stream_type == StreamType.QPACK_DECODER: <25> assert self._peer_decoder_stream_id is None <26> self._peer_decoder_stream_id = stream_id <27> elif stream_type == StreamType.QPACK_ENCODER: <28> assert self._peer_encoder_stream_id is None <29> self._peer_encoder_stream_id = stream_id <30> self._stream_types[stream_id] = stream_type <31> <32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: <33> # fetch next frame <34> try: <35> frame_type = buf.pull_uint_var() <36> frame_length = buf.pull_uint_var() <37> frame_data = buf.pull_bytes(frame_length) <38> except BufferReadError: <39> break <40> </s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: decoder, headers = self._decoder.feed_header( stream_id, frame_data ) self._quic.send_stream_data( self._local_decoder_stream_id, decoder ) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get( Setting.QPACK_BLOCKED_STREAMS, 0 ), ) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: self._decoder.feed_encoder(data) # remove processed data from buffer</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 2 <s>._peer_encoder_stream_id: self._decoder.feed_encoder(data) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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]
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
88362eee9e4573402d32f88554680c03f67dabaf
[http3] handle receiving FIN only on a stream
<6>:<add> <add> buf = Buffer(data=self._stream_buffers[stream_id]) <8>:<add> # some peers (e.g. f5) end the stream with no data <add> if stream_ended and buf.eof() and (stream_id % 4 == 0): <add> http_events.append( <add> DataReceived(data=b"", stream_id=stream_id, stream_ended=True) <add> ) <add> <del> buf = Buffer(data=self._stream_buffers[stream_id])
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> consumed = 0 <7> <8> buf = Buffer(data=self._stream_buffers[stream_id]) <9> while not buf.eof(): <10> # fetch stream type for unidirectional streams <11> if ( <12> stream_is_unidirectional(stream_id) <13> and stream_id not in self._stream_types <14> ): <15> try: <16> stream_type = buf.pull_uint_var() <17> except BufferReadError: <18> break <19> consumed = buf.tell() <20> <21> if stream_type == StreamType.CONTROL: <22> assert self._peer_control_stream_id is None <23> self._peer_control_stream_id = stream_id <24> elif stream_type == StreamType.QPACK_DECODER: <25> assert self._peer_decoder_stream_id is None <26> self._peer_decoder_stream_id = stream_id <27> elif stream_type == StreamType.QPACK_ENCODER: <28> assert self._peer_encoder_stream_id is None <29> self._peer_encoder_stream_id = stream_id <30> self._stream_types[stream_id] = stream_type <31> <32> if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: <33> # fetch next frame <34> try: <35> frame_type = buf.pull_uint_var() <36> frame_length = buf.pull_uint_var() <37> frame_data = buf.pull_bytes(frame_length) <38> except BufferReadError: <39> break <40> </s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: decoder, headers = self._decoder.feed_header( stream_id, frame_data ) self._quic.send_stream_data( self._local_decoder_stream_id, decoder ) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) encoder = self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get( Setting.QPACK_BLOCKED_STREAMS, 0 ), ) self._quic.send_stream_data( self._local_encoder_stream_id, encoder ) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id ==</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 2 <s> self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: self._decoder.feed_encoder(data) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_buffers: Dict[int, bytes] = {} self._stream_types: Dict[int, int] = {} self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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]
aioquic.packet_builder/QuicPacketBuilder.start_packet
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
# module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: <0> """ <1> Starts a new packet. <2> """ <3> buf = self.buffer <4> self._ack_eliciting = False <5> <6> # if there is too little space remaining, start a new datagram <7> # FIXME: the limit is arbitrary! <8> packet_start = buf.tell() <9> if self._buffer_capacity - packet_start < 128: <10> self._flush_current_datagram() <11> packet_start = 0 <12> <13> # initialize datagram if needed <14> if self._datagram_init: <15> if self.max_flight_bytes is not None: <16> remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes <17> if remaining_flight_bytes < self._buffer_capacity: <18> self._buffer_capacity = remaining_flight_bytes <19> if self.max_total_bytes is not None: <20> remaining_total_bytes = self.max_total_bytes - self._total_bytes <21> if remaining_total_bytes < self._buffer_capacity: <22> self._buffer_capacity = remaining_total_bytes <23> self._datagram_init = False <24> <25> # calculate header size <26> packet_long_header = is_long_header(packet_type) <27> if packet_long_header: <28> header_size = 11 + len(self._peer_cid) + len(self._host_cid) <29> if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: <30> token_length = len(self._peer_token) <31> header_size += size_uint_var(token_length) + token_length <32> else: <33> header_size = 3 + len(self._peer_cid) <34> <35> # check we have enough space <36> if packet_start + header_size >= self._buffer_capacity: <37> raise QuicPacketBuilderStop <38> <39> </s>
===========below chunk 0=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int at: aioquic.buffer size_uint_var(value: int) -> int at: aioquic.crypto CryptoPair() at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_MASK = 0xF0 is_long_header(first_byte: int) -> bool at: aioquic.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 )) QuicPacketBuilderStop(*args: object) at: aioquic.packet_builder.QuicPacketBuilder _flush_current_datagram() -> None at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.max_flight_bytes: Optional[int] = None self.max_total_bytes: Optional[int] = None self._host_cid = host_cid self._peer_cid = peer_cid self._peer_token = peer_token self._ack_eliciting = False self._datagram_init = True self._flight_bytes = 0 self._total_bytes = 0 self._header_size = 0 self._packet: Optional[QuicSentPacket] = None self._packet_crypto: Optional[CryptoPair] = None self._packet_long_header = False self._packet_number = packet_number self._packet_start = 0 ===========unchanged ref 1=========== self._packet_type = 0 self.buffer = Buffer(PACKET_MAX_SIZE) self._buffer_capacity = PACKET_MAX_SIZE at: aioquic.packet_builder.QuicPacketBuilder._flush_current_datagram self._datagram_init = True self._flight_bytes += datagram_bytes self._total_bytes += datagram_bytes at: aioquic.packet_builder.QuicPacketBuilder.end_packet self._packet_number += 1 self._packet = None at: aioquic.packet_builder.QuicPacketBuilder.start_frame self._ack_eliciting = True at: aioquic.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 ) at: aioquic.tls Epoch() ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 )
tests.test_recovery/QuicPacketRecoveryTest.test_on_packet_lost_crypto
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
<6>:<add> packet_type=PACKET_TYPE_INITIAL,
# module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def test_on_packet_lost_crypto(self): <0> packet = QuicSentPacket( <1> epoch=tls.Epoch.INITIAL, <2> in_flight=True, <3> is_ack_eliciting=True, <4> is_crypto_packet=True, <5> packet_number=0, <6> sent_bytes=1280, <7> sent_time=123.45, <8> ) <9> space = self.INITIAL_SPACE <10> <11> self.recovery.on_packet_sent(packet, space) <12> self.assertEqual(self.recovery.bytes_in_flight, 1280) <13> self.assertEqual(space.ack_eliciting_in_flight, 1) <14> self.assertEqual(len(space.sent_packets), 1) <15> <16> self.recovery.on_packet_lost(packet, space) <17> self.assertEqual(self.recovery.bytes_in_flight, 0) <18> self.assertEqual(space.ack_eliciting_in_flight, 0) <19> self.assertEqual(len(space.sent_packets), 0) <20>
===========unchanged ref 0=========== at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 at: aioquic.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 )) at: aioquic.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 ) at: aioquic.recovery.QuicPacketRecovery on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None on_packet_sent(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.recovery.QuicPacketRecovery.__init__ self.bytes_in_flight = 0 at: aioquic.recovery.QuicPacketRecovery.on_packet_acked self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_expired self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_lost self.bytes_in_flight -= packet.sent_bytes at: aioquic.recovery.QuicPacketRecovery.on_packet_sent self.bytes_in_flight += packet.sent_bytes ===========unchanged ref 1=========== at: aioquic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} at: aioquic.tls Epoch() at: tests.test_recovery.QuicPacketRecoveryTest.setUp self.INITIAL_SPACE = QuicPacketSpace() self.recovery = QuicPacketRecovery( is_client_without_1rtt=False, send_probe=send_probe ) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 ) ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHA</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, + packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_padding
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
<33>:<add> packet_type=PACKET_TYPE_INITIAL,
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> pad_first_datagram=True, <4> peer_cid=bytes(8), <5> peer_token=b"", <6> spin_bit=False, <7> version=QuicProtocolVersion.DRAFT_20, <8> ) <9> crypto = CryptoPair() <10> crypto.setup_initial(bytes(8), is_client=True) <11> <12> # INITIAL, fully padded <13> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <14> self.assertEqual(builder.remaining_space, 1236) <15> builder.start_frame(QuicFrameType.CRYPTO) <16> builder.buffer.push_bytes(bytes(100)) <17> self.assertTrue(builder.end_packet()) <18> self.assertEqual(builder.buffer.tell(), 1280) <19> <20> # check datagrams <21> datagrams, packets = builder.flush() <22> self.assertEqual(len(datagrams), 1) <23> self.assertEqual(len(datagrams[0]), 1280) <24> self.assertEqual( <25> packets, <26> [ <27> QuicSentPacket( <28> epoch=Epoch.INITIAL, <29> in_flight=True, <30> is_ack_eliciting=True, <31> is_crypto_packet=True, <32> packet_number=0, <33> sent_bytes=1280, <34> ) <35> ], <36> ) <37>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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 )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) ===========unchanged ref 1=========== at: aioquic.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 ) at: aioquic.tls Epoch() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 ) ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHA</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, + packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========changed ref 3=========== # module: tests.test_recovery class QuicPacketRecoveryTest(TestCase): def test_on_packet_lost_crypto(self): packet = QuicSentPacket( epoch=tls.Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, + packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, sent_time=123.45, ) space = self.INITIAL_SPACE self.recovery.on_packet_sent(packet, space) self.assertEqual(self.recovery.bytes_in_flight, 1280) self.assertEqual(space.ack_eliciting_in_flight, 1) self.assertEqual(len(space.sent_packets), 1) self.recovery.on_packet_lost(packet, space) self.assertEqual(self.recovery.bytes_in_flight, 0) self.assertEqual(space.ack_eliciting_in_flight, 0) self.assertEqual(len(space.sent_packets), 0)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_short_header
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(bytes(8), is_client=True) <10> <11> # INITIAL, fully padded <12> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <13> self.assertEqual(builder.remaining_space, 1236) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(builder.remaining_space)) <16> self.assertTrue(builder.end_packet()) <17> self.assertEqual(builder.buffer.tell(), 1280) <18> <19> # ONE_RTT, fully padded <20> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <21> self.assertEqual(builder.remaining_space, 1253) <22> builder.start_frame(QuicFrameType.STREAM_BASE) <23> builder.buffer.push_bytes(bytes(builder.remaining_space)) <24> self.assertTrue(builder.end_packet()) <25> self.assertEqual(builder.buffer.tell(), 0) <26> <27> # check datagrams <28> datagrams, packets = builder.flush() <29> self.assertEqual(len(datagrams), 2) <30> self.assertEqual(len(datagrams[0]), 1280) <31> self.assertEqual(len(datagrams[1]), 1280) <32> self.assertEqual( <33> packets, <34> [ <35> QuicSentPacket( <36> epoch=Epoch.INITIAL, <37> in_flight=True, <38> is_ack_eliciting=True,</s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_short_header(self): # offset: 1 packet_number=0, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, sent_bytes=1280, ), ], ) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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 )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.tls Epoch() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 ) ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHA</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, + packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_long_header_then_long_header
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(bytes(8), is_client=True) <10> <11> # INITIAL <12> builder.start_packet(PACKET_TYPE_INITIAL, crypto) <13> self.assertEqual(builder.remaining_space, 1236) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(199)) <16> self.assertEqual(builder.buffer.tell(), 228) <17> self.assertTrue(builder.end_packet()) <18> self.assertEqual(builder.buffer.tell(), 244) <19> <20> # HANDSHAKE <21> builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) <22> self.assertEqual(builder.buffer.tell(), 271) <23> self.assertEqual(builder.remaining_space, 993) <24> builder.start_frame(QuicFrameType.CRYPTO) <25> builder.buffer.push_bytes(bytes(299)) <26> self.assertEqual(builder.buffer.tell(), 571) <27> self.assertTrue(builder.end_packet()) <28> self.assertEqual(builder.buffer.tell(), 587) <29> <30> # ONE_RTT <31> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <32> self.assertEqual(builder.remaining_space, 666) <33> builder.start_frame(QuicFrameType.CRYPTO) <34> builder.buffer.push_bytes(bytes(299)) <35> self.assertTrue(builder.end_packet()) <36> </s>
===========below chunk 0=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_then_long_header(self): # offset: 1 # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 914) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, sent_bytes=244, ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, sent_bytes=343, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, sent_bytes=327, ), ], ) ===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_INITIAL = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x00 PACKET_TYPE_HANDSHAKE = PACKET_LONG_HEADER | PACKET_FIXED_BIT | 0x20 PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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 )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool ===========unchanged ref 1=========== at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) at: aioquic.tls Epoch() at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 ) ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHA</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, + packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size)
tests.test_packet_builder/QuicPacketBuilderTest.test_short_header_padding
Modified
aiortc~aioquic
6372da7c3d7c88a9293d6069f4dd94b604346b95
[packet builder] keep track of the packet type
<35>:<add> packet_type=PACKET_TYPE_ONE_RTT,
# module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_short_header_padding(self): <0> builder = QuicPacketBuilder( <1> host_cid=bytes(8), <2> packet_number=0, <3> peer_cid=bytes(8), <4> peer_token=b"", <5> spin_bit=False, <6> version=QuicProtocolVersion.DRAFT_20, <7> ) <8> crypto = CryptoPair() <9> crypto.setup_initial(bytes(8), is_client=True) <10> <11> # ONE_RTT, fully padded <12> builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) <13> self.assertEqual(builder.remaining_space, 1253) <14> builder.start_frame(QuicFrameType.CRYPTO) <15> builder.buffer.push_bytes(bytes(builder.remaining_space)) <16> self.assertTrue(builder.end_packet()) <17> <18> # check builder <19> self.assertEqual(builder.buffer.tell(), 0) <20> self.assertEqual(builder.packet_number, 1) <21> <22> # check datagrams <23> datagrams, packets = builder.flush() <24> self.assertEqual(len(datagrams), 1) <25> self.assertEqual(len(datagrams[0]), 1280) <26> self.assertEqual( <27> packets, <28> [ <29> QuicSentPacket( <30> epoch=Epoch.ONE_RTT, <31> in_flight=True, <32> is_ack_eliciting=True, <33> is_crypto_packet=True, <34> packet_number=0, <35> sent_bytes=1280, <36> ) <37> ], <38> ) <39>
===========unchanged ref 0=========== at: aioquic._buffer.Buffer tell() -> int push_bytes(value: bytes) -> None at: aioquic.crypto CryptoPair() at: aioquic.crypto.CryptoPair setup_initial(cid: bytes, is_client: bool) -> None at: aioquic.packet PACKET_TYPE_ONE_RTT = PACKET_FIXED_BIT QuicProtocolVersion(x: Union[str, bytes, bytearray], base: int) QuicProtocolVersion(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) QuicFrameType(x: Union[str, bytes, bytearray], base: int) at: aioquic.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 )) QuicPacketBuilder(*, host_cid: bytes, peer_cid: bytes, version: int, pad_first_datagram: bool=False, packet_number: int=0, peer_token: bytes=b"", spin_bit: bool=False) at: aioquic.packet_builder.QuicPacketBuilder flush() -> Tuple[List[bytes], List[QuicSentPacket]] start_frame(frame_type: int, handler: Optional[QuicDeliveryHandler]=None, args: Sequence[Any]=[]) -> None start_packet(packet_type: int, crypto: CryptoPair) -> None end_packet() -> bool at: aioquic.packet_builder.QuicPacketBuilder.__init__ self.buffer = Buffer(PACKET_MAX_SIZE) ===========unchanged ref 1=========== at: aioquic.tls Epoch() at: tests.test_packet_builder.QuicPacketBuilderTest.test_short_header_empty builder = QuicPacketBuilder( host_cid=bytes(8), packet_number=0, peer_cid=bytes(8), peer_token=b"", spin_bit=False, version=QuicProtocolVersion.DRAFT_20, ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.packet_builder @dataclass class 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 ) ===========changed ref 1=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: """ Starts a new packet. """ buf = self.buffer self._ack_eliciting = False # if there is too little space remaining, start a new datagram # FIXME: the limit is arbitrary! packet_start = buf.tell() if self._buffer_capacity - packet_start < 128: self._flush_current_datagram() packet_start = 0 # initialize datagram if needed if self._datagram_init: if self.max_flight_bytes is not None: remaining_flight_bytes = self.max_flight_bytes - self._flight_bytes if remaining_flight_bytes < self._buffer_capacity: self._buffer_capacity = remaining_flight_bytes if self.max_total_bytes is not None: remaining_total_bytes = self.max_total_bytes - self._total_bytes if remaining_total_bytes < self._buffer_capacity: self._buffer_capacity = remaining_total_bytes self._datagram_init = False # calculate header size packet_long_header = is_long_header(packet_type) if packet_long_header: header_size = 11 + len(self._peer_cid) + len(self._host_cid) if (packet_type & PACKET_TYPE_MASK) == PACKET_TYPE_INITIAL: token_length = len(self._peer_token) header_size += size_uint_var(token_length) + token_length else: header_size = 3 + len(self._peer_cid) # check we have enough space if packet_start + header_size >= self._buffer_capacity: raise QuicPacketBuilderStop # determine ack epoch if packet_type == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHA</s> ===========changed ref 2=========== # module: aioquic.packet_builder class QuicPacketBuilder: def start_packet(self, packet_type: int, crypto: CryptoPair) -> None: # offset: 1 <s> == PACKET_TYPE_INITIAL: epoch = Epoch.INITIAL elif packet_type == PACKET_TYPE_HANDSHAKE: epoch = Epoch.HANDSHAKE else: epoch = Epoch.ONE_RTT self._header_size = header_size self._packet = QuicSentPacket( epoch=epoch, in_flight=False, is_ack_eliciting=False, is_crypto_packet=False, packet_number=self._packet_number, + packet_type=packet_type, ) self._packet_crypto = crypto self._packet_long_header = packet_long_header self._packet_start = packet_start self._packet_type = packet_type buf.seek(self._packet_start + self._header_size) ===========changed ref 3=========== # module: tests.test_packet_builder class QuicPacketBuilderTest(TestCase): def test_long_header_padding(self): builder = QuicPacketBuilder( host_cid=bytes(8), packet_number=0, pad_first_datagram=True, peer_cid=bytes(8), peer_token=b"", spin_bit=False, version=QuicProtocolVersion.DRAFT_20, ) crypto = CryptoPair() crypto.setup_initial(bytes(8), is_client=True) # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, + packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], )
aioquic.h3.connection/H3Connection.__init__
Modified
aiortc~aioquic
90c4cb26b181cfe614e91e0218a5c8f1b80c62bd
[http3] add support for blocked streams
<7>:<add> self._stream_blocked: Set[int] = set() <8>:<add> self._stream_ended: Set[int] = set()
# module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): <0> self._max_table_capacity = 0x100 <1> self._blocked_streams = 0x10 <2> <3> self._is_client = quic.configuration.is_client <4> self._quic = quic <5> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) <6> self._encoder = Encoder() <7> self._stream_buffers: Dict[int, bytes] = {} <8> self._stream_types: Dict[int, int] = {} <9> <10> self._local_control_stream_id: Optional[int] = None <11> self._local_decoder_stream_id: Optional[int] = None <12> self._local_encoder_stream_id: Optional[int] = None <13> <14> self._peer_control_stream_id: Optional[int] = None <15> self._peer_decoder_stream_id: Optional[int] = None <16> self._peer_encoder_stream_id: Optional[int] = None <17> <18> self._init_connection() <19>
===========unchanged ref 0=========== at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.h3.connection.H3Connection._init_connection self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.connection.H3Connection._receive_stream_data self._peer_control_stream_id = stream_id self._peer_decoder_stream_id = stream_id self._peer_encoder_stream_id = stream_id at: typing Set = _alias(set, 1, inst=False, name='Set') Dict = _alias(dict, 2, inst=False, name='Dict')
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
90c4cb26b181cfe614e91e0218a5c8f1b80c62bd
[http3] add support for blocked streams
<6>:<add> if stream_ended: <add> self._stream_ended.add(stream_id) <add> if stream_id in self._stream_blocked: <add> return http_events <9>:<add> unblocked_streams: Set[int] = set()
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> <7> buf = Buffer(data=self._stream_buffers[stream_id]) <8> consumed = 0 <9> <10> # some peers (e.g. f5) end the stream with no data <11> if stream_ended and buf.eof() and (stream_id % 4 == 0): <12> http_events.append( <13> DataReceived(data=b"", stream_id=stream_id, stream_ended=True) <14> ) <15> <16> while not buf.eof(): <17> # fetch stream type for unidirectional streams <18> if ( <19> stream_is_unidirectional(stream_id) <20> and stream_id not in self._stream_types <21> ): <22> try: <23> stream_type = buf.pull_uint_var() <24> except BufferReadError: <25> break <26> consumed = buf.tell() <27> <28> if stream_type == StreamType.CONTROL: <29> assert self._peer_control_stream_id is None <30> self._peer_control_stream_id = stream_id <31> elif stream_type == StreamType.QPACK_DECODER: <32> assert self._peer_decoder_stream_id is None <33> self._peer_decoder_stream_id = stream_id <34> elif stream_type == StreamType.QPACK_ENCODER: <35> assert self._peer_encoder_stream_id is None <36> self._peer_encoder_stream_id = stream_id <37> self._stream_types[stream_id] = stream_type <38> <39> if (stream_id % 4 == 0) or stream_id</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 # fetch next frame try: frame_type = buf.pull_uint_var() frame_length = buf.pull_uint_var() frame_data = buf.pull_bytes(frame_length) except BufferReadError: break consumed = buf.tell() if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: decoder, headers = self._decoder.feed_header( stream_id, frame_data ) self._quic.send_stream_data( self._local_decoder_stream_id, decoder ) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) encoder = self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get( Setting.QPACK_BLOCKED_STREAMS, 0 ), ) self._quic.send_stream_data( self._local_encoder_stream_id, encoder ) else: </s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 2 <s>ic.send_stream_data( self._local_encoder_stream_id, encoder ) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: self._decoder.feed_encoder(data) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] return http_events ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream_blocked: Set[int] = set() self._stream_buffers: Dict[int, bytes] = {} self._stream_ended: Set[int] = set() self._stream_types: Dict[int, int] = {} self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: typing List = _alias(list, 1, inst=False, name='List') Set = _alias(set, 1, inst=False, name='Set') 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.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() + self._stream_blocked: Set[int] = set() self._stream_buffers: Dict[int, bytes] = {} + self._stream_ended: Set[int] = set() self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None self._init_connection()
tests.test_h3/H3ConnectionTest.test_fragmented_frame
Modified
aiortc~aioquic
90c4cb26b181cfe614e91e0218a5c8f1b80c62bd
[http3] add support for blocked streams
<0>:<del> class FakeQuicConnection: <1>:<del> def __init__(self, configuration): <2>:<del> self.configuration = configuration <3>:<del> self.stream_queue = [] <4>:<del> self._next_stream_bidi = 0 if configuration.is_client else 2 <5>:<del> self._next_stream_uni = 1 if configuration.is_client else 3 <6>:<del> <7>:<del> def get_next_available_stream_id(self, is_unidirectional=False): <8>:<del> if is_unidirectional: <9>:<del> stream_id = self._next_stream_uni <10>:<del> self._next_stream_uni += 4 <11>:<del> else: <12>:<del> stream_id = self._next_stream_bidi <13>:<del> self._next_stream_bidi += 4 <14>:<del> return stream_id <15>:<del> <16>:<del> def send_stream_data(self, stream_id, data, end_stream=False): <17>:<del> # chop up data into individual bytes <18>:<del> for c in data: <19>:<del> self.stream_queue.append( <20>:<del> StreamDataReceived( <21>:<del> data=bytes([c]), end_stream=False, stream_id=stream_id <22>:<del> ) <23>:<del> ) <24>:<del> if end_stream: <25>:<del> self.stream_queue.append( <26>:<del> StreamDataReceived( <27>:<del> data=b"", end_stream=end_stream, stream_id=stream_id <28>:<del> ) <29>:<del> ) <30>:<del>
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_fragmented_frame(self): <0> class FakeQuicConnection: <1> def __init__(self, configuration): <2> self.configuration = configuration <3> self.stream_queue = [] <4> self._next_stream_bidi = 0 if configuration.is_client else 2 <5> self._next_stream_uni = 1 if configuration.is_client else 3 <6> <7> def get_next_available_stream_id(self, is_unidirectional=False): <8> if is_unidirectional: <9> stream_id = self._next_stream_uni <10> self._next_stream_uni += 4 <11> else: <12> stream_id = self._next_stream_bidi <13> self._next_stream_bidi += 4 <14> return stream_id <15> <16> def send_stream_data(self, stream_id, data, end_stream=False): <17> # chop up data into individual bytes <18> for c in data: <19> self.stream_queue.append( <20> StreamDataReceived( <21> data=bytes([c]), end_stream=False, stream_id=stream_id <22> ) <23> ) <24> if end_stream: <25> self.stream_queue.append( <26> StreamDataReceived( <27> data=b"", end_stream=end_stream, stream_id=stream_id <28> ) <29> ) <30> <31> quic_client = FakeQuicConnection( <32> configuration=QuicConfiguration(is_client=True) <33> ) <34> quic_server = FakeQuicConnection( <35> configuration=QuicConfiguration(is_client=False) <36> ) <37> <38> h3_client = H3Connection(quic_client) <39> h3_server = H3Connection(quic_server) <40> <41> # send headers <42> stream_id = quic_client.get_next_available_stream_id() <43> h3_client.send_headers( </s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_fragmented_frame(self): # offset: 1 headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), (b"x-foo", b"client"), ], ) http_events = [] for event in quic_client.stream_queue: http_events.extend(h3_server.handle_event(event)) quic_client.stream_queue.clear() self.assertEqual( http_events, [ RequestReceived( headers=[ (b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"localhost"), (b":path", b"/"), (b"x-foo", b"client"), ], stream_id=0, stream_ended=False, ) ], ) # send body h3_client.send_data(stream_id=stream_id, data=b"hello", end_stream=True) http_events = [] for event in quic_client.stream_queue: http_events.extend(h3_server.handle_event(event)) quic_client.stream_queue.clear() self.assertEqual( http_events, [ DataReceived(data=b"hello", stream_id=0, stream_ended=False), DataReceived(data=b"", stream_id=0, stream_ended=True), ], ) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool ===========unchanged ref 1=========== at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 FakeQuicConnection(configuration) at: tests.test_h3.FakeQuicConnection get_next_available_stream_id(is_unidirectional=False) at: tests.test_h3.FakeQuicConnection.__init__ self.stream_queue = [] at: tests.test_h3.H3ConnectionTest _make_request(h3_client, h3_server) at: tests.test_h3.H3ConnectionTest._make_request stream_id = quic_client.get_next_available_stream_id() events = h3_transfer(quic_server, h3_client) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None assertTrue(expr: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_h3 + class FakeQuicConnection: + def get_next_available_stream_id(self, is_unidirectional=False): + if is_unidirectional: + stream_id = self._next_stream_uni + self._next_stream_uni += 4 + else: + stream_id = self._next_stream_bidi + self._next_stream_bidi += 4 + return stream_id + ===========changed ref 1=========== # module: tests.test_h3 + class FakeQuicConnection: + def __init__(self, configuration): + self.configuration = configuration + self.stream_queue = [] + self._next_stream_bidi = 0 if configuration.is_client else 2 + self._next_stream_uni = 1 if configuration.is_client else 3 + ===========changed ref 2=========== # module: tests.test_h3 + class FakeQuicConnection: + def send_stream_data(self, stream_id, data, end_stream=False): + # chop up data into individual bytes + for c in data: + self.stream_queue.append( + StreamDataReceived( + data=bytes([c]), end_stream=False, stream_id=stream_id + ) + ) + if end_stream: + self.stream_queue.append( + StreamDataReceived(data=b"", end_stream=end_stream, stream_id=stream_id) + ) + ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() + self._stream_blocked: Set[int] = set() self._stream_buffers: Dict[int, bytes] = {} + self._stream_ended: Set[int] = set() self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None self._init_connection()
examples.http3-client/run
Modified
aiortc~aioquic
90c4cb26b181cfe614e91e0218a5c8f1b80c62bd
[http3] add support for blocked streams
# module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <18> is_client=True, <19> server_name=server_name, <20> **kwargs <21> ), <22> session_ticket_handler=save_session_ticket, <23> ) <24> quic.connect(server_addr, now=time.time()) <25> <26> # send request <27> http: HttpConnection <28> if legacy_http: <29> http = H0Connection(quic) <30> else: <31> http = H3Connection(quic) <32> stream_id = quic.get_next_available_stream_id() <33> http.send_headers( <34> stream_id=stream_id, <35> headers=[ <36> (b":method", b"GET"), <37> (b":scheme", parsed.scheme.encode("utf8")), <38> (b":authority", parsed.netloc.encode("utf8")), <39> (b":path", parsed.path.encode("utf8")), <40> (b"user-agent", b"aioquic"), <41> ], <42> ) <43> http.send_data(stream_id=stream_id, data</s>
===========below chunk 0=========== # module: examples.http3-client def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): if isinstance(http_event, ResponseReceived): stream_ended = http_event.stream_ended headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") if isinstance(http_event, DataReceived): stream_ended = http_event.stream_ended sys.stdout.buffer.write(http_event.data) event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: aioquic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[tls.SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[tls.SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None ===========unchanged ref 1=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] save_session_ticket(ticket) at: socket AF_INET: AddressFamily SOCK_DGRAM: SocketKind socket(family: int=..., type: int=..., proto: int=..., fileno: Optional[int]=...) gethostbyname(hostname: str) -> str at: socket.socket family: int type: int proto: int recvfrom(bufsize: int, flags: int=...) -> Tuple[bytes, _RetAddress] sendto(data: bytes, address: _Address) -> int sendto(data: bytes, flags: int, address: _Address) -> int at: sys stdout: TextIO stderr: TextIO at: time time() -> float at: typing.BinaryIO __slots__ = () ===========unchanged ref 2=========== write(s: AnyStr) -> int at: typing.IO __slots__ = () flush() -> None at: typing.TextIO __slots__ = () at: urllib.parse urlparse(url: str, scheme: Optional[str]=..., allow_fragments: bool=...) -> ParseResult urlparse(url: Optional[bytes], scheme: Optional[bytes]=..., allow_fragments: bool=...) -> ParseResultBytes ===========changed ref 0=========== # module: tests.test_h3 + class FakeQuicConnection: + def __init__(self, configuration): + self.configuration = configuration + self.stream_queue = [] + self._next_stream_bidi = 0 if configuration.is_client else 2 + self._next_stream_uni = 1 if configuration.is_client else 3 + ===========changed ref 1=========== # module: tests.test_h3 + class FakeQuicConnection: + def get_next_available_stream_id(self, is_unidirectional=False): + if is_unidirectional: + stream_id = self._next_stream_uni + self._next_stream_uni += 4 + else: + stream_id = self._next_stream_bidi + self._next_stream_bidi += 4 + return stream_id + ===========changed ref 2=========== # module: tests.test_h3 + class FakeQuicConnection: + def send_stream_data(self, stream_id, data, end_stream=False): + # chop up data into individual bytes + for c in data: + self.stream_queue.append( + StreamDataReceived( + data=bytes([c]), end_stream=False, stream_id=stream_id + ) + ) + if end_stream: + self.stream_queue.append( + StreamDataReceived(data=b"", end_stream=end_stream, stream_id=stream_id) + ) +
aioquic.h0.connection/H0Connection.handle_event
Modified
aiortc~aioquic
d01c68649c57e02e4343a86bc401d5beb0405de2
[quic] move quic code to aioquic.quic
<3>:<add> isinstance(event, aioquic.quic.events.StreamDataReceived) <del> isinstance(event, aioquic.events.StreamDataReceived)
# module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if ( <3> isinstance(event, aioquic.events.StreamDataReceived) <4> and (event.stream_id % 4) == 0 <5> ): <6> data = event.data <7> if not self._headers_received.get(event.stream_id, False): <8> if self._is_client: <9> http_events.append( <10> ResponseReceived( <11> headers=[], stream_ended=False, stream_id=event.stream_id <12> ) <13> ) <14> else: <15> method, path = data.rstrip().split(b" ", 1) <16> http_events.append( <17> RequestReceived( <18> headers=[(b":method", method), (b":path", path)], <19> stream_ended=False, <20> stream_id=event.stream_id, <21> ) <22> ) <23> data = b"" <24> self._headers_received[event.stream_id] = True <25> <26> http_events.append( <27> DataReceived( <28> data=data, stream_ended=event.end_stream, stream_id=event.stream_id <29> ) <30> ) <31> <32> return http_events <33>
===========unchanged ref 0=========== at: aioquic.events Event() StreamDataReceived(data: bytes, end_stream: bool, stream_id: int) at: aioquic.h0.connection.H0Connection.__init__ self._headers_received: Dict[int, bool] = {} self._is_client = quic.configuration.is_client at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool 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] ===========changed ref 0=========== + # module: aioquic.quic.retry + + ===========changed ref 1=========== + # module: aioquic.quic + + ===========changed ref 2=========== + # module: aioquic.quic.connection + + ===========changed ref 3=========== + # module: aioquic.quic.configuration + + ===========changed ref 4=========== + # module: aioquic.quic.stream + + ===========changed ref 5=========== + # module: aioquic.quic.packet_builder + + ===========changed ref 6=========== + # module: aioquic.quic.crypto + + ===========changed ref 7=========== + # module: aioquic.quic.packet + + ===========changed ref 8=========== + # module: aioquic.quic.rangeset + + ===========changed ref 9=========== + # module: aioquic.quic.packet_builder + class QuicPacketBuilderStop(Exception): + pass + ===========changed ref 10=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __bool__(self) -> bool: + raise NotImplementedError + ===========changed ref 11=========== + # module: aioquic.quic.connection + class QuicConnection: + @property + def configuration(self) -> QuicConfiguration: + return self._configuration + ===========changed ref 12=========== + # module: aioquic.quic.stream + class QuicStream: + @property + def stream_id(self) -> Optional[int]: + return self.__stream_id + ===========changed ref 13=========== + # module: aioquic.quic.connection + class QuicConnection: + def _send_probe(self) -> None: + self._probe_pending = True + ===========changed ref 14=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __len__(self) -> int: + return len(self.__ranges) + ===========changed ref 15=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __getitem__(self, key: Any) -> range: + return self.__ranges[key] + ===========changed ref 16=========== + # module: aioquic.quic.crypto + class CryptoContext: + def is_valid(self) -> bool: + return self.aead is not None + ===========changed ref 17=========== + # module: aioquic.quic.crypto + class CryptoPair: + def update_key(self) -> None: + self._update_key_requested = True + ===========changed ref 18=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def shift(self) -> range: + return self.__ranges.pop(0) + ===========changed ref 19=========== + # module: aioquic.quic.connection + class QuicConnection: + """ + A QUIC connection. + """ + ===========changed ref 20=========== + # module: aioquic.quic.connection + def dump_cid(cid: bytes) -> str: + return binascii.hexlify(cid).decode("ascii") + ===========changed ref 21=========== + # module: aioquic.quic.recovery + # TODO : collapse congestion window if persistent congestion + ===========changed ref 22=========== + # module: aioquic.quic.recovery + class QuicPacketRecovery: + def on_packet_expired(self, packet: QuicSentPacket) -> None: + self.bytes_in_flight -= packet.sent_bytes + ===========changed ref 23=========== + # module: aioquic.quic.packet_builder + class QuicPacketBuilder: + """ + Helper for building QUIC packets. + """ + ===========changed ref 24=========== + # module: aioquic.quic.recovery + class QuicPacketRecovery: + """ + Packet loss and congestion controller. + """ + ===========changed ref 25=========== + # module: aioquic.quic.packet + def is_long_header(first_byte: int) -> bool: + return bool(first_byte & PACKET_LONG_HEADER) + ===========changed ref 26=========== + # module: aioquic.quic.packet + def get_spin_bit(first_byte: int) -> bool: + return bool(first_byte & PACKET_SPIN_BIT) + ===========changed ref 27=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __repr__(self) -> str: + return "RangeSet({})".format(repr(self.__ranges)) + ===========changed ref 28=========== + # module: aioquic.quic.packet_builder + class QuicDeliveryState(Enum): + ACKED = 0 + LOST = 1 + EXPIRED = 2 + ===========changed ref 29=========== + # module: aioquic.quic.crypto + class CryptoPair: + def teardown(self) -> None: + self.recv.teardown() + self.send.teardown() + ===========changed ref 30=========== + # module: aioquic.quic.connection + class QuicConnection: + def _handle_padding_frame( + self, context: QuicReceiveContext, frame_type: int, buf: Buffer + ) -> None: + """ + Handle a PADDING or PING frame. + """ + pass + ===========changed ref 31=========== + # module: aioquic.quic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 32=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def bounds(self) -> range: + return range(self.__ranges[0].start, self.__ranges[-1].stop) + ===========changed ref 33=========== + # module: aioquic.quic.packet + @dataclass + class QuicStreamFrame: + data: bytes = b"" + fin: bool = False + offset: int = 0 + ===========changed ref 34=========== + # module: aioquic.quic.connection + class QuicConnectionAdapter(logging.LoggerAdapter): + def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]: + return "[%s] %s" % (self.extra["host_cid"], msg), kwargs + ===========changed ref 35=========== + # module: aioquic.quic.packet + def pull_new_token_frame(buf: Buffer) -> bytes: + length = buf.pull_uint_var() + return buf.pull_bytes(length) + ===========changed ref 36=========== + # module: aioquic.quic.packet + def push_new_token_frame(buf: Buffer, token: bytes) -> None: + buf.push_uint_var(len(token)) + buf.push_bytes(token) + ===========changed ref 37=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __contains__(self, val: Any) -> bool: + for r in self.__ranges: + if val in r: + return True + return False +
aioquic.h3.connection/H3Connection.handle_event
Modified
aiortc~aioquic
d01c68649c57e02e4343a86bc401d5beb0405de2
[quic] move quic code to aioquic.quic
<5>:<add> if isinstance(event, aioquic.quic.events.StreamDataReceived): <del> if isinstance(event, aioquic.events.StreamDataReceived):
# module: aioquic.h3.connection class H3Connection: + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event) -> List[Event]: <0> """ <1> Handle a QUIC event and return a list of HTTP events. <2> """ <3> http_events: List[Event] = [] <4> <5> if isinstance(event, aioquic.events.StreamDataReceived): <6> http_events.extend( <7> self._receive_stream_data(event.stream_id, event.data, event.end_stream) <8> ) <9> <10> return http_events <11>
===========unchanged ref 0=========== at: aioquic.h3.connection.H3Connection _receive_stream_data(stream_id: int, data: bytes, stream_ended: bool) -> List[Event] at: aioquic.h3.events Event() at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== + # module: aioquic.quic.events + + ===========changed ref 1=========== + # module: aioquic.quic.retry + + ===========changed ref 2=========== + # module: aioquic.quic + + ===========changed ref 3=========== + # module: aioquic.quic.connection + + ===========changed ref 4=========== + # module: aioquic.quic.configuration + + ===========changed ref 5=========== + # module: aioquic.quic.stream + + ===========changed ref 6=========== + # module: aioquic.quic.packet_builder + + ===========changed ref 7=========== + # module: aioquic.quic.crypto + + ===========changed ref 8=========== + # module: aioquic.quic.packet + + ===========changed ref 9=========== + # module: aioquic.quic.rangeset + + ===========changed ref 10=========== + # module: aioquic.quic.packet_builder + class QuicPacketBuilderStop(Exception): + pass + ===========changed ref 11=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __bool__(self) -> bool: + raise NotImplementedError + ===========changed ref 12=========== + # module: aioquic.quic.connection + class QuicConnection: + @property + def configuration(self) -> QuicConfiguration: + return self._configuration + ===========changed ref 13=========== + # module: aioquic.quic.events + @dataclass + class ConnectionIdRetired(Event): + connection_id: bytes + ===========changed ref 14=========== + # module: aioquic.quic.events + @dataclass + class ConnectionIdIssued(Event): + connection_id: bytes + ===========changed ref 15=========== + # module: aioquic.quic.stream + class QuicStream: + @property + def stream_id(self) -> Optional[int]: + return self.__stream_id + ===========changed ref 16=========== + # module: aioquic.quic.connection + class QuicConnection: + def _send_probe(self) -> None: + self._probe_pending = True + ===========changed ref 17=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __len__(self) -> int: + return len(self.__ranges) + ===========changed ref 18=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __getitem__(self, key: Any) -> range: + return self.__ranges[key] + ===========changed ref 19=========== + # module: aioquic.quic.crypto + class CryptoContext: + def is_valid(self) -> bool: + return self.aead is not None + ===========changed ref 20=========== + # module: aioquic.quic.crypto + class CryptoPair: + def update_key(self) -> None: + self._update_key_requested = True + ===========changed ref 21=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def shift(self) -> range: + return self.__ranges.pop(0) + ===========changed ref 22=========== + # module: aioquic.quic.connection + class QuicConnection: + """ + A QUIC connection. + """ + ===========changed ref 23=========== + # module: aioquic.quic.connection + def dump_cid(cid: bytes) -> str: + return binascii.hexlify(cid).decode("ascii") + ===========changed ref 24=========== + # module: aioquic.quic.recovery + # TODO : collapse congestion window if persistent congestion + ===========changed ref 25=========== + # module: aioquic.quic.recovery + class QuicPacketRecovery: + def on_packet_expired(self, packet: QuicSentPacket) -> None: + self.bytes_in_flight -= packet.sent_bytes + ===========changed ref 26=========== + # module: aioquic.quic.packet_builder + class QuicPacketBuilder: + """ + Helper for building QUIC packets. + """ + ===========changed ref 27=========== + # module: aioquic.quic.recovery + class QuicPacketRecovery: + """ + Packet loss and congestion controller. + """ + ===========changed ref 28=========== + # module: aioquic.quic.packet + def is_long_header(first_byte: int) -> bool: + return bool(first_byte & PACKET_LONG_HEADER) + ===========changed ref 29=========== + # module: aioquic.quic.packet + def get_spin_bit(first_byte: int) -> bool: + return bool(first_byte & PACKET_SPIN_BIT) + ===========changed ref 30=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __repr__(self) -> str: + return "RangeSet({})".format(repr(self.__ranges)) + ===========changed ref 31=========== + # module: aioquic.quic.packet_builder + class QuicDeliveryState(Enum): + ACKED = 0 + LOST = 1 + EXPIRED = 2 + ===========changed ref 32=========== + # module: aioquic.quic.crypto + class CryptoPair: + def teardown(self) -> None: + self.recv.teardown() + self.send.teardown() + ===========changed ref 33=========== + # module: aioquic.quic.events + class Event: + """ + Base class for QUIC events. + """ + + pass + ===========changed ref 34=========== + # module: aioquic.quic.connection + class QuicConnection: + def _handle_padding_frame( + self, context: QuicReceiveContext, frame_type: int, buf: Buffer + ) -> None: + """ + Handle a PADDING or PING frame. + """ + pass + ===========changed ref 35=========== + # module: aioquic.quic.connection + def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]: + return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut) + ===========changed ref 36=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def bounds(self) -> range: + return range(self.__ranges[0].start, self.__ranges[-1].stop) + ===========changed ref 37=========== + # module: aioquic.quic.packet + @dataclass + class QuicStreamFrame: + data: bytes = b"" + fin: bool = False + offset: int = 0 + ===========changed ref 38=========== + # module: aioquic.quic.connection + class QuicConnectionAdapter(logging.LoggerAdapter): + def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]: + return "[%s] %s" % (self.extra["host_cid"], msg), kwargs + ===========changed ref 39=========== + # module: aioquic.quic.packet + def pull_new_token_frame(buf: Buffer) -> bytes: + length = buf.pull_uint_var() + return buf.pull_bytes(length) + ===========changed ref 40=========== + # module: aioquic.quic.packet + def push_new_token_frame(buf: Buffer, token: bytes) -> None: + buf.push_uint_var(len(token)) + buf.push_bytes(token) + ===========changed ref 41=========== + # module: aioquic.quic.rangeset + class RangeSet(Sequence): + def __contains__(self, val: Any) -> bool: + for r in self.__ranges: + if val in r: + return True + return False + ===========changed ref 42=========== + # module: aioquic.quic.packet_builder + class QuicPacketBuilder: + @property + def packet_number(self) -> int: + """ + Returns the packet number for the next packet. + """ + return self._packet_number + ===========changed ref 43=========== + # module: aioquic.quic.packet + def decode_reason_phrase(reason_bytes: bytes) -> str: + try: + return reason_bytes.decode("utf8") + except UnicodeDecodeError: + return "" +
examples.http3-server/HttpServer._consume_events
Modified
aiortc~aioquic
d01c68649c57e02e4343a86bc401d5beb0405de2
[quic] move quic code to aioquic.quic
<3>:<add> if isinstance(event, aioquic.quic.events.ConnectionTerminated): <del> if isinstance(event, aioquic.events.ConnectionTerminated): <11>:<add> elif isinstance(event, aioquic.quic.events.ProtocolNegotiated): <del> elif isinstance(event, aioquic.events.ProtocolNegotiated): <16>:<add> elif isinstance(event, aioquic.quic.events.ConnectionIdIssued): <del> elif isinstance(event, aioquic.events.ConnectionIdIssued): <18>:<add> elif isinstance(event, aioquic.quic.events.ConnectionIdRetired): <del> elif isinstance(event, aioquic.events.ConnectionIdRetired):
# module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: <0> # process events <1> event = connection.next_event() <2> while event is not None: <3> if isinstance(event, aioquic.events.ConnectionTerminated): <4> # remove the connection <5> for cid, conn in list(self._connections.items()): <6> if conn == connection: <7> del self._connections[cid] <8> self._http.pop(connection, None) <9> self._timer.pop(connection, None) <10> return <11> elif isinstance(event, aioquic.events.ProtocolNegotiated): <12> if event.alpn_protocol == "h3-22": <13> self._http[connection] = H3Connection(connection) <14> elif event.alpn_protocol == "hq-22": <15> self._http[connection] = H0Connection(connection) <16> elif isinstance(event, aioquic.events.ConnectionIdIssued): <17> self._connections[event.connection_id] = connection <18> elif isinstance(event, aioquic.events.ConnectionIdRetired): <19> assert self._connections[event.connection_id] == connection <20> del self._connections[event.connection_id] <21> <22> #  pass event to the HTTP layer <23> http = self._http.get(connection) <24> if http is not None: <25> for http_event in http.handle_event(event): <26> handle_http_event(http, http_event) <27> <28> event = connection.next_event() <29> <30> # send datagrams <31> for data, addr in connection.datagrams_to_send(now=self._loop.time()): <32> self._transport.sendto(data, addr) <33> <34> # re-arm timer <35> next_timer_at = connection.get_timer() <36> (timer, timer_at) = self._timer.get(connection, (None, None)) <37> if timer is not None and</s>
===========below chunk 0=========== # module: examples.http3-server class HttpServer(asyncio.DatagramProtocol): def _consume_events(self, connection: QuicConnection) -> None: # offset: 1 timer.cancel() timer = None if timer is None and timer_at is not None: timer = self._loop.call_at( next_timer_at, partial(self._handle_timer, connection) ) self._timer[connection] = (timer, next_timer_at) ===========unchanged ref 0=========== at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection datagrams_to_send(now: float) -> List[Tuple[bytes, NetworkAddress]] get_timer() -> Optional[float] next_event() -> Optional[events.Event] at: asyncio.events.AbstractEventLoop call_at(when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle time() -> float at: asyncio.events.TimerHandle __slots__ = ['_scheduled', '_when'] cancel() -> None at: asyncio.transports.DatagramTransport __slots__ = () sendto(data: Any, addr: Optional[_Address]=...) -> None at: examples.http3-server handle_http_event(connection: HttpConnection, event: aioquic.h3.events.Event) -> None at: examples.http3-server.HttpServer _handle_timer(connection: QuicConnection) -> None at: examples.http3-server.HttpServer.__init__ self._connections: Dict[bytes, QuicConnection] = {} self._http: Dict[QuicConnection, HttpConnection] = {} ===========unchanged ref 1=========== self._loop = asyncio.get_event_loop() self._timer: Dict[QuicConnection, Tuple[asyncio.TimerHandle, float]] = {} self._transport: Optional[asyncio.DatagramTransport] = None at: examples.http3-server.HttpServer.connection_made self._transport = cast(asyncio.DatagramTransport, transport) at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() 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.quic.connection + class QuicConnection: + """ + A QUIC connection. + """ + ===========changed ref 1=========== + # module: aioquic.quic.connection + class QuicConnection: + def next_event(self) -> Optional[events.Event]: + """ + Retrieve the next event from the event buffer. + + Returns `None` if there are no buffered events. + """ + try: + return self._events.popleft() + except IndexError: + return None + ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event) -> List[Event]: """ Handle a QUIC event and return a list of HTTP events. """ http_events: List[Event] = [] + if isinstance(event, aioquic.quic.events.StreamDataReceived): - if isinstance(event, aioquic.events.StreamDataReceived): http_events.extend( self._receive_stream_data(event.stream_id, event.data, event.end_stream) ) return http_events ===========changed ref 3=========== + # module: aioquic.quic.connection + class QuicConnection: + def get_timer(self) -> Optional[float]: + """ + Return the time at which the timer should fire or None if no timer is needed. + """ + timer_at = self._close_at + if self._state not in END_STATES: + # ack timer + for space in self._loss.spaces: + if space.ack_at is not None and space.ack_at < timer_at: + timer_at = space.ack_at + + # loss detection timer + self._loss_at = self._loss.get_loss_detection_time() + if self._loss_at is not None and self._loss_at < timer_at: + timer_at = self._loss_at + return timer_at + ===========changed ref 4=========== # module: aioquic.h0.connection class H0Connection: + def handle_event(self, event: aioquic.quic.events.Event) -> List[Event]: - def handle_event(self, event: aioquic.events.Event) -> List[Event]: http_events: List[Event] = [] if ( + isinstance(event, aioquic.quic.events.StreamDataReceived) - isinstance(event, aioquic.events.StreamDataReceived) and (event.stream_id % 4) == 0 ): data = event.data if not self._headers_received.get(event.stream_id, False): if self._is_client: http_events.append( ResponseReceived( headers=[], stream_ended=False, stream_id=event.stream_id ) ) else: method, path = data.rstrip().split(b" ", 1) http_events.append( RequestReceived( headers=[(b":method", method), (b":path", path)], stream_ended=False, stream_id=event.stream_id, ) ) data = b"" self._headers_received[event.stream_id] = True http_events.append( DataReceived( data=data, stream_ended=event.end_stream, stream_id=event.stream_id ) ) return http_events
examples.interop/test_version_negotiation
Modified
aiortc~aioquic
6b1303b581bb4d9f18b2caad7d95268af271d7e5
[interop] separate stateless retry test from the rest
<3>:<add> await connection.ping()
# module: examples.interop def test_version_negotiation(config, **kwargs): <0> async with connect( <1> config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs <2> ) as connection: <3> if connection._connection._version_negotiation_count == 1: <4> config.result |= Result.V <5>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] ===========changed ref 0=========== # module: examples.interop @dataclass class Config: name: str host: str port: int + retry_port: Optional[int] path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 1=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), - Config("aioquic", "quic.aiortc.org", 4434, "/"), + Config("ats", "quic.ogre.com", 4433, 4434, "/"), - Config("ats", "quic.ogre.com", 4434, "/"), + Config("f5", "f5quic.com", 4433, 4433, "/"), - Config("f5", "f5quic.com", 4433, "/"), + Config("gquic", "quic.rocks", 4433, 4433, "/"), - Config("gquic", "quic.rocks", 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), - Config("lsquic", "http3-test.litespeedtech.com", 4434, None), + Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), - Config("mvfst", "fb.mvfst.net", 4433, "/"), + Config("ngtcp2", "nghttp2.org", 4433, 4434, None), - Config("ngtcp2", "nghttp2.org", 4434, None), + Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), - Config("ngx_quic", "cloudflare-quic.com", 443, None), + Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), - Config("pandora", "pandora.cm.in.tum.de", 4433, "/"), + Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), - Config("picoquic", "test.privateoctopus.com", 4434</s> ===========changed ref 2=========== # module: examples.interop # offset: 1 <s> 4433, 4434, "/"), - Config("picoquic", "test.privateoctopus.com", 4434, "/"), + Config("quant", "quant.eggert.org", 4433, 4434, "/"), - Config("quant", "quant.eggert.org", 4434, "/"), + Config("quic-go", "quic.seemann.io", 443, 443, "/"), - Config("quic-go", "quic.seemann.io", 443, "/"), + Config("quiche", "quic.tech", 4433, 4433, "/"), - Config("quiche", "quic.tech", 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), - Config("quicker", "quicker.edm.uhasselt.be", 4433, "/"), + Config("quicly", "kazuhooku.com", 4433, 4434, "/"), - Config("quicly", "kazuhooku.com", 4434, "/"), + Config("quinn", "ralith.com", 4433, 4434, "/"), - Config("quinn", "ralith.com", 4433, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4434, "/"), ]
examples.interop/test_handshake_and_close
Modified
aiortc~aioquic
6b1303b581bb4d9f18b2caad7d95268af271d7e5
[interop] separate stateless retry test from the rest
<1>:<add> await connection.ping() <2>:<del> if connection._connection._stateless_retry_count == 1: <3>:<del> config.result |= Result.S
# module: examples.interop def test_handshake_and_close(config, **kwargs): <0> async with connect(config.host, config.port, **kwargs) as connection: <1> config.result |= Result.H <2> if connection._connection._stateless_retry_count == 1: <3> config.result |= Result.S <4> config.result |= Result.C <5>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop def test_version_negotiation(config, **kwargs): async with connect( config.host, config.port, protocol_version=0x1A2A3A4A, **kwargs ) as connection: + await connection.ping() if connection._connection._version_negotiation_count == 1: config.result |= Result.V ===========changed ref 1=========== # module: examples.interop @dataclass class Config: name: str host: str port: int + retry_port: Optional[int] path: str result: Result = field(default_factory=lambda: Result(0)) ===========changed ref 2=========== # module: examples.interop CONFIGS = [ + Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), - Config("aioquic", "quic.aiortc.org", 4434, "/"), + Config("ats", "quic.ogre.com", 4433, 4434, "/"), - Config("ats", "quic.ogre.com", 4434, "/"), + Config("f5", "f5quic.com", 4433, 4433, "/"), - Config("f5", "f5quic.com", 4433, "/"), + Config("gquic", "quic.rocks", 4433, 4433, "/"), - Config("gquic", "quic.rocks", 4433, "/"), + Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), - Config("lsquic", "http3-test.litespeedtech.com", 4434, None), + Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), - Config("mvfst", "fb.mvfst.net", 4433, "/"), + Config("ngtcp2", "nghttp2.org", 4433, 4434, None), - Config("ngtcp2", "nghttp2.org", 4434, None), + Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), - Config("ngx_quic", "cloudflare-quic.com", 443, None), + Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), - Config("pandora", "pandora.cm.in.tum.de", 4433, "/"), + Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), - Config("picoquic", "test.privateoctopus.com", 4434</s> ===========changed ref 3=========== # module: examples.interop # offset: 1 <s> 4433, 4434, "/"), - Config("picoquic", "test.privateoctopus.com", 4434, "/"), + Config("quant", "quant.eggert.org", 4433, 4434, "/"), - Config("quant", "quant.eggert.org", 4434, "/"), + Config("quic-go", "quic.seemann.io", 443, 443, "/"), - Config("quic-go", "quic.seemann.io", 443, "/"), + Config("quiche", "quic.tech", 4433, 4433, "/"), - Config("quiche", "quic.tech", 4433, "/"), + Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), - Config("quicker", "quicker.edm.uhasselt.be", 4433, "/"), + Config("quicly", "kazuhooku.com", 4433, 4434, "/"), - Config("quicly", "kazuhooku.com", 4434, "/"), + Config("quinn", "ralith.com", 4433, 4434, "/"), - Config("quinn", "ralith.com", 4433, "/"), + Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), - Config("winquic", "quic.westus.cloudapp.azure.com", 4434, "/"), ]
examples.http3-client/run
Modified
aiortc~aioquic
659aaff67ea8b508400ea580d9a0d43e0fdce7ec
[examples] make http3 client example use asyncio
<10>:<add> # lookup remote address <add> infos = await loop.getaddrinfo(server_name, port, type=socket.SOCK_DGRAM) <add> server_addr = infos[0][4] <add> if len(server_addr) == 2: <add> server_addr = ("::ffff:" + server_addr[0], server_addr[1], 0, 0) <del> # prepare socket <11>:<del> server_addr = (socket.gethostbyname(server_name), port) <12>:<del> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <15>:<add> _, client = await loop.create_datagram_endpoint( <add> lambda: HttpClient( <del> quic = QuicConnection( <16>:<add> configuration=QuicConfiguration( <del> configuration=QuicConfiguration( <17>:<add> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <del> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <18>:<add> is_client=True, <del> is_client=True, <19>:<add> server_name=server_name, <del> server_name=server_name, <20>:<add> **kwargs <del> **kwargs <21>:<add> ), <add> server_addr=server_addr, <add> session_ticket_handler=save_session_ticket, <22>:<add> local_addr=("::", 0), <del> session_ticket_handler=save_session_ticket, <24>:<add> client =
# module: examples.http3-client + def run(url: str, legacy_http: bool, **kwargs) -> None: - def run(url: str, legacy_http: bool, **kwargs) -> None: <0> # parse URL <1> parsed = urlparse(url) <2> assert parsed.scheme == "https", "Only HTTPS URLs are supported." <3> if ":" in parsed.netloc: <4> server_name, port_str = parsed.netloc.split(":") <5> port = int(port_str) <6> else: <7> server_name = parsed.netloc <8> port = 443 <9> <10> # prepare socket <11> server_addr = (socket.gethostbyname(server_name), port) <12> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <13> <14> # prepare QUIC connection <15> quic = QuicConnection( <16> configuration=QuicConfiguration( <17> alpn_protocols=["hq-22" if legacy_http else "h3-22"], <18> is_client=True, <19> server_name=server_name, <20> **kwargs <21> ), <22> session_ticket_handler=save_session_ticket, <23> ) <24> quic.connect(server_addr, now=time.time()) <25> <26> # send request <27> http: HttpConnection <28> if legacy_http: <29> http = H0Connection(quic) <30> else: <31> http = H3Connection(quic) <32> stream_id = quic.get_next_available_stream_id() <33> http.send_headers( <34> stream_id=stream_id, <35> headers=[ <36> (b":method", b"GET"), <37> (b":scheme", parsed.scheme.encode("utf8")), <38> (b":authority", parsed.netloc.encode("utf8")), <39> (b":path", parsed.path.encode("utf8")), <40> (b"user-agent", b"aioquic"), <41> ],</s>
===========below chunk 0=========== # module: examples.http3-client + def run(url: str, legacy_http: bool, **kwargs) -> None: - def run(url: str, legacy_http: bool, **kwargs) -> None: # offset: 1 http.send_data(stream_id=stream_id, data=b"", end_stream=True) for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # handle events stream_ended = False while not stream_ended: data, addr = sock.recvfrom(2048) quic.receive_datagram(data, addr, now=time.time()) # process events event = quic.next_event() while event is not None: for http_event in http.handle_event(event): if isinstance(http_event, ResponseReceived): stream_ended = http_event.stream_ended headers = b"" for k, v in http_event.headers: headers += k + b": " + v + b"\r\n" if headers: sys.stderr.buffer.write(headers + b"\r\n") sys.stderr.buffer.flush() if isinstance(http_event, DataReceived): stream_ended = http_event.stream_ended sys.stdout.buffer.write(http_event.data) event = quic.next_event() # send datagrams for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) # close connection quic.close() for data, addr in quic.datagrams_to_send(now=time.time()): sock.sendto(data, addr) ===========unchanged ref 0=========== at: _asyncio get_event_loop() at: _asyncio.Future set_result(result, /) at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h0.connection.H0Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: List[Tuple[bytes, bytes]]) -> None at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection handle_event(event: aioquic.quic.events.Event) -> List[Event] send_data(stream_id: int, data: bytes, end_stream: bool) -> None send_headers(stream_id: int, headers: Headers) -> None at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any ===========unchanged ref 1=========== QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.quic.connection.QuicConnection close(error_code: int=QuicErrorCode.NO_ERROR, frame_type: Optional[int]=None, reason_phrase: str="") -> None connect(addr: NetworkAddress, now: float, protocol_version: Optional[int]=None) -> None get_next_available_stream_id(is_unidirectional=False) -> int next_event() -> Optional[events.Event] receive_datagram(data: bytes, addr: NetworkAddress, now: float) -> None at: aioquic.quic.events ConnectionTerminated(error_code: int, frame_type: Optional[int], reason_phrase: str) at: asyncio.events TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop at: asyncio.events.AbstractEventLoop time() -> float create_future() -> Future[Any] at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.futures.Future _state = _PENDING _result = None _exception = None _loop = None _source_traceback = None _cancel_message = None _cancelled_exc = None _asyncio_future_blocking = False __log_traceback = False __class_getitem__ = classmethod(GenericAlias) set_result(result: _T, /) -> None __iter__ = __await__ # make compatible with 'yield from'. ===========unchanged ref 2=========== at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: asyncio.locks.Event wait() -> bool at: asyncio.protocols.BaseProtocol __slots__ = () connection_made(self, transport: transports.BaseTransport) -> None at: asyncio.protocols.DatagramProtocol __slots__ = () datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None at: asyncio.tasks shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop]=...) -> Future[_T] at: asyncio.transports BaseTransport(extra: Optional[Mapping[Any, Any]]=...) DatagramTransport(extra: Optional[Mapping[Any, Any]]=...) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-client.HttpClient._consume_events self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: examples.http3-client.HttpClient._handle_timer self._timer = None self._timer_at = None at: typing cast(typ: Type[_T], val: Any) -> _T cast(typ: str, val: Any) -> Any cast(typ: object, val: Any) -> Any List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') Text = str at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T]
aioquic.tls/pull_client_hello
Modified
aiortc~aioquic
3ad2650f57fbc13f539606b2d0b55be7c39eefdc
[tls] don't fail if presented with unsupported cipher suites
<8>:<add> cipher_suites=pull_list(buf, 2, buf.pull_uint16), <del> cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)),
# module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: <0> assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> client_random = buf.pull_bytes(32) <4> <5> hello = ClientHello( <6> random=client_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), <9> compression_methods=pull_list( <10> buf, 1, partial(pull_compression_method, buf) <11> ), <12> ) <13> <14> # extensions <15> after_psk = False <16> <17> def pull_extension() -> None: <18> # pre_shared_key MUST be last <19> nonlocal after_psk <20> assert not after_psk <21> <22> extension_type = buf.pull_uint16() <23> extension_length = buf.pull_uint16() <24> if extension_type == ExtensionType.KEY_SHARE: <25> hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) <26> elif extension_type == ExtensionType.SUPPORTED_VERSIONS: <27> hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) <28> elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: <29> hello.signature_algorithms = pull_list( <30> buf, 2, partial(pull_signature_algorithm, buf) <31> ) <32> elif extension_type == ExtensionType.SUPPORTED_GROUPS: <33> hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) <34> elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: <35> hello.psk_key_exchange_modes = pull_list( <36> buf, 1, partial(pull_psk_key_exchange_mode</s>
===========below chunk 0=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 ) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_bytes(length: int) -> bytes pull_uint8() -> int pull_uint16() -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_compression_method(buf: Buffer) -> CompressionMethod pull_group(buf: Buffer) -> Group pull_psk_key_exchange_mode(buf: Buffer) -> PskKeyExchangeMode pull_signature_algorithm(buf: Buffer) -> SignatureAlgorithm pull_block(buf: Buffer, capacity: int) -> Generator pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T] pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry pull_alpn_protocol(buf: Buffer) -> str pull_psk_identity(buf: Buffer) -> PskIdentity pull_psk_binder(buf: Buffer) -> bytes OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ===========unchanged ref 1=========== ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) at: aioquic.tls.ClientHello random: bytes session_id: bytes cipher_suites: List[int] compression_methods: List[CompressionMethod] alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) at: aioquic.tls.OfferedPsks identities: List[PskIdentity] binders: List[bytes] at: functools partial(func: Callable[..., _T], *args: Any, **kwargs: Any) partial(func, *args, **keywords, /) -> function with partial application() ===========changed ref 0=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes + cipher_suites: List[int] - cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls - # INTEGERS - - - def pull_cipher_suite(buf: Buffer) -> CipherSuite: - return CipherSuite(buf.pull_uint16()) -
aioquic.tls/pull_server_hello
Modified
aiortc~aioquic
3ad2650f57fbc13f539606b2d0b55be7c39eefdc
[tls] don't fail if presented with unsupported cipher suites
<8>:<add> cipher_suite=buf.pull_uint16(), <del> cipher_suite=pull_cipher_suite(buf),
# module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: <0> assert buf.pull_uint8() == HandshakeType.SERVER_HELLO <1> with pull_block(buf, 3): <2> assert buf.pull_uint16() == TLS_VERSION_1_2 <3> server_random = buf.pull_bytes(32) <4> <5> hello = ServerHello( <6> random=server_random, <7> session_id=pull_opaque(buf, 1), <8> cipher_suite=pull_cipher_suite(buf), <9> compression_method=pull_compression_method(buf), <10> ) <11> <12> # extensions <13> def pull_extension() -> None: <14> extension_type = buf.pull_uint16() <15> extension_length = buf.pull_uint16() <16> if extension_type == ExtensionType.SUPPORTED_VERSIONS: <17> hello.supported_version = buf.pull_uint16() <18> elif extension_type == ExtensionType.KEY_SHARE: <19> hello.key_share = pull_key_share(buf) <20> elif extension_type == ExtensionType.PRE_SHARED_KEY: <21> hello.pre_shared_key = buf.pull_uint16() <22> else: <23> hello.other_extensions.append( <24> (extension_type, buf.pull_bytes(extension_length)) <25> ) <26> <27> pull_list(buf, 2, pull_extension) <28> <29> return hello <30>
===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer pull_bytes(length: int) -> bytes pull_uint16() -> int at: aioquic.tls TLS_VERSION_1_2 = 0x0303 ExtensionType(x: Union[str, bytes, bytearray], base: int) ExtensionType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) pull_compression_method(buf: Buffer) -> CompressionMethod pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T] pull_opaque(buf: Buffer, capacity: int) -> bytes pull_key_share(buf: Buffer) -> KeyShareEntry ServerHello(random: bytes, session_id: bytes, cipher_suite: int, compression_method: CompressionMethod, key_share: Optional[KeyShareEntry]=None, pre_shared_key: Optional[int]=None, supported_version: Optional[int]=None, other_extensions: List[Tuple[int, bytes]]=field(default_factory=list)) at: aioquic.tls.ServerHello random: bytes session_id: bytes cipher_suite: int compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 0=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes + cipher_suite: int - cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls - # INTEGERS - - - def pull_cipher_suite(buf: Buffer) -> CipherSuite: - return CipherSuite(buf.pull_uint16()) - ===========changed ref 2=========== # module: aioquic.tls @dataclass class ClientHello: random: bytes session_id: bytes + cipher_suites: List[int] - cipher_suites: List[CipherSuite] compression_methods: List[CompressionMethod] # extensions alpn_protocols: Optional[List[str]] = None early_data: bool = False key_share: Optional[List[KeyShareEntry]] = None pre_shared_key: Optional[OfferedPsks] = None psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]] = None server_name: Optional[str] = None signature_algorithms: Optional[List[SignatureAlgorithm]] = None supported_groups: Optional[List[Group]] = None supported_versions: Optional[List[int]] = None other_extensions: List[Extension] = field(default_factory=list) ===========changed ref 3=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: assert buf.pull_uint8() == HandshakeType.CLIENT_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 client_random = buf.pull_bytes(32) hello = ClientHello( random=client_random, session_id=pull_opaque(buf, 1), + cipher_suites=pull_list(buf, 2, buf.pull_uint16), - cipher_suites=pull_list(buf, 2, partial(pull_cipher_suite, buf)), compression_methods=pull_list( buf, 1, partial(pull_compression_method, buf) ), ) # extensions after_psk = False def pull_extension() -> None: # pre_shared_key MUST be last nonlocal after_psk assert not after_psk extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_list(buf, 2, partial(pull_key_share, buf)) elif extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_versions = pull_list(buf, 1, buf.pull_uint16) elif extension_type == ExtensionType.SIGNATURE_ALGORITHMS: hello.signature_algorithms = pull_list( buf, 2, partial(pull_signature_algorithm, buf) ) elif extension_type == ExtensionType.SUPPORTED_GROUPS: hello.supported_groups = pull_list(buf, 2, partial(pull_group, buf)) elif extension_type == ExtensionType.PSK_KEY_EXCHANGE_MODES: hello.psk_key_exchange_modes = pull_list( buf, 1, partial(pull_psk_key_exchange_mode, buf) ) elif extension_type ==</s> ===========changed ref 4=========== # module: aioquic.tls def pull_client_hello(buf: Buffer) -> ClientHello: # offset: 1 <s> buf, 1, partial(pull_psk_key_exchange_mode, buf) ) elif extension_type == ExtensionType.SERVER_NAME: with pull_block(buf, 2): assert buf.pull_uint8() == 0 hello.server_name = pull_opaque(buf, 2).decode("ascii") elif extension_type == ExtensionType.ALPN: hello.alpn_protocols = pull_list( buf, 2, partial(pull_alpn_protocol, buf) ) elif extension_type == ExtensionType.EARLY_DATA: hello.early_data = True elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = OfferedPsks( identities=pull_list(buf, 2, partial(pull_psk_identity, buf)), binders=pull_list(buf, 2, partial(pull_psk_binder, buf)), ) after_psk = True else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello
aioquic.tls/Context._client_send_hello
Modified
aiortc~aioquic
3ad2650f57fbc13f539606b2d0b55be7c39eefdc
[tls] don't fail if presented with unsupported cipher suites
<20>:<add> cipher_suites=[int(x) for x in self._cipher_suites], <del> cipher_suites=self._cipher_suites,
# module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: <0> key_share: List[KeyShareEntry] = [] <1> supported_groups: List[Group] = [] <2> <3> if Group.SECP256R1 in self._supported_groups: <4> self._ec_private_key = ec.generate_private_key( <5> GROUP_TO_CURVE[Group.SECP256R1](), default_backend() <6> ) <7> key_share.append(encode_public_key(self._ec_private_key.public_key())) <8> supported_groups.append(Group.SECP256R1) <9> <10> if Group.X25519 in self._supported_groups: <11> self._x25519_private_key = x25519.X25519PrivateKey.generate() <12> key_share.append(encode_public_key(self._x25519_private_key.public_key())) <13> supported_groups.append(Group.X25519) <14> <15> assert len(key_share), "no key share entries" <16> <17> hello = ClientHello( <18> random=self.client_random, <19> session_id=self.session_id, <20> cipher_suites=self._cipher_suites, <21> compression_methods=self._compression_methods, <22> alpn_protocols=self.alpn_protocols, <23> key_share=key_share, <24> psk_key_exchange_modes=self._psk_key_exchange_modes <25> if (self.session_ticket or self.new_session_ticket_cb is not None) <26> else None, <27> server_name=self.server_name, <28> signature_algorithms=self._signature_algorithms, <29> supported_groups=supported_groups, <30> supported_versions=self._supported_versions, <31> other_extensions=self.handshake_extensions, <32> ) <33> <34> # PSK <35> if self.session_ticket and self.session_ticket.is_valid: <36> </s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 1 self._key_schedule_psk.extract(self.session_ticket.resumption_secret) binder_key = self._key_schedule_psk.derive_secret(b"res binder") binder_length = self._key_schedule_psk.algorithm.digest_size # update hello if self.session_ticket.max_early_data_size is not None: hello.early_data = True hello.pre_shared_key = OfferedPsks( identities=[ (self.session_ticket.ticket, self.session_ticket.obfuscated_age) ], binders=[bytes(binder_length)], ) # serialize hello without binder tmp_buf = Buffer(capacity=1024) push_client_hello(tmp_buf, hello) # calculate binder hash_offset = tmp_buf.tell() - binder_length - 3 self._key_schedule_psk.update_hash(tmp_buf.data_slice(0, hash_offset)) binder = self._key_schedule_psk.finished_verify_data(binder_key) hello.pre_shared_key.binders[0] = binder self._key_schedule_psk.update_hash( tmp_buf.data_slice(hash_offset, hash_offset + 3) + binder ) # calculate early data key if hello.early_data: early_key = self._key_schedule_psk.derive_secret(b"c e traffic") self.update_traffic_key_cb( Direction.ENCRYPT, Epoch.ZERO_RTT, self._key_schedule_psk.cipher_suite, early_key, ) self._key_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None)</s> ===========below chunk 1=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: # offset: 2 <s>_schedule_proxy = KeyScheduleProxy(hello.cipher_suites) self._key_schedule_proxy.extract(None) with push_message(self._key_schedule_proxy, output_buf): push_client_hello(output_buf, hello) self._set_state(State.CLIENT_EXPECT_SERVER_HELLO) ===========unchanged ref 0=========== at: aioquic._buffer Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer data_slice(start: int, end: int) -> bytes tell() -> int at: aioquic.tls Direction() Epoch() State() Group(x: Union[str, bytes, bytearray], base: int) Group(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) OfferedPsks(identities: List[PskIdentity], binders: List[bytes]) ClientHello(random: bytes, session_id: bytes, cipher_suites: List[int], compression_methods: List[CompressionMethod], alpn_protocols: Optional[List[str]]=None, early_data: bool=False, key_share: Optional[List[KeyShareEntry]]=None, pre_shared_key: Optional[OfferedPsks]=None, psk_key_exchange_modes: Optional[List[PskKeyExchangeMode]]=None, server_name: Optional[str]=None, signature_algorithms: Optional[List[SignatureAlgorithm]]=None, supported_groups: Optional[List[Group]]=None, supported_versions: Optional[List[int]]=None, other_extensions: List[Extension]=field(default_factory=list)) push_client_hello(buf: Buffer, hello: ClientHello) -> None pull_server_hello(buf: Buffer) -> ServerHello KeySchedule(cipher_suite: CipherSuite) KeyScheduleProxy(cipher_suites: List[CipherSuite]) GROUP_TO_CURVE = { Group.SECP256R1: ec.SECP256R1, Group.SECP384R1: ec.SECP384R1, Group.SECP521R1: ec.SECP521R1, } encode_public_key(public_key: Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey]) -> KeyShareEntry ===========unchanged ref 1=========== push_message(key_schedule: Union[KeySchedule, KeyScheduleProxy], buf: Buffer) -> Generator at: aioquic.tls.ClientHello early_data: bool = False pre_shared_key: Optional[OfferedPsks] = None at: aioquic.tls.Context _set_state(state: State) -> None at: aioquic.tls.Context.__init__ self.alpn_protocols: Optional[List[str]] = None self.handshake_extensions: List[Extension] = [] self.session_ticket: Optional[SessionTicket] = None self.server_name: Optional[str] = None self.new_session_ticket_cb: Optional[SessionTicketHandler] = None self.update_traffic_key_cb: Callable[ [Direction, Epoch, CipherSuite, bytes], None ] = lambda d, e, c, s: None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._psk_key_exchange_modes = [PskKeyExchangeMode.PSK_DHE_KE] self._signature_algorithms = [ SignatureAlgorithm.RSA_PSS_RSAE_SHA256, SignatureAlgorithm.ECDSA_SECP256R1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA256, SignatureAlgorithm.RSA_PKCS1_SHA1, ] self._supported_groups = [Group.SECP256R1] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None
aioquic.tls/Context._client_handle_hello
Modified
aiortc~aioquic
3ad2650f57fbc13f539606b2d0b55be7c39eefdc
[tls] don't fail if presented with unsupported cipher suites
<2>:<add> cipher_suite = negotiate( <add> self._cipher_suites, <add> [peer_hello.cipher_suite], <add> AlertHandshakeFailure("Unsupported cipher suite"), <add> ) <del> assert peer_hello.cipher_suite in self._cipher_suites <11>:<add> or cipher_suite != self._key_schedule_psk.cipher_suite <del> or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite <17>:<add> self.key_schedule = self._key_schedule_proxy.select(cipher_suite) <del> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite)
# module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: <0> peer_hello = pull_server_hello(input_buf) <1> <2> assert peer_hello.cipher_suite in self._cipher_suites <3> assert peer_hello.compression_method in self._compression_methods <4> assert peer_hello.supported_version in self._supported_versions <5> <6> # select key schedule <7> if peer_hello.pre_shared_key is not None: <8> if ( <9> self._key_schedule_psk is None <10> or peer_hello.pre_shared_key != 0 <11> or peer_hello.cipher_suite != self._key_schedule_psk.cipher_suite <12> ): <13> raise AlertIllegalParameter <14> self.key_schedule = self._key_schedule_psk <15> self._session_resumed = True <16> else: <17> self.key_schedule = self._key_schedule_proxy.select(peer_hello.cipher_suite) <18> self._key_schedule_psk = None <19> self._key_schedule_proxy = None <20> <21> # perform key exchange <22> peer_public_key = decode_public_key(peer_hello.key_share) <23> shared_key: Optional[bytes] = None <24> if ( <25> isinstance(peer_public_key, x25519.X25519PublicKey) <26> and self._x25519_private_key is not None <27> ): <28> shared_key = self._x25519_private_key.exchange(peer_public_key) <29> elif ( <30> isinstance(peer_public_key, ec.EllipticCurvePublicKey) <31> and self._ec_private_key is not None <32> and self._ec_private_key.public_key().curve.__class__ <33> == peer_public_key.curve.__class__ <34> ): <35> shared_key = self._ec_private_key.exchange(ec.ECDH(), peer_public_key) <36> </s>
===========below chunk 0=========== # module: aioquic.tls class Context: def _client_handle_hello(self, input_buf: Buffer, output_buf: Buffer) -> None: # offset: 1 self.key_schedule.update_hash(input_buf.data) self.key_schedule.extract(shared_key) self._setup_traffic_protection( Direction.DECRYPT, Epoch.HANDSHAKE, b"s hs traffic" ) self._set_state(State.CLIENT_EXPECT_ENCRYPTED_EXTENSIONS) ===========unchanged ref 0=========== at: aioquic.tls AlertHandshakeFailure(*args: object) AlertIllegalParameter(*args: object) Direction() Epoch() decode_public_key(key_share: KeyShareEntry) -> Union[ec.EllipticCurvePublicKey, x25519.X25519PublicKey] negotiate(supported: List[T], offered: Optional[List[Any]], exc: Optional[Alert]=None) -> T at: aioquic.tls.Context _setup_traffic_protection(direction: Direction, epoch: Epoch, label: bytes) -> None at: aioquic.tls.Context.__init__ self.key_schedule: Optional[KeySchedule] = None self._cipher_suites = [ CipherSuite.AES_256_GCM_SHA384, CipherSuite.AES_128_GCM_SHA256, CipherSuite.CHACHA20_POLY1305_SHA256, ] self._compression_methods = [CompressionMethod.NULL] self._supported_versions = [TLS_VERSION_1_3] self._key_schedule_psk: Optional[KeySchedule] = None self._key_schedule_proxy: Optional[KeyScheduleProxy] = None self._session_resumed = False self._ec_private_key: Optional[ec.EllipticCurvePrivateKey] = None self._x25519_private_key: Optional[x25519.X25519PrivateKey] = None at: aioquic.tls.Context._client_handle_hello peer_hello = pull_server_hello(input_buf) at: aioquic.tls.Context._client_send_hello self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) self._x25519_private_key = x25519.X25519PrivateKey.generate() self._key_schedule_psk = KeySchedule(self.session_ticket.cipher_suite) ===========unchanged ref 1=========== self._key_schedule_proxy = KeyScheduleProxy(self._cipher_suites) at: aioquic.tls.Context._server_handle_hello self.key_schedule = KeySchedule(cipher_suite) self._session_resumed = True self._x25519_private_key = x25519.X25519PrivateKey.generate() self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[key_share[0]](), default_backend() ) at: aioquic.tls.KeySchedule extract(key_material: Optional[bytes]=None) -> None update_hash(data: bytes) -> None at: aioquic.tls.KeySchedule.__init__ self.cipher_suite = cipher_suite at: aioquic.tls.KeyScheduleProxy select(cipher_suite: CipherSuite) -> KeySchedule at: aioquic.tls.ServerHello cipher_suite: int compression_method: CompressionMethod key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None ===========changed ref 0=========== # module: aioquic.tls @dataclass class ServerHello: random: bytes session_id: bytes + cipher_suite: int - cipher_suite: CipherSuite compression_method: CompressionMethod # extensions key_share: Optional[KeyShareEntry] = None pre_shared_key: Optional[int] = None supported_version: Optional[int] = None other_extensions: List[Tuple[int, bytes]] = field(default_factory=list) ===========changed ref 1=========== # module: aioquic.tls - # INTEGERS - - - def pull_cipher_suite(buf: Buffer) -> CipherSuite: - return CipherSuite(buf.pull_uint16()) - ===========changed ref 2=========== # module: aioquic.tls def pull_server_hello(buf: Buffer) -> ServerHello: assert buf.pull_uint8() == HandshakeType.SERVER_HELLO with pull_block(buf, 3): assert buf.pull_uint16() == TLS_VERSION_1_2 server_random = buf.pull_bytes(32) hello = ServerHello( random=server_random, session_id=pull_opaque(buf, 1), + cipher_suite=buf.pull_uint16(), - cipher_suite=pull_cipher_suite(buf), compression_method=pull_compression_method(buf), ) # extensions def pull_extension() -> None: extension_type = buf.pull_uint16() extension_length = buf.pull_uint16() if extension_type == ExtensionType.SUPPORTED_VERSIONS: hello.supported_version = buf.pull_uint16() elif extension_type == ExtensionType.KEY_SHARE: hello.key_share = pull_key_share(buf) elif extension_type == ExtensionType.PRE_SHARED_KEY: hello.pre_shared_key = buf.pull_uint16() else: hello.other_extensions.append( (extension_type, buf.pull_bytes(extension_length)) ) pull_list(buf, 2, pull_extension) return hello ===========changed ref 3=========== # module: aioquic.tls class Context: def _client_send_hello(self, output_buf: Buffer) -> None: key_share: List[KeyShareEntry] = [] supported_groups: List[Group] = [] if Group.SECP256R1 in self._supported_groups: self._ec_private_key = ec.generate_private_key( GROUP_TO_CURVE[Group.SECP256R1](), default_backend() ) key_share.append(encode_public_key(self._ec_private_key.public_key())) supported_groups.append(Group.SECP256R1) if Group.X25519 in self._supported_groups: self._x25519_private_key = x25519.X25519PrivateKey.generate() key_share.append(encode_public_key(self._x25519_private_key.public_key())) supported_groups.append(Group.X25519) assert len(key_share), "no key share entries" hello = ClientHello( random=self.client_random, session_id=self.session_id, + cipher_suites=[int(x) for x in self._cipher_suites], - cipher_suites=self._cipher_suites, compression_methods=self._compression_methods, alpn_protocols=self.alpn_protocols, key_share=key_share, psk_key_exchange_modes=self._psk_key_exchange_modes if (self.session_ticket or self.new_session_ticket_cb is not None) else None, server_name=self.server_name, signature_algorithms=self._signature_algorithms, supported_groups=supported_groups, supported_versions=self._supported_versions, other_extensions=self.handshake_extensions, ) # PSK if self.session_ticket and self.session_ticket.is_valid: self._key_schedule_psk = KeySchedule(self</s>
examples.http3-client/HttpClient.__init__
Modified
aiortc~aioquic
727405af8916490c50afe2502ec0096c3123734c
[examples] make HTTP/3 client save session ticket
<4>:<add> self._quic = QuicConnection( <add> configuration=configuration, session_ticket_handler=session_ticket_handler <add> ) <del> self._quic = QuicConnection(configuration=configuration)
# module: examples.http3-client class HttpClient(asyncio.DatagramProtocol): def __init__( self, *, configuration: QuicConfiguration, server_addr: NetworkAddress, session_ticket_handler: Optional[SessionTicketHandler] = None ): <0> self._closed = asyncio.Event() <1> self._connect_called = False <2> self._http: HttpConnection <3> self._loop = asyncio.get_event_loop() <4> self._quic = QuicConnection(configuration=configuration) <5> self._server_addr = server_addr <6> self._timer: Optional[asyncio.TimerHandle] = None <7> self._timer_at = 0.0 <8> <9> self._request_events: Dict[int, List[Event]] = {} <10> self._request_waiter: Dict[int, asyncio.Future[List[Event]]] = {} <11> <12> if configuration.alpn_protocols[0].startswith("hq-"): <13> self._http = H0Connection(self._quic) <14> else: <15> self._http = H3Connection(self._quic) <16>
===========unchanged ref 0=========== at: _asyncio get_event_loop() at: aioquic.h0.connection H0Connection(quic: QuicConnection) at: aioquic.h3.events Event() at: aioquic.quic.configuration QuicConfiguration(alpn_protocols: Optional[List[str]]=None, certificate: Any=None, idle_timeout: float=60.0, is_client: bool=True, private_key: Any=None, secrets_log_file: TextIO=None, server_name: Optional[str]=None, session_ticket: Optional[SessionTicket]=None, supported_versions: List[QuicProtocolVersion]=field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] )) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: aioquic.tls SessionTicketHandler = Callable[[SessionTicket], None] at: asyncio.events TimerHandle(when: float, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop, context: Optional[Context]=...) get_event_loop() -> AbstractEventLoop ===========unchanged ref 1=========== at: asyncio.futures Future(*, loop: Optional[AbstractEventLoop]=...) Future = _CFuture = _asyncio.Future at: asyncio.locks Event(*, loop: Optional[AbstractEventLoop]=...) at: examples.http3-client HttpConnection = Union[H0Connection, H3Connection] at: examples.http3-client.HttpClient._consume_events self._timer = self._loop.call_at(timer_at, self._handle_timer) self._timer = None self._timer_at = timer_at at: examples.http3-client.HttpClient._handle_timer self._timer = None self._timer_at = None at: examples.http3-client.HttpClient.get self._connect_called = True at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
examples.interop/test_session_resumption
Modified
aiortc~aioquic
975975ab854a8e2e0c7d2622377a844aa18ea79f
[interop] rework interop script
<22>:<add> # check session was resumed <del> # check session was resumed <23>:<add> if connection._connection.tls.session_resumed: <del> if connection._connection.tls.session_resumed: <24>:<add> config.result |= Result.R <del> config.result |= Result.R <26>:<add> # check early data was accepted <del> # check early data was accepted <27>:<add> if connection._connection.tls.early_data_accepted: <del> if connection._connection.tls.early_data_accepted: <28>:<add> config.result |= Result.Z <del> config.result |= Result.Z
# module: examples.interop def test_session_resumption(config, **kwargs): <0> saved_ticket = None <1> <2> def session_ticket_handler(ticket): <3> nonlocal saved_ticket <4> saved_ticket = ticket <5> <6> # connect a first time, receive a ticket <7> async with connect( <8> config.host, <9> config.port, <10> session_ticket_handler=session_ticket_handler, <11> **kwargs <12> ) as connection: <13> await connection.ping() <14> <15> # connect a second time, with the ticket <16> if saved_ticket is not None: <17> async with connect( <18> config.host, config.port, session_ticket=saved_ticket, **kwargs <19> ) as connection: <20> await connection.ping() <21> <22> # check session was resumed <23> if connection._connection.tls.session_resumed: <24> config.result |= Result.R <25> <26> # check early data was accepted <27> if connection._connection.tls.early_data_accepted: <28> config.result |= Result.Z <29>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._connection = connection at: aioquic.quic.connection.QuicConnection.__init__ self._stateless_retry_count = 0 at: aioquic.quic.connection.QuicConnection.receive_datagram self._stateless_retry_count += 1 at: examples.interop Result() http_request(connection, path) http3_request(connection, authority, path) ===========changed ref 0=========== # module: examples.interop + def http3_request(connection, authority, path): + reader, writer = await connection.create_stream() + stream_id = writer.get_extra_info("stream_id") + + http = H3Connection(connection._connection) + http.send_headers( + stream_id=stream_id, + headers=[ + (b":method", b"GET"), + (b":scheme", b"https"), + (b":authority", authority.encode("utf8")), + (b":path", path.encode("utf8")), + ], + ) + http.send_data(stream_id=stream_id, data=b"", end_stream=True) + + return await reader.read() + ===========changed ref 1=========== # module: examples.interop class Result(Flag): + V = 0x0001 - V = 1 + H = 0x0002 - H = 2 + D = 0x0004 - D = 4 + C = 0x0008 - C = 8 + R = 0x0010 - R = 16 + Z = 0x0020 - Z = 32 + S = 0x0040 - S = 64 - # M = 128 - # B = 256 - U = 512 - # 3 = 1024 + M = 0x0080 + B = 0x0100 + U = 0x0200 + P = 0x0400 - P = 2048 + E = 0x0800 + T = 0x1000 + three = 0x2000 + d = 0x4000 + p = 0x8000 ===========changed ref 2=========== # module: examples.interop - def test_data_transfer(config, **kwargs): - if config.path is None: - return - - async with connect(config.host, config.port, **kwargs) as connection: - response1 = await http_request(connection, config.path) - response2 = await http_request(connection, config.path) - - if response1 and response2: - config.result |= Result.D - ===========changed ref 3=========== # module: examples.interop CONFIGS = [ Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), Config("ats", "quic.ogre.com", 4433, 4434, "/"), Config("f5", "f5quic.com", 4433, 4433, "/"), Config("gquic", "quic.rocks", 4433, 4433, "/"), Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, None), Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), Config("quant", "quant.eggert.org", 4433, 4434, "/"), Config("quic-go", "quic.seemann.io", 443, 443, "/"), Config("quiche", "quic.tech", 4433, 4433, "/"), Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), Config("quicly", "kazuhooku.com", 4433, 4434, "/"), Config("quinn", "ralith.com", 4433, 4434, "/"), Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/print_result
Modified
aiortc~aioquic
975975ab854a8e2e0c7d2622377a844aa18ea79f
[interop] rework interop script
<0>:<add> result = str(config.result).replace("three", "3") <add> result = result[0:7] + " " + result[7:13] + " " + result[13:] <add> print("%s%s%s" % (config.name, " " * (20 - len(config.name)), result)) <del> print("%s%s%s" % (config.name, " " * (20 - len(config.name)), config.result))
# module: examples.interop def print_result(config: Config) -> None: <0> print("%s%s%s" % (config.name, " " * (20 - len(config.name)), config.result)) <1>
===========unchanged ref 0=========== at: aioquic.asyncio.protocol.QuicConnectionProtocol ping() -> None ===========changed ref 0=========== # module: examples.interop + def test_http_0(config, **kwargs): + if config.path is None: + return + + kwargs["alpn_protocols"] = ["hq-22"] + async with connect(config.host, config.port, **kwargs) as connection: + response = await http_request(connection, config.path) + if response: + config.result |= Result.D + ===========changed ref 1=========== # module: examples.interop + def test_http_3(config, **kwargs): + if config.path is None: + return + + kwargs["alpn_protocols"] = ["h3-22"] + async with connect(config.host, config.port, **kwargs) as connection: + response = await http3_request(connection, config.host, config.path) + if response: + config.result |= Result.D + config.result |= Result.three + ===========changed ref 2=========== # module: examples.interop - def test_data_transfer(config, **kwargs): - if config.path is None: - return - - async with connect(config.host, config.port, **kwargs) as connection: - response1 = await http_request(connection, config.path) - response2 = await http_request(connection, config.path) - - if response1 and response2: - config.result |= Result.D - ===========changed ref 3=========== # module: examples.interop + def http3_request(connection, authority, path): + reader, writer = await connection.create_stream() + stream_id = writer.get_extra_info("stream_id") + + http = H3Connection(connection._connection) + http.send_headers( + stream_id=stream_id, + headers=[ + (b":method", b"GET"), + (b":scheme", b"https"), + (b":authority", authority.encode("utf8")), + (b":path", path.encode("utf8")), + ], + ) + http.send_data(stream_id=stream_id, data=b"", end_stream=True) + + return await reader.read() + ===========changed ref 4=========== # module: examples.interop def test_session_resumption(config, **kwargs): saved_ticket = None def session_ticket_handler(ticket): nonlocal saved_ticket saved_ticket = ticket # connect a first time, receive a ticket async with connect( config.host, config.port, session_ticket_handler=session_ticket_handler, **kwargs ) as connection: await connection.ping() # connect a second time, with the ticket if saved_ticket is not None: async with connect( config.host, config.port, session_ticket=saved_ticket, **kwargs ) as connection: await connection.ping() + # check session was resumed - # check session was resumed + if connection._connection.tls.session_resumed: - if connection._connection.tls.session_resumed: + config.result |= Result.R - config.result |= Result.R + # check early data was accepted - # check early data was accepted + if connection._connection.tls.early_data_accepted: - if connection._connection.tls.early_data_accepted: + config.result |= Result.Z - config.result |= Result.Z ===========changed ref 5=========== # module: examples.interop class Result(Flag): + V = 0x0001 - V = 1 + H = 0x0002 - H = 2 + D = 0x0004 - D = 4 + C = 0x0008 - C = 8 + R = 0x0010 - R = 16 + Z = 0x0020 - Z = 32 + S = 0x0040 - S = 64 - # M = 128 - # B = 256 - U = 512 - # 3 = 1024 + M = 0x0080 + B = 0x0100 + U = 0x0200 + P = 0x0400 - P = 2048 + E = 0x0800 + T = 0x1000 + three = 0x2000 + d = 0x4000 + p = 0x8000 ===========changed ref 6=========== # module: examples.interop CONFIGS = [ Config("aioquic", "quic.aiortc.org", 4433, 4434, "/"), Config("ats", "quic.ogre.com", 4433, 4434, "/"), Config("f5", "f5quic.com", 4433, 4433, "/"), Config("gquic", "quic.rocks", 4433, 4433, "/"), Config("lsquic", "http3-test.litespeedtech.com", 4433, 4434, None), Config("mvfst", "fb.mvfst.net", 4433, 4434, "/"), + Config("ngtcp2", "nghttp2.org", 4433, 4434, "/"), - Config("ngtcp2", "nghttp2.org", 4433, 4434, None), Config("ngx_quic", "cloudflare-quic.com", 443, 443, None), Config("pandora", "pandora.cm.in.tum.de", 4433, 4434, "/"), Config("picoquic", "test.privateoctopus.com", 4433, 4434, "/"), Config("quant", "quant.eggert.org", 4433, 4434, "/"), Config("quic-go", "quic.seemann.io", 443, 443, "/"), Config("quiche", "quic.tech", 4433, 4433, "/"), Config("quicker", "quicker.edm.uhasselt.be", 4433, None, "/"), Config("quicly", "kazuhooku.com", 4433, 4434, "/"), Config("quinn", "ralith.com", 4433, 4434, "/"), Config("winquic", "quic.westus.cloudapp.azure.com", 4433, 4434, "/"), ]
examples.interop/run
Modified
aiortc~aioquic
975975ab854a8e2e0c7d2622377a844aa18ea79f
[interop] rework interop script
<0>:<del> configs = list(filter(lambda x: not only or x.name == only, CONFIGS)) <1>:<del> <3>:<add> for test_name, test_func in tests: <del> for test_name, test_func in filter( <4>:<del> lambda x: x[0].startswith("test_"), globals().items() <5>:<del> ):
# module: examples.interop + def run(configs, tests, **kwargs) -> None: - def run(only=None, **kwargs) -> None: <0> configs = list(filter(lambda x: not only or x.name == only, CONFIGS)) <1> <2> for config in configs: <3> for test_name, test_func in filter( <4> lambda x: x[0].startswith("test_"), globals().items() <5> ): <6> print("\n=== %s %s ===\n" % (config.name, test_name)) <7> try: <8> await asyncio.wait_for(test_func(config, **kwargs), timeout=5) <9> except Exception as exc: <10> print(exc) <11> print("") <12> print_result(config) <13> <14> # print summary <15> if len(configs) > 1: <16> print("SUMMARY") <17> for config in configs: <18> print_result(config) <19>
===========unchanged ref 0=========== at: aioquic.asyncio.client connect(*args, **kwds) connect(host: str, port: int, *, alpn_protocols: Optional[List[str]]=None, idle_timeout: Optional[float]=None, protocol_version: Optional[int]=None, secrets_log_file: Optional[TextIO]=None, session_ticket: Optional[SessionTicket]=None, session_ticket_handler: Optional[SessionTicketHandler]=None, stream_handler: Optional[QuicStreamHandler]=None) -> AsyncGenerator[QuicConnectionProtocol, None] at: aioquic.asyncio.protocol.QuicConnectionProtocol request_key_update() -> None ping() -> None at: aioquic.asyncio.protocol.QuicConnectionProtocol.__init__ self._connection = connection at: aioquic.quic.connection.QuicConnection._initialize self.tls = tls.Context(is_client=self._is_client, logger=self._logger) at: aioquic.tls.Context.__init__ self.early_data_accepted = False at: aioquic.tls.Context._client_handle_encrypted_extensions self.early_data_accepted = encrypted_extensions.early_data at: aioquic.tls.Context._server_handle_hello self.early_data_accepted = True at: examples.interop Result() ===========changed ref 0=========== # module: examples.interop class Result(Flag): + V = 0x0001 - V = 1 + H = 0x0002 - H = 2 + D = 0x0004 - D = 4 + C = 0x0008 - C = 8 + R = 0x0010 - R = 16 + Z = 0x0020 - Z = 32 + S = 0x0040 - S = 64 - # M = 128 - # B = 256 - U = 512 - # 3 = 1024 + M = 0x0080 + B = 0x0100 + U = 0x0200 + P = 0x0400 - P = 2048 + E = 0x0800 + T = 0x1000 + three = 0x2000 + d = 0x4000 + p = 0x8000 ===========changed ref 1=========== # module: examples.interop def print_result(config: Config) -> None: + result = str(config.result).replace("three", "3") + result = result[0:7] + " " + result[7:13] + " " + result[13:] + print("%s%s%s" % (config.name, " " * (20 - len(config.name)), result)) - print("%s%s%s" % (config.name, " " * (20 - len(config.name)), config.result)) ===========changed ref 2=========== # module: examples.interop + def test_http_0(config, **kwargs): + if config.path is None: + return + + kwargs["alpn_protocols"] = ["hq-22"] + async with connect(config.host, config.port, **kwargs) as connection: + response = await http_request(connection, config.path) + if response: + config.result |= Result.D + ===========changed ref 3=========== # module: examples.interop + def test_http_3(config, **kwargs): + if config.path is None: + return + + kwargs["alpn_protocols"] = ["h3-22"] + async with connect(config.host, config.port, **kwargs) as connection: + response = await http3_request(connection, config.host, config.path) + if response: + config.result |= Result.D + config.result |= Result.three + ===========changed ref 4=========== # module: examples.interop - def test_data_transfer(config, **kwargs): - if config.path is None: - return - - async with connect(config.host, config.port, **kwargs) as connection: - response1 = await http_request(connection, config.path) - response2 = await http_request(connection, config.path) - - if response1 and response2: - config.result |= Result.D - ===========changed ref 5=========== # module: examples.interop + def http3_request(connection, authority, path): + reader, writer = await connection.create_stream() + stream_id = writer.get_extra_info("stream_id") + + http = H3Connection(connection._connection) + http.send_headers( + stream_id=stream_id, + headers=[ + (b":method", b"GET"), + (b":scheme", b"https"), + (b":authority", authority.encode("utf8")), + (b":path", path.encode("utf8")), + ], + ) + http.send_data(stream_id=stream_id, data=b"", end_stream=True) + + return await reader.read() + ===========changed ref 6=========== # module: examples.interop def test_session_resumption(config, **kwargs): saved_ticket = None def session_ticket_handler(ticket): nonlocal saved_ticket saved_ticket = ticket # connect a first time, receive a ticket async with connect( config.host, config.port, session_ticket_handler=session_ticket_handler, **kwargs ) as connection: await connection.ping() # connect a second time, with the ticket if saved_ticket is not None: async with connect( config.host, config.port, session_ticket=saved_ticket, **kwargs ) as connection: await connection.ping() + # check session was resumed - # check session was resumed + if connection._connection.tls.session_resumed: - if connection._connection.tls.session_resumed: + config.result |= Result.R - config.result |= Result.R + # check early data was accepted - # check early data was accepted + if connection._connection.tls.early_data_accepted: - if connection._connection.tls.early_data_accepted: + config.result |= Result.Z - config.result |= Result.Z
aioquic.h3.connection/H3Connection.__init__
Modified
aiortc~aioquic
71523435ae58fde0a6d8029c0e0746b451683c02
[http3] add an H3Stream class
<7>:<del> self._stream_blocked: Set[int] = set() <8>:<del> self._stream_buffers: Dict[int, bytes] = {} <9>:<del> self._stream_ended: Set[int] = set() <10>:<add> self._stream: Dict[int, H3Stream] = {} <del> self._stream_types: Dict[int, int] = {}
# module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): <0> self._max_table_capacity = 0x100 <1> self._blocked_streams = 0x10 <2> <3> self._is_client = quic.configuration.is_client <4> self._quic = quic <5> self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) <6> self._encoder = Encoder() <7> self._stream_blocked: Set[int] = set() <8> self._stream_buffers: Dict[int, bytes] = {} <9> self._stream_ended: Set[int] = set() <10> self._stream_types: Dict[int, int] = {} <11> <12> self._local_control_stream_id: Optional[int] = None <13> self._local_decoder_stream_id: Optional[int] = None <14> self._local_encoder_stream_id: Optional[int] = None <15> <16> self._peer_control_stream_id: Optional[int] = None <17> self._peer_decoder_stream_id: Optional[int] = None <18> self._peer_encoder_stream_id: Optional[int] = None <19> <20> self._init_connection() <21>
===========unchanged ref 0=========== at: aioquic.h3.connection H3Stream() at: aioquic.h3.connection.H3Connection._init_connection self._local_control_stream_id = self._create_uni_stream(StreamType.CONTROL) self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) self._local_decoder_stream_id = self._create_uni_stream( StreamType.QPACK_DECODER ) at: aioquic.quic.configuration.QuicConfiguration alpn_protocols: Optional[List[str]] = None certificate: Any = None idle_timeout: float = 60.0 is_client: bool = True private_key: Any = None secrets_log_file: TextIO = None server_name: Optional[str] = None session_ticket: Optional[SessionTicket] = None supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection QuicConnection(*, configuration: QuicConfiguration, original_connection_id: Optional[bytes]=None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher]=None, session_ticket_handler: Optional[tls.SessionTicketHandler]=None) at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: aioquic.h3.connection + class H3Stream: + def __init__(self): + self.blocked = False + self.buffer = b"" + self.ended = False + self.stream_type = None +
aioquic.h3.connection/H3Connection._receive_stream_data
Modified
aiortc~aioquic
71523435ae58fde0a6d8029c0e0746b451683c02
[http3] add an H3Stream class
<2>:<add> if stream_id not in self._stream: <del> if stream_id in self._stream_buffers: <3>:<del> self._stream_buffers[stream_id] += data <4>:<del> else: <5>:<add> self._stream[stream_id] = H3Stream() <del> self._stream_buffers[stream_id] = data <6>:<add> stream = self._stream[stream_id] <add> stream.buffer += data <7>:<add> stream.ended = True <add> if stream.blocked: <del> self._stream_ended.add(stream_id) <8>:<del> if stream_id in self._stream_blocked: <11>:<add> buf = Buffer(data=stream.buffer) <del> buf = Buffer(data=self._stream_buffers[stream_id]) <23>:<del> if ( <24>:<del> stream_is_unidirectional(stream_id) <25>:<del> and stream_id not in self._stream_types <26>:<del> ): <27>:<add> if stream_is_unidirectional(stream_id) and stream.stream_type is None: <28>:<add> stream.stream_type = buf.pull_uint_var() <del> stream_type = buf.pull_uint_var() <33>:<add> if stream.stream_type == StreamType.CONTROL: <del> if stream_type == StreamType.CONTROL: <36>:<add> elif stream.stream_type == StreamType.QPACK_DECODER: <del> elif stream_type == StreamType.QPACK_DECODER: <39>:<add> elif stream.stream_type == StreamType.QPACK_ENCODER: <del> elif stream_type == StreamType.QPACK_ENCODER:
# module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: <0> http_events: List[Event] = [] <1> <2> if stream_id in self._stream_buffers: <3> self._stream_buffers[stream_id] += data <4> else: <5> self._stream_buffers[stream_id] = data <6> if stream_ended: <7> self._stream_ended.add(stream_id) <8> if stream_id in self._stream_blocked: <9> return http_events <10> <11> buf = Buffer(data=self._stream_buffers[stream_id]) <12> consumed = 0 <13> unblocked_streams: Set[int] = set() <14> <15> # some peers (e.g. f5) end the stream with no data <16> if stream_ended and buf.eof() and (stream_id % 4 == 0): <17> http_events.append( <18> DataReceived(data=b"", stream_id=stream_id, stream_ended=True) <19> ) <20> <21> while not buf.eof(): <22> # fetch stream type for unidirectional streams <23> if ( <24> stream_is_unidirectional(stream_id) <25> and stream_id not in self._stream_types <26> ): <27> try: <28> stream_type = buf.pull_uint_var() <29> except BufferReadError: <30> break <31> consumed = buf.tell() <32> <33> if stream_type == StreamType.CONTROL: <34> assert self._peer_control_stream_id is None <35> self._peer_control_stream_id = stream_id <36> elif stream_type == StreamType.QPACK_DECODER: <37> assert self._peer_decoder_stream_id is None <38> self._peer_decoder_stream_id = stream_id <39> elif stream_type == StreamType.QPACK_ENCODER: <40> assert self._peer_</s>
===========below chunk 0=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 self._peer_encoder_stream_id = stream_id self._stream_types[stream_id] = stream_type if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: # fetch next frame try: frame_type = buf.pull_uint_var() frame_length = buf.pull_uint_var() frame_data = buf.pull_bytes(frame_length) except BufferReadError: break consumed = buf.tell() if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type == FrameType.HEADERS: try: decoder, headers = self._decoder.feed_header( stream_id, frame_data ) except StreamBlocked: self._stream_blocked.add(stream_id) break self._quic.send_stream_data( self._local_decoder_stream_id, decoder ) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif stream_id == self._peer_control_stream_id: # unidirectional control stream if frame_type == FrameType.SETTINGS: settings = parse_settings(frame_data) encoder = self._encoder.apply_settings( max_table_capacity=settings.get</s> ===========below chunk 1=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 2 <s>_settings(frame_data) encoder = self._encoder.apply_settings( max_table_capacity=settings.get( Setting.QPACK_MAX_TABLE_CAPACITY, 0 ), blocked_streams=settings.get( Setting.QPACK_BLOCKED_STREAMS, 0 ), ) self._quic.send_stream_data( self._local_encoder_stream_id, encoder ) else: # fetch unframed data data = buf.pull_bytes(buf.capacity - buf.tell()) consumed = buf.tell() if stream_id == self._peer_decoder_stream_id: self._encoder.feed_decoder(data) elif stream_id == self._peer_encoder_stream_id: unblocked_streams.update(self._decoder.feed_encoder(data)) # remove processed data from buffer self._stream_buffers[stream_id] = self._stream_buffers[stream_id][consumed:] # process unblocked streams for stream_id in unblocked_streams: decoder, headers = self._decoder.resume_header(stream_id) self._stream_blocked.discard(stream_id) cls = ResponseReceived if self._is_client else RequestReceived http_events.append( cls( headers=headers, stream_id=stream_id, stream_ended=stream_id in self._stream_ended and not self._stream_buffers[stream_id], ) ) http_events.extend( self._receive_stream_data( stream_id, b"", stream_id in self._stream_ended ===========unchanged ref 0=========== at: aioquic._buffer BufferReadError(*args: object) Buffer(capacity: Optional[int]=0, data: Optional[bytes]=None) at: aioquic._buffer.Buffer eof() -> bool tell() -> int pull_bytes(length: int) -> bytes pull_uint_var() -> int at: aioquic.h3.connection FrameType(x: Union[str, bytes, bytearray], base: int) FrameType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) Setting(x: Union[str, bytes, bytearray], base: int) Setting(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, SupportsInt, _SupportsIndex, _SupportsTrunc]=...) StreamType(x: Union[str, bytes, bytearray], base: int) parse_settings(data: bytes) -> Dict[int, int] H3Stream() at: aioquic.h3.connection.H3Connection _create_uni_stream(stream_type: int) -> int at: aioquic.h3.connection.H3Connection.__init__ self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() self._stream: Dict[int, H3Stream] = {} self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None ===========unchanged ref 1=========== at: aioquic.h3.connection.H3Connection._init_connection self._local_encoder_stream_id = self._create_uni_stream( StreamType.QPACK_ENCODER ) at: aioquic.h3.connection.H3Stream.__init__ self.blocked = False self.buffer = b"" self.ended = False self.stream_type = None at: aioquic.h3.events Event() DataReceived(data: bytes, stream_id: int, stream_ended: bool) RequestReceived(headers: Headers, stream_id: int, stream_ended: bool) ResponseReceived(headers: Headers, stream_id: int, stream_ended: bool) at: aioquic.h3.events.DataReceived data: bytes stream_id: int stream_ended: bool at: aioquic.h3.events.RequestReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.h3.events.ResponseReceived headers: Headers stream_id: int stream_ended: bool at: aioquic.quic.connection stream_is_unidirectional(stream_id: int) -> bool at: aioquic.quic.connection.QuicConnection send_stream_data(stream_id: int, data: bytes, end_stream: bool=False) -> None at: typing List = _alias(list, 1, inst=False, name='List') Set = _alias(set, 1, inst=False, name='Set') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co]
tests.test_h3/H3ConnectionTest.test_uni_stream_type
Modified
aiortc~aioquic
71523435ae58fde0a6d8029c0e0746b451683c02
[http3] add an H3Stream class
<11>:<add> self.assertEqual(list(h3_server._stream.keys()), [2]) <add> self.assertEqual(h3_server._stream[2].buffer, b"") <del> self.assertEqual(h3_server._stream_buffers, {2: b""}) <12>:<add> self.assertEqual(h3_server._stream[2].stream_type, 9) <del> self.assertEqual(h3_server._stream_types, {2: 9}) <20>:<add> self.assertEqual(list(h3_server._stream.keys()), [2, 6]) <add> self.assertEqual(h3_server._stream[2].buffer, b"") <del> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b"\x40"}) <21>:<add> self.assertEqual(h3_server._stream[2].stream_type, 9) <del> self.assertEqual(h3_server._stream_types, {2: 9}) <22>:<add> self.assertEqual(h3_server._stream[6].buffer, b"\x40") <add> self.assertEqual(h3_server._stream[6].stream_type, None) <25>:<add> self.assertEqual(list(h3_server._stream.keys()), [2, 6]) <add> self.assertEqual(h3_server._stream[2].
# module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): <0> with client_and_server( <1> client_options={"alpn_protocols": ["h3-22"]}, <2> server_options={"alpn_protocols": ["h3-22"]}, <3> ) as (quic_client, quic_server): <4> h3_server = H3Connection(quic_server) <5> <6> # unknown stream type 9 <7> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <8> self.assertEqual(stream_id, 2) <9> quic_client.send_stream_data(stream_id, b"\x09") <10> self.assertEqual(h3_transfer(quic_client, h3_server), []) <11> self.assertEqual(h3_server._stream_buffers, {2: b""}) <12> self.assertEqual(h3_server._stream_types, {2: 9}) <13> <14> # unknown stream type 64, one byte at a time <15> stream_id = quic_client.get_next_available_stream_id(is_unidirectional=True) <16> self.assertEqual(stream_id, 6) <17> <18> quic_client.send_stream_data(stream_id, b"\x40") <19> self.assertEqual(h3_transfer(quic_client, h3_server), []) <20> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b"\x40"}) <21> self.assertEqual(h3_server._stream_types, {2: 9}) <22> <23> quic_client.send_stream_data(stream_id, b"\x40") <24> self.assertEqual(h3_transfer(quic_client, h3_server), []) <25> self.assertEqual(h3_server._stream_buffers, {2: b"", 6: b""}) <26> self.assertEqual</s>
===========below chunk 0=========== # module: tests.test_h3 class H3ConnectionTest(TestCase): def test_uni_stream_type(self): # offset: 1 ===========unchanged ref 0=========== at: aioquic.h3.connection H3Connection(quic: QuicConnection) at: aioquic.h3.connection.H3Connection.__init__ self._stream: Dict[int, H3Stream] = {} at: aioquic.h3.connection.H3Stream.__init__ self.buffer = b"" self.stream_type = None at: tests.test_connection client_and_server(client_options={}, client_patch=lambda x: None, server_options={}, server_patch=lambda x: None, transport_options={}) at: tests.test_h3 h3_transfer(quic_sender, h3_receiver) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: aioquic.h3.connection + class H3Stream: + def __init__(self): + self.blocked = False + self.buffer = b"" + self.ended = False + self.stream_type = None + ===========changed ref 1=========== # module: aioquic.h3.connection class H3Connection: def __init__(self, quic: QuicConnection): self._max_table_capacity = 0x100 self._blocked_streams = 0x10 self._is_client = quic.configuration.is_client self._quic = quic self._decoder = Decoder(self._max_table_capacity, self._blocked_streams) self._encoder = Encoder() - self._stream_blocked: Set[int] = set() - self._stream_buffers: Dict[int, bytes] = {} - self._stream_ended: Set[int] = set() + self._stream: Dict[int, H3Stream] = {} - self._stream_types: Dict[int, int] = {} self._local_control_stream_id: Optional[int] = None self._local_decoder_stream_id: Optional[int] = None self._local_encoder_stream_id: Optional[int] = None self._peer_control_stream_id: Optional[int] = None self._peer_decoder_stream_id: Optional[int] = None self._peer_encoder_stream_id: Optional[int] = None self._init_connection() ===========changed ref 2=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: http_events: List[Event] = [] + if stream_id not in self._stream: - if stream_id in self._stream_buffers: - self._stream_buffers[stream_id] += data - else: + self._stream[stream_id] = H3Stream() - self._stream_buffers[stream_id] = data + stream = self._stream[stream_id] + stream.buffer += data if stream_ended: + stream.ended = True + if stream.blocked: - self._stream_ended.add(stream_id) - if stream_id in self._stream_blocked: return http_events + buf = Buffer(data=stream.buffer) - buf = Buffer(data=self._stream_buffers[stream_id]) consumed = 0 unblocked_streams: Set[int] = set() # some peers (e.g. f5) end the stream with no data if stream_ended and buf.eof() and (stream_id % 4 == 0): http_events.append( DataReceived(data=b"", stream_id=stream_id, stream_ended=True) ) while not buf.eof(): # fetch stream type for unidirectional streams - if ( - stream_is_unidirectional(stream_id) - and stream_id not in self._stream_types - ): + if stream_is_unidirectional(stream_id) and stream.stream_type is None: try: + stream.stream_type = buf.pull_uint_var() - stream_type = buf.pull_uint_var() except BufferReadError: break consumed = buf.tell() + if stream.stream_type == StreamType.CONTROL: - if</s> ===========changed ref 3=========== # module: aioquic.h3.connection class H3Connection: def _receive_stream_data( self, stream_id: int, data: bytes, stream_ended: bool ) -> List[Event]: # offset: 1 <s> break consumed = buf.tell() + if stream.stream_type == StreamType.CONTROL: - if stream_type == StreamType.CONTROL: assert self._peer_control_stream_id is None self._peer_control_stream_id = stream_id + elif stream.stream_type == StreamType.QPACK_DECODER: - elif stream_type == StreamType.QPACK_DECODER: assert self._peer_decoder_stream_id is None self._peer_decoder_stream_id = stream_id + elif stream.stream_type == StreamType.QPACK_ENCODER: - elif stream_type == StreamType.QPACK_ENCODER: assert self._peer_encoder_stream_id is None self._peer_encoder_stream_id = stream_id - self._stream_types[stream_id] = stream_type if (stream_id % 4 == 0) or stream_id == self._peer_control_stream_id: # fetch next frame try: frame_type = buf.pull_uint_var() frame_length = buf.pull_uint_var() frame_data = buf.pull_bytes(frame_length) except BufferReadError: break consumed = buf.tell() if (stream_id % 4) == 0: # client-initiated bidirectional streams carry requests and responses if frame_type == FrameType.DATA: http_events.append( DataReceived( data=frame_data, stream_id=stream_id, stream_ended=stream_ended and buf.eof(), ) ) elif frame_type ==</s>
aioquic.h3.connection/H3Stream.__init__
Modified
aiortc~aioquic
ed5190a3f3df75433a902c776c0bcfe01f97e8c5
[http3] fix mypy errors
<3>:<add> self.stream_type: Optional[int] = None <del> self.stream_type = None
# module: aioquic.h3.connection class H3Stream: + def __init__(self) -> None: - def __init__(self): <0> self.blocked = False <1> self.buffer = b"" <2> self.ended = False <3> self.stream_type = None <4>
aioquic.quic.recovery/QuicPacketRecovery.__init__
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
<6>:<add> self._quic_logger = quic_logger <21>:<add> self._ssthresh: Optional[int] = None <del> self._ssthresh = math.inf
# module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( + self, + is_client_without_1rtt: bool, + send_probe: Callable[[], None], + quic_logger: Optional[QuicLogger] = None, - self, is_client_without_1rtt: bool, send_probe: Callable[[], None] ) -> None: <0> self.ack_delay_exponent = 3 <1> self.is_client_without_1rtt = is_client_without_1rtt <2> self.max_ack_delay = 25 # ms <3> self.spaces: List[QuicPacketSpace] = [] <4> <5> # callbacks <6> self._send_probe = send_probe <7> <8> # loss detection <9> self._pto_count = 0 <10> self._rtt_initialized = False <11> self._rtt_latest = 0.0 <12> self._rtt_min = math.inf <13> self._rtt_smoothed = 0.0 <14> self._rtt_variance = 0.0 <15> self._time_of_last_sent_ack_eliciting_packet = 0.0 <16> <17> # congestion control <18> self.bytes_in_flight = 0 <19> self.congestion_window = K_INITIAL_WINDOW <20> self._congestion_recovery_start_time = 0.0 <21> self._ssthresh = math.inf <22>
===========unchanged ref 0=========== at: aioquic.quic.logger QuicLogger() at: aioquic.quic.recovery QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery.on_ack_received self._rtt_latest = max(latest_rtt, 0.001) self._rtt_latest -= ack_delay self._rtt_min = self._rtt_latest self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = latest_rtt self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self._pto_count = 0 at: aioquic.quic.recovery.QuicPacketRecovery.on_loss_detection_timeout self._pto_count += 1 at: aioquic.quic.recovery.QuicPacketRecovery.on_packet_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.logger + class QuicLogger: + """ + A QUIC event logger. + + Events are logged in the format defined by qlog draft-00. + + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00 + """ + ===========changed ref 1=========== + # module: aioquic.quic.logger + + ===========changed ref 2=========== + # module: aioquic.quic.logger + class QuicLogger: + def log_event(self, *, category: str, event: str, data: Dict) -> None: + self._events.append((time.time(), category, event, data)) + ===========changed ref 3=========== + # module: aioquic.quic.logger + class QuicLogger: + def __init__(self) -> None: + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque() + ===========changed ref 4=========== + # module: aioquic.quic.logger + class QuicLogger: + def packet_type(self, packet_type: int) -> str: + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, "1RTT") + ===========changed ref 5=========== + # module: aioquic.quic.logger + PACKET_TYPE_NAMES = { + PACKET_TYPE_INITIAL: "initial", + PACKET_TYPE_HANDSHAKE: "handshake", + PACKET_TYPE_ZERO_RTT: "0RTT", + PACKET_TYPE_ONE_RTT: "1RTT", + PACKET_TYPE_RETRY: "retry", + } + ===========changed ref 6=========== + # module: aioquic.quic.logger + class QuicLogger: + def to_dict(self) -> Dict[str, Any]: + """ + Return the trace as a dictionary which can be written as JSON. + """ + traces = [] + if self._events: + reference_time = self._events[0][0] + trace = { + "common_fields": {"reference_time": "%d" % (reference_time * 1000)}, + "event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"], + "events": list( + map( + lambda event: ( + "%d" % ((event[0] - reference_time) * 1000), + event[1].upper(), # draft-00 + event[2].upper(), # draft-00 + event[3], + ), + self._events, + ) + ), + } + traces.append(trace) + + return {"qlog_version": "draft-00", "traces": traces} +
aioquic.quic.recovery/QuicPacketRecovery.on_ack_received
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: <0> """ <1> Update metrics as the result of an ACK being received. <2> """ <3> is_ack_eliciting = False <4> largest_acked = ack_rangeset.bounds().stop - 1 <5> largest_newly_acked = None <6> largest_sent_time = None <7> <8> if largest_acked > space.largest_acked_packet: <9> space.largest_acked_packet = largest_acked <10> <11> for packet_number in sorted(space.sent_packets.keys()): <12> if packet_number > largest_acked: <13> break <14> if packet_number in ack_rangeset: <15> # remove packet and update counters <16> packet = space.sent_packets.pop(packet_number) <17> if packet.is_ack_eliciting: <18> is_ack_eliciting = True <19> space.ack_eliciting_in_flight -= 1 <20> if packet.in_flight: <21> self.on_packet_acked(packet) <22> largest_newly_acked = packet_number <23> largest_sent_time = packet.sent_time <24> <25> # trigger callbacks <26> for handler, args in packet.delivery_handlers: <27> handler(QuicDeliveryState.ACKED, *args) <28> <29> # nothing to do if there are no newly acked packets <30> if largest_newly_acked is None: <31> return <32> <33> if largest_acked == largest_newly_acked and is_ack_eliciting: <34> latest_rtt = now - largest_sent_time <35> <36> # decode ACK delay into seconds <37> ack_delay = max( <38> (ack_delay_encoded << self.ack_delay_</s>
===========below chunk 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: # offset: 1 self.max_ack_delay / 1000, ) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) self.detect_loss(space, now=now) self._pto_count = 0 ===========unchanged ref 0=========== at: aioquic.quic.packet_builder QuicDeliveryState() at: aioquic.quic.packet_builder.QuicSentPacket epoch: Epoch in_flight: bool is_ack_eliciting: bool is_crypto_packet: bool packet_number: int packet_type: int sent_time: Optional[float] = None sent_bytes: int = 0 delivery_handlers: List[Tuple[QuicDeliveryHandler, Any]] = field( default_factory=list ) at: aioquic.quic.rangeset RangeSet(ranges: Iterable[range]=[]) at: aioquic.quic.rangeset.RangeSet bounds() -> range at: aioquic.quic.recovery K_GRANULARITY = 0.001 # seconds QuicPacketSpace() at: aioquic.quic.recovery.QuicPacketRecovery on_packet_acked(packet: QuicSentPacket) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.ack_delay_exponent = 3 self.max_ack_delay = 25 # ms self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 at: aioquic.quic.recovery.QuicPacketSpace.__init__ self.ack_eliciting_in_flight = 0 self.largest_acked_packet = 0 self.sent_packets: Dict[int, QuicSentPacket] = {} at: typing.MutableMapping pop(key: _KT) -> _VT pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( + self, + is_client_without_1rtt: bool, + send_probe: Callable[[], None], + quic_logger: Optional[QuicLogger] = None, - self, is_client_without_1rtt: bool, send_probe: Callable[[], None] ) -> None: self.ack_delay_exponent = 3 self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks + self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 + self._ssthresh: Optional[int] = None - self._ssthresh = math.inf ===========changed ref 1=========== + # module: aioquic.quic.logger + + ===========changed ref 2=========== + # module: aioquic.quic.logger + class QuicLogger: + def log_event(self, *, category: str, event: str, data: Dict) -> None: + self._events.append((time.time(), category, event, data)) + ===========changed ref 3=========== + # module: aioquic.quic.logger + class QuicLogger: + def __init__(self) -> None: + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque() + ===========changed ref 4=========== + # module: aioquic.quic.logger + class QuicLogger: + def packet_type(self, packet_type: int) -> str: + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, "1RTT") + ===========changed ref 5=========== + # module: aioquic.quic.logger + class QuicLogger: + """ + A QUIC event logger. + + Events are logged in the format defined by qlog draft-00. + + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00 + """ + ===========changed ref 6=========== + # module: aioquic.quic.logger + PACKET_TYPE_NAMES = { + PACKET_TYPE_INITIAL: "initial", + PACKET_TYPE_HANDSHAKE: "handshake", + PACKET_TYPE_ZERO_RTT: "0RTT", + PACKET_TYPE_ONE_RTT: "1RTT", + PACKET_TYPE_RETRY: "retry", + } + ===========changed ref 7=========== + # module: aioquic.quic.logger + class QuicLogger: + def to_dict(self) -> Dict[str, Any]: + """ + Return the trace as a dictionary which can be written as JSON. + """ + traces = [] + if self._events: + reference_time = self._events[0][0] + trace = { + "common_fields": {"reference_time": "%d" % (reference_time * 1000)}, + "event_fields": ["relative_time", "CATEGORY", "EVENT_TYPE", "DATA"], + "events": list( + map( + lambda event: ( + "%d" % ((event[0] - reference_time) * 1000), + event[1].upper(), # draft-00 + event[2].upper(), # draft-00 + event[3], + ), + self._events, + ) + ), + } + traces.append(trace) + + return {"qlog_version": "draft-00", "traces": traces} +
aioquic.quic.recovery/QuicPacketRecovery.on_packet_acked
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
<6>:<add> if self._ssthresh is None or self.congestion_window < self._ssthresh: <del> if self.congestion_window < self._ssthresh:
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: <0> self.bytes_in_flight -= packet.sent_bytes <1> <2> # don't increase window in congestion recovery <3> if packet.sent_time <= self._congestion_recovery_start_time: <4> return <5> <6> if self.congestion_window < self._ssthresh: <7> # slow start <8> self.congestion_window += packet.sent_bytes <9> else: <10> # congestion avoidance <11> self.congestion_window += ( <12> K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window <13> ) <14>
===========unchanged ref 0=========== at: aioquic.quic.recovery.QuicPacketRecovery detect_loss(space: QuicPacketSpace, now: float) -> None get_earliest_loss_time() -> Optional[QuicPacketSpace] on_packet_lost(packet: QuicSentPacket, space: QuicPacketSpace) -> None at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.spaces: List[QuicPacketSpace] = [] 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 __init__( + self, + is_client_without_1rtt: bool, + send_probe: Callable[[], None], + quic_logger: Optional[QuicLogger] = None, - self, is_client_without_1rtt: bool, send_probe: Callable[[], None] ) -> None: self.ack_delay_exponent = 3 self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks + self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 + self._ssthresh: Optional[int] = None - self._ssthresh = math.inf ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # decode ACK delay into seconds ack_delay = max( (ack_delay_encoded << self.ack_delay_exponent) / 1000000, self.max_ack_delay / 1000, ) # update RTT estimate, which cannot be < 1 ms self._</s> ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: # offset: 1 <s>max_ack_delay / 1000, ) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) + if self._quic_logger is not None: + self._quic_logger.log_event( + category="recovery", + event="metric_update", + data={ + "latest_rtt": int(self._rtt_latest * 1000), + "min_rtt": int(self._rtt_min * 1000), + "smoothed_rtt": int(self._rtt_smoothed * 1000), + "rtt_variance": int(self._rtt_variance * 1000), + }, + ) + self.detect_loss(space, now ===========changed ref 3=========== + # module: aioquic.quic.logger + + ===========changed ref 4=========== + # module: aioquic.quic.logger + class QuicLogger: + def log_event(self, *, category: str, event: str, data: Dict) -> None: + self._events.append((time.time(), category, event, data)) + ===========changed ref 5=========== + # module: aioquic.quic.logger + class QuicLogger: + def __init__(self) -> None: + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque() + ===========changed ref 6=========== + # module: aioquic.quic.logger + class QuicLogger: + def packet_type(self, packet_type: int) -> str: + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, "1RTT") + ===========changed ref 7=========== + # module: aioquic.quic.logger + class QuicLogger: + """ + A QUIC event logger. + + Events are logged in the format defined by qlog draft-00. + + See: https://tools.ietf.org/html/draft-marx-qlog-main-schema-00 + """ + ===========changed ref 8=========== + # module: aioquic.quic.logger + PACKET_TYPE_NAMES = { + PACKET_TYPE_INITIAL: "initial", + PACKET_TYPE_HANDSHAKE: "handshake", + PACKET_TYPE_ZERO_RTT: "0RTT", + PACKET_TYPE_ONE_RTT: "1RTT", + PACKET_TYPE_RETRY: "retry", + } +
aioquic.quic.recovery/QuicPacketRecovery.on_packet_lost
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
<7>:<add> if self._quic_logger is not None: <add> self._quic_logger.log_event( <add> category="recovery", <add> event="packet_lost", <add> data={ <add> "type": self._quic_logger.packet_type(packet.packet_type), <add> "packet_number": packet.packet_number, <add> }, <add> ) <add> self._log_metric_update() <add>
# module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_lost(self, packet: QuicSentPacket, space: QuicPacketSpace) -> None: <0> del space.sent_packets[packet.packet_number] <1> <2> if packet.is_ack_eliciting: <3> space.ack_eliciting_in_flight -= 1 <4> if packet.in_flight: <5> self.bytes_in_flight -= packet.sent_bytes <6> <7> # trigger callbacks <8> for handler, args in packet.delivery_handlers: <9> handler(QuicDeliveryState.LOST, *args) <10>
===========unchanged ref 0=========== at: aioquic.quic.packet_builder.QuicSentPacket sent_time: Optional[float] = None sent_bytes: int = 0 at: aioquic.quic.recovery.QuicPacketRecovery.__init__ self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 self._ssthresh: Optional[int] = None at: aioquic.quic.recovery.QuicPacketRecovery.on_packets_lost self._congestion_recovery_start_time = now self.congestion_window = max( int(self.congestion_window * K_LOSS_REDUCTION_FACTOR), K_MINIMUM_WINDOW ) self._ssthresh = self.congestion_window ===========changed ref 0=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_packet_acked(self, packet: QuicSentPacket) -> None: self.bytes_in_flight -= packet.sent_bytes # don't increase window in congestion recovery if packet.sent_time <= self._congestion_recovery_start_time: return + if self._ssthresh is None or self.congestion_window < self._ssthresh: - if self.congestion_window < self._ssthresh: # slow start self.congestion_window += packet.sent_bytes else: # congestion avoidance self.congestion_window += ( K_MAX_DATAGRAM_SIZE * packet.sent_bytes // self.congestion_window ) ===========changed ref 1=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def __init__( + self, + is_client_without_1rtt: bool, + send_probe: Callable[[], None], + quic_logger: Optional[QuicLogger] = None, - self, is_client_without_1rtt: bool, send_probe: Callable[[], None] ) -> None: self.ack_delay_exponent = 3 self.is_client_without_1rtt = is_client_without_1rtt self.max_ack_delay = 25 # ms self.spaces: List[QuicPacketSpace] = [] # callbacks + self._quic_logger = quic_logger self._send_probe = send_probe # loss detection self._pto_count = 0 self._rtt_initialized = False self._rtt_latest = 0.0 self._rtt_min = math.inf self._rtt_smoothed = 0.0 self._rtt_variance = 0.0 self._time_of_last_sent_ack_eliciting_packet = 0.0 # congestion control self.bytes_in_flight = 0 self.congestion_window = K_INITIAL_WINDOW self._congestion_recovery_start_time = 0.0 + self._ssthresh: Optional[int] = None - self._ssthresh = math.inf ===========changed ref 2=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: """ Update metrics as the result of an ACK being received. """ is_ack_eliciting = False largest_acked = ack_rangeset.bounds().stop - 1 largest_newly_acked = None largest_sent_time = None if largest_acked > space.largest_acked_packet: space.largest_acked_packet = largest_acked for packet_number in sorted(space.sent_packets.keys()): if packet_number > largest_acked: break if packet_number in ack_rangeset: # remove packet and update counters packet = space.sent_packets.pop(packet_number) if packet.is_ack_eliciting: is_ack_eliciting = True space.ack_eliciting_in_flight -= 1 if packet.in_flight: self.on_packet_acked(packet) largest_newly_acked = packet_number largest_sent_time = packet.sent_time # trigger callbacks for handler, args in packet.delivery_handlers: handler(QuicDeliveryState.ACKED, *args) # nothing to do if there are no newly acked packets if largest_newly_acked is None: return if largest_acked == largest_newly_acked and is_ack_eliciting: latest_rtt = now - largest_sent_time # decode ACK delay into seconds ack_delay = max( (ack_delay_encoded << self.ack_delay_exponent) / 1000000, self.max_ack_delay / 1000, ) # update RTT estimate, which cannot be < 1 ms self._</s> ===========changed ref 3=========== # module: aioquic.quic.recovery class QuicPacketRecovery: def on_ack_received( self, space: QuicPacketSpace, ack_rangeset: RangeSet, ack_delay_encoded: int, now: float, ) -> None: # offset: 1 <s>max_ack_delay / 1000, ) # update RTT estimate, which cannot be < 1 ms self._rtt_latest = max(latest_rtt, 0.001) if self._rtt_latest < self._rtt_min: self._rtt_min = self._rtt_latest if self._rtt_latest > self._rtt_min + ack_delay: self._rtt_latest -= ack_delay if not self._rtt_initialized: self._rtt_initialized = True self._rtt_variance = latest_rtt / 2 self._rtt_smoothed = latest_rtt else: self._rtt_variance = 3 / 4 * self._rtt_variance + 1 / 4 * abs( self._rtt_min - self._rtt_latest ) self._rtt_smoothed = ( 7 / 8 * self._rtt_smoothed + 1 / 8 * self._rtt_latest ) + if self._quic_logger is not None: + self._quic_logger.log_event( + category="recovery", + event="metric_update", + data={ + "latest_rtt": int(self._rtt_latest * 1000), + "min_rtt": int(self._rtt_min * 1000), + "smoothed_rtt": int(self._rtt_smoothed * 1000), + "rtt_variance": int(self._rtt_variance * 1000), + }, + ) + self.detect_loss(space, now ===========changed ref 4=========== + # module: aioquic.quic.logger + + ===========changed ref 5=========== + # module: aioquic.quic.logger + class QuicLogger: + def log_event(self, *, category: str, event: str, data: Dict) -> None: + self._events.append((time.time(), category, event, data)) + ===========changed ref 6=========== + # module: aioquic.quic.logger + class QuicLogger: + def __init__(self) -> None: + self._events: Deque[Tuple[float, str, str, Dict[str, Any]]] = deque() + ===========changed ref 7=========== + # module: aioquic.quic.logger + class QuicLogger: + def packet_type(self, packet_type: int) -> str: + return PACKET_TYPE_NAMES.get(packet_type & PACKET_TYPE_MASK, "1RTT") +
aioquic.quic.connection/QuicConnection.__init__
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
<13>:<add> self._quic_logger = configuration.quic_logger
# module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: <0> if configuration.is_client: <1> assert ( <2> original_connection_id is None <3> ), "Cannot set original_connection_id for a client" <4> else: <5> assert ( <6> configuration.certificate is not None <7> ), "SSL certificate is required for a server" <8> assert ( <9> configuration.private_key is not None <10> ), "SSL private key is required for a server" <11> <12> # counters for debugging <13> self._stateless_retry_count = 0 <14> self._version_negotiation_count = 0 <15> <16> # configuration <17> self._configuration = configuration <18> self._is_client = configuration.is_client <19> <20> self._ack_delay = K_GRANULARITY <21> self._close_at: Optional[float] = None <22> self._close_event: Optional[events.ConnectionTerminated] = None <23> self._connect_called = False <24> self._cryptos: Dict[tls.Epoch, CryptoPair] = {} <25> self._crypto_buffers: Dict[tls.Epoch, Buffer] = {} <26> self._crypto_streams: Dict[tls.Epoch, QuicStream] = {} <27> self._events: Deque[events.Event] = deque() <28> self._handshake_complete = False <29> self._handshake_confirmed = False <30> self._host_cids = [ <31> QuicConnectionId( <32> cid=os.urandom(8), <33> sequence_number=0, <34> stateless_reset_token=os.urandom(16), <35> was_sent=True, <36> ) <37> ] <38> self.host_cid</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 1 self._host_cid_seq = 1 self._local_active_connection_id_limit = 8 self._local_max_data = MAX_DATA_WINDOW self._local_max_data_sent = MAX_DATA_WINDOW self._local_max_data_used = 0 self._local_max_stream_data_bidi_local = MAX_DATA_WINDOW self._local_max_stream_data_bidi_remote = MAX_DATA_WINDOW self._local_max_stream_data_uni = MAX_DATA_WINDOW self._local_max_streams_bidi = 128 self._local_max_streams_uni = 128 self._logger = QuicConnectionAdapter( logger, {"host_cid": dump_cid(self.host_cid)} ) self._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, send_probe=self._send_probe ) self._loss_at: Optional[float] = None self._network_paths: List[QuicNetworkPath] = [] self._original_connection_id = original_connection_id self._packet_number = 0 self._parameters_received = False self._peer_cid = os.urandom(8) self._peer_cid_seq: Optional[int] = None self._peer_cid_available: List[QuicConnectionId] = [] self._peer_token = b"" self._remote_active_connection_id_limit = 0 self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self</s> ===========below chunk 1=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 2 <s> self._remote_idle_timeout = 0.0 # seconds self._remote_max_data = 0 self._remote_max_data_used = 0 self._remote_max_stream_data_bidi_local = 0 self._remote_max_stream_data_bidi_remote = 0 self._remote_max_stream_data_uni = 0 self._remote_max_streams_bidi = 0 self._remote_max_streams_uni = 0 self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} self._spin_bit = False self._spin_bit_peer = False self._spin_highest_pn = 0 self._state = QuicConnectionState.FIRSTFLIGHT self._streams: Dict[int, QuicStream] = {} self._streams_blocked_bidi: List[QuicStream] = [] self._streams_blocked_uni: List[QuicStream] = [] self._version: Optional[int] = None # things to send self._close_pending = False self._ping_pending: List[int] = [] self._probe_pending = False self._retire_connection_ids: List[int] = [] self._streams_blocked_pending = False # callbacks self._session_ticket_fetcher = session_ticket_fetcher self._session_ticket_handler = session_ticket_handler # frame handlers self.__frame_handlers = [ </s> ===========below chunk 2=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 3 <s>._handle_padding_frame, EPOCHS("IZHO")), (self._handle_padding_frame, EPOCHS("ZO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_ack_frame, EPOCHS("IHO")), (self._handle_reset_stream_frame, EPOCHS("ZO")), (self._handle_stop_sending_frame, EPOCHS("ZO")), (self._handle_crypto_frame, EPOCHS("IHO")), (self._handle_new_token_frame, EPOCHS("O")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_stream_frame, EPOCHS("ZO")), (self._handle_max_data_frame, EPOCHS("ZO")), (self._handle_max_stream_data_frame, EPOCHS("ZO")), (self._handle_max_streams_bidi_frame, EPOCHS("ZO</s> ===========below chunk 3=========== # module: aioquic.quic.connection class QuicConnection: def __init__( self, *, configuration: QuicConfiguration, original_connection_id: Optional[bytes] = None, session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None, session_ticket_handler: Optional[tls.SessionTicketHandler] = None, ) -> None: # offset: 4 <s> (self._handle_max_streams_uni_frame, EPOCHS("ZO")), (self._handle_data_blocked_frame, EPOCHS("ZO")), (self._handle_stream_data_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_streams_blocked_frame, EPOCHS("ZO")), (self._handle_new_connection_id_frame, EPOCHS("ZO")), (self._handle_retire_connection_id_frame, EPOCHS("O")), (self._handle_path_challenge_frame, EPOCHS("ZO")), (self._handle_path_response_frame, EPOCHS("O")), (self._handle_connection_close_frame, EPOCHS("IZHO")), (self._handle_connection_close_frame, EPOCHS("ZO")), ]
aioquic.quic.connection/QuicConnection.datagrams_to_send
Modified
aiortc~aioquic
aad0bcbeab3cbde64ceafd5816a83e0b311f284e
[logger] add initial support for QLOG format
# module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: <0> """ <1> Return a list of `(data, addr)` tuples of datagrams which need to be <2> sent, and the network address to which they need to be sent. <3> <4> :param now: The current time. <5> """ <6> network_path = self._network_paths[0] <7> <8> if self._state in END_STATES: <9> return [] <10> <11> # build datagrams <12> builder = QuicPacketBuilder( <13> host_cid=self.host_cid, <14> packet_number=self._packet_number, <15> pad_first_datagram=( <16> self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT <17> ), <18> peer_cid=self._peer_cid, <19> peer_token=self._peer_token, <20> spin_bit=self._spin_bit, <21> version=self._version, <22> ) <23> if self._close_pending: <24> for epoch, packet_type in ( <25> (tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT), <26> (tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE), <27> (tls.Epoch.INITIAL, PACKET_TYPE_INITIAL), <28> ): <29> crypto = self._cryptos[epoch] <30> if crypto.send.is_valid(): <31> builder.start_packet(packet_type, crypto) <32> write_close_frame( <33> builder=builder, <34> error_code=self._close_event.error_code, <35> frame_type=self._close_event.frame_type, <36> reason_phrase=self._close_event.reason_phrase, <37> ) <38> builder.end_packet() <39> self._close_pending = False <40> break <41> self._close_begin(is_initiator=True, now</s>
===========below chunk 0=========== # module: aioquic.quic.connection class QuicConnection: def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]: # offset: 1 else: # congestion control builder.max_flight_bytes = ( self._loss.congestion_window - self._loss.bytes_in_flight ) if self._probe_pending and builder.max_flight_bytes < PACKET_MAX_SIZE: builder.max_flight_bytes = PACKET_MAX_SIZE # limit data on un-validated network paths if not network_path.is_validated: builder.max_total_bytes = ( network_path.bytes_received * 3 - network_path.bytes_sent ) try: if not self._handshake_confirmed: for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]: self._write_handshake(builder, epoch) self._write_application(builder, network_path, now) except QuicPacketBuilderStop: pass datagrams, packets = builder.flush() if datagrams: self._packet_number = builder.packet_number # register packets sent_handshake = False for packet in packets: packet.sent_time = now self._loss.on_packet_sent( packet=packet, space=self._spaces[packet.epoch] ) if packet.epoch == tls.Epoch.HANDSHAKE: sent_handshake = True # 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: network_path.bytes_sent += len(datagram) ret.append((datagram, network_path.addr)) return ret ===========unchanged ref 0=========== at: aioquic.quic.configuration.QuicConfiguration supported_versions: List[QuicProtocolVersion] = field( default_factory=lambda: [QuicProtocolVersion.DRAFT_22] ) at: aioquic.quic.connection NetworkAddress = Any write_close_frame(builder: QuicPacketBuilder, error_code: int, frame_type: Optional[int], reason_phrase: str) -> None QuicConnectionState() END_STATES = frozenset( [ QuicConnectionState.CLOSING, QuicConnectionState.DRAINING, QuicConnectionState.TERMINATED, ] ) at: aioquic.quic.connection.QuicConnection _close_begin(is_initiator: bool, now: float) -> None _connect(now: float) -> None _write_application(builder: QuicPacketBuilder, network_path: QuicNetworkPath, now: float) -> None _write_handshake(builder: QuicPacketBuilder, epoch: tls.Epoch) -> None at: aioquic.quic.connection.QuicConnection.__init__ self._configuration = configuration 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._loss = QuicPacketRecovery( is_client_without_1rtt=self._is_client, quic_logger=self._quic_logger, send_probe=self._send_probe, ) self._network_paths: List[QuicNetworkPath] = [] self._packet_number = 0 self._peer_cid = os.urandom(8) self._peer_token = b"" self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {} ===========unchanged ref 1=========== self._spin_bit = False self._state = QuicConnectionState.FIRSTFLIGHT self._version: Optional[int] = None self._close_pending = False self._probe_pending = False at: aioquic.quic.connection.QuicConnection._handle_ack_frame self._handshake_confirmed = True at: aioquic.quic.connection.QuicConnection._handle_connection_close_frame self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase ) at: aioquic.quic.connection.QuicConnection._initialize self._cryptos = { tls.Epoch.INITIAL: CryptoPair(), tls.Epoch.ZERO_RTT: CryptoPair(), tls.Epoch.HANDSHAKE: CryptoPair(), tls.Epoch.ONE_RTT: CryptoPair(), } self._spaces = { tls.Epoch.INITIAL: QuicPacketSpace(), tls.Epoch.HANDSHAKE: QuicPacketSpace(), tls.Epoch.ONE_RTT: QuicPacketSpace(), } self._packet_number = 0 at: aioquic.quic.connection.QuicConnection._send_probe self._probe_pending = True at: aioquic.quic.connection.QuicConnection._set_state self._state = state at: aioquic.quic.connection.QuicConnection._write_application self._probe_pending = False at: aioquic.quic.connection.QuicConnection._write_handshake self._probe_pending = False at: aioquic.quic.connection.QuicConnection.change_connection_id self._peer_cid = connection_id.cid ===========unchanged ref 2=========== at: aioquic.quic.connection.QuicConnection.close self._close_event = events.ConnectionTerminated( error_code=error_code, frame_type=frame_type, reason_phrase=reason_phrase, ) self._close_pending = True at: aioquic.quic.connection.QuicConnection.connect self._network_paths = [QuicNetworkPath(addr, is_validated=True)] at: aioquic.quic.connection.QuicConnection.handle_timer self._close_event = events.ConnectionTerminated( error_code=QuicErrorCode.INTERNAL_ERROR, frame_type=None, reason_phrase="Idle timeout", ) at: aioquic.quic.connection.QuicConnection.receive_datagram self._close_event = events.ConnectionTerminated( error_code=QuicErrorCode.INTERNAL_ERROR, frame_type=None, reason_phrase="Could not find a common protocol version", ) self._version = QuicProtocolVersion(header.version) self._version = QuicProtocolVersion(max(common)) self._peer_cid = header.source_cid self._peer_token = header.token self._network_paths = [network_path] self._spin_bit = self._spin_bit_peer self._spin_bit = not self._spin_bit_peer self.host_cid = context.host_cid 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.crypto.CryptoContext is_valid() -> bool at: aioquic.quic.crypto.CryptoPair.__init__ self.send = CryptoContext()
examples.http3-server/handle_http_event
Modified
aiortc~aioquic
b81fa362ce14f9799e9998fec604c6ce03f357f2
[http3] serve static files from disk
<11>:<add> content_type="text/plain", <add> data=b"Bad Request", <del> data=render_html("Bad Request"), <15>:<add> return <16>:<add> # dynamically generated data, maximum 50MB <18>:<del> # we accept a maximum of 50MB <27>:<del> elif path in ["/", "/index.html"]: <28>:<del> send_response( <29>:<del> connection=connection, <30>:<del> data=render_html("It works!"), <31>:<del> status_code=200, <32>:<del> stream_id=event.stream_id, <33>:<add> return <del> ) <34>:<del> else: <35>:<del> send_response( <36>:<del> connection=connection, <37>:<del> data=render_html("The document could not be found."), <38>:<del> status_code=404, <39>:<del> stream_id=event.stream_id, <40>:<del> )
# module: examples.http3-server def handle_http_event( connection: HttpConnection, event: aioquic.h3.events.Event ) -> None: <0> """ <1> Serve HTTP requests. <2> """ <3> <4> if isinstance(event, RequestReceived): <5> headers = dict(event.headers) <6> try: <7> path = headers[b":path"].decode("utf8") <8> except (UnicodeDecodeError, ValueError): <9> send_response( <10> connection=connection, <11> data=render_html("Bad Request"), <12> status_code=400, <13> stream_id=event.stream_id, <14> ) <15> <16> size_match = re.match(r"^/(\d+)$", path) <17> if size_match: <18> # we accept a maximum of 50MB <19> size = min(50000000, int(size_match.group(1))) <20> send_response( <21> connection=connection, <22> content_type="text/plain", <23> data=b"Z" * size, <24> status_code=200, <25> stream_id=event.stream_id, <26> ) <27> elif path in ["/", "/index.html"]: <28> send_response( <29> connection=connection, <30> data=render_html("It works!"), <31> status_code=200, <32> stream_id=event.stream_id, <33> ) <34> else: <35> send_response( <36> connection=connection, <37> data=render_html("The document could not be found."), <38> status_code=404, <39> stream_id=event.stream_id, <40> ) <41>
===========unchanged ref 0=========== at: examples.http3-server ROOT = os.path.join(os.path.dirname(__file__), "htdocs") send_response(connection: HttpConnection, stream_id: int, data: bytes=b"", content_type: str="text/html", status_code: int=200) -> None at: io.BufferedWriter read(self, size: Optional[int]=..., /) -> bytes at: mimetypes guess_type(url: Union[Text, PathLike[str]], strict: bool=...) -> Tuple[Optional[str], Optional[str]] at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes at: re match(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: typing.Match pos: int endpos: int lastindex: Optional[int] lastgroup: Optional[AnyStr] string: AnyStr re: Pattern[AnyStr] group(group1: Union[str, int], group2: Union[str, int], /, *groups: Union[str, int]) -> Tuple[AnyStr, ...] group(group: Union[str, int]=..., /) -> AnyStr ===========changed ref 0=========== # module: examples.http3-server try: import uvloop except ImportError: uvloop = None - TEMPLATE = """<!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"/> - <title>aioquic</title> - </head> - <body> - <h1>Welcome to aioquic</h1> - <p>{content}</p> - </body> - </html> - """ - + ROOT = os.path.join(os.path.dirname(__file__), "htdocs") HttpConnection = Union[H0Connection, H3Connection]