{ // 获取包含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 \"\";\n TestDataSource body1{kShortBody};\n nghttp2_data_provider provider = body1.MakeDataProvider();\n std::unique_ptr frame_source =\n MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback);\n auto [length, eof] = frame_source->SelectPayloadLength(200);\n EXPECT_EQ(length, kShortBody.size());\n EXPECT_TRUE(eof);\n frame_source->Send(\"ninebytes\", length);\n EXPECT_EQ(result, absl::StrCat(\"ninebytes\", kShortBody));\n}\nTEST(MakeZeroCopyDataFrameSource, MultiFramePayload) {\n std::string result;\n const absl::string_view kShortBody =\n \"Example Page!\"\n \"
Wow!!\"\n \"
\"\n \"\";\n TestDataSource body1{kShortBody};\n nghttp2_data_provider provider = body1.MakeDataProvider();\n std::unique_ptr frame_source =\n MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback);\n auto ret = frame_source->SelectPayloadLength(50);\n EXPECT_EQ(ret.first, 50);\n EXPECT_FALSE(ret.second);\n frame_source->Send(\"ninebyte1\", ret.first);\n ret = frame_source->SelectPayloadLength(50);\n EXPECT_EQ(ret.first, 50);\n EXPECT_FALSE(ret.second);\n frame_source->Send(\"ninebyte2\", ret.first);\n ret = frame_source->SelectPayloadLength(50);\n EXPECT_EQ(ret.first, 44);\n EXPECT_TRUE(ret.second);\n frame_source->Send(\"ninebyte3\", ret.first);\n EXPECT_EQ(result,\n \"ninebyte1Example Page!
Wow!!<\"\n \"ninebyte3/th>
\");\n}\n} \n} \n} \n} "}}},{"rowIdx":415,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_ADAPTER_OGHTTP2_ADAPTER_H_\n#define QUICHE_HTTP2_ADAPTER_OGHTTP2_ADAPTER_H_\n#include \n#include \n#include \"quiche/http2/adapter/http2_adapter.h\"\n#include \"quiche/http2/adapter/http2_session.h\"\n#include \"quiche/http2/adapter/oghttp2_session.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace adapter {\nclass QUICHE_EXPORT OgHttp2Adapter : public Http2Adapter {\n public:\n using Options = OgHttp2Session::Options;\n static std::unique_ptr Create(Http2VisitorInterface& visitor,\n Options options);\n ~OgHttp2Adapter() override;\n bool IsServerSession() const override;\n bool want_read() const override { return session_->want_read(); }\n bool want_write() const override { return session_->want_write(); }\n int64_t ProcessBytes(absl::string_view bytes) override;\n void SubmitSettings(absl::Span settings) override;\n void SubmitPriorityForStream(Http2StreamId stream_id,\n Http2StreamId parent_stream_id, int weight,\n bool exclusive) override;\n void SubmitPing(Http2PingId ping_id) override;\n void SubmitShutdownNotice() override;\n void SubmitGoAway(Http2StreamId last_accepted_stream_id,\n Http2ErrorCode error_code,\n absl::string_view opaque_data) override;\n void SubmitWindowUpdate(Http2StreamId stream_id,\n int window_increment) override;\n void SubmitMetadata(Http2StreamId stream_id, size_t max_frame_size,\n std::unique_ptr source) override;\n void SubmitMetadata(Http2StreamId stream_id, size_t num_frames) override;\n int Send() override;\n int GetSendWindowSize() const override;\n int GetStreamSendWindowSize(Http2StreamId stream_id) const override;\n int GetStreamReceiveWindowLimit(Http2StreamId stream_id) const override;\n int GetStreamReceiveWindowSize(Http2StreamId stream_id) const override;\n int GetReceiveWindowSize() const override;\n int GetHpackEncoderDynamicTableSize() const override;\n int GetHpackEncoderDynamicTableCapacity() const;\n int GetHpackDecoderDynamicTableSize() const override;\n int GetHpackDecoderSizeLimit() const;\n Http2StreamId GetHighestReceivedStreamId() const override;\n void MarkDataConsumedForStream(Http2StreamId stream_id,\n size_t num_bytes) override;\n void SubmitRst(Http2StreamId stream_id, Http2ErrorCode error_code) override;\n int32_t SubmitRequest(absl::Span headers,\n std::unique_ptr data_source,\n bool end_stream, void* user_data) override;\n int SubmitResponse(Http2StreamId stream_id, absl::Span headers,\n std::unique_ptr data_source,\n bool end_stream) override;\n int SubmitTrailer(Http2StreamId stream_id,\n absl::Span trailers) override;\n void SetStreamUserData(Http2StreamId stream_id, void* user_data) override;\n void* GetStreamUserData(Http2StreamId stream_id) override;\n bool ResumeStream(Http2StreamId stream_id) override;\n private:\n OgHttp2Adapter(Http2VisitorInterface& visitor, Options options);\n std::unique_ptr session_;\n};\n} \n} \n#endif \n#include \"quiche/http2/adapter/oghttp2_adapter.h\"\n#include \n#include \n#include \n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"quiche/http2/adapter/http2_util.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/spdy/core/spdy_protocol.h\"\nnamespace http2 {\nnamespace adapter {\nnamespace {\nusing spdy::SpdyGoAwayIR;\nusing spdy::SpdyPingIR;\nusing spdy::SpdyPriorityIR;\nusing spdy::SpdyWindowUpdateIR;\n} \nstd::unique_ptr OgHttp2Adapter::Create(\n Http2VisitorInterface& visitor, Options options) {\n return absl::WrapUnique(new OgHttp2Adapter(visitor, std::move(options)));\n}\nOgHttp2Adapter::~OgHttp2Adapter() {}\nbool OgHttp2Adapter::IsServerSession() const {\n return session_->IsServerSession();\n}\nint64_t OgHttp2Adapter::ProcessBytes(absl::string_view bytes) {\n return session_->ProcessBytes(bytes);\n}\nvoid OgHttp2Adapter::SubmitSettings(absl::Span settings) {\n session_->SubmitSettings(settings);\n}\nvoid OgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id,\n Http2StreamId parent_stream_id,\n int weight, bool exclusive) {\n session_->EnqueueFrame(std::make_unique(\n stream_id, parent_stream_id, weight, exclusive));\n}\nvoid OgHttp2Adapter::SubmitPing(Http2PingId ping_id) {\n session_->EnqueueFrame(std::make_unique(ping_id));\n}\nvoid OgHttp2Adapter::SubmitShutdownNotice() {\n session_->StartGracefulShutdown();\n}\nvoid OgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id,\n Http2ErrorCode error_code,\n absl::string_view opaque_data) {\n session_->EnqueueFrame(std::make_unique(\n last_accepted_stream_id, TranslateErrorCode(error_code),\n std::string(opaque_data)));\n}\nvoid OgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id,\n int window_increment) {\n session_->EnqueueFrame(\n std::make_unique(stream_id, window_increment));\n}\nvoid OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,\n size_t ,\n std::unique_ptr source) {\n session_->SubmitMetadata(stream_id, std::move(source));\n}\nvoid OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,\n size_t ) {\n session_->SubmitMetadata(stream_id);\n}\nint OgHttp2Adapter::Send() { return session_->Send(); }\nint OgHttp2Adapter::GetSendWindowSize() const {\n return session_->GetRemoteWindowSize();\n}\nint OgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const {\n return session_->GetStreamSendWindowSize(stream_id);\n}\nint OgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const {\n return session_->GetStreamReceiveWindowLimit(stream_id);\n}\nint OgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const {\n return session_->GetStreamReceiveWindowSize(stream_id);\n}\nint OgHttp2Adapter::GetReceiveWindowSize() const {\n return session_->GetReceiveWindowSize();\n}\nint OgHttp2Adapter::GetHpackEncoderDynamicTableSize() const {\n return session_->GetHpackEncoderDynamicTableSize();\n}\nint OgHttp2Adapter::GetHpackEncoderDynamicTableCapacity() const {\n return session_->GetHpackEncoderDynamicTableCapacity();\n}\nint OgHttp2Adapter::GetHpackDecoderDynamicTableSize() const {\n return session_->GetHpackDecoderDynamicTableSize();\n}\nint OgHttp2Adapter::GetHpackDecoderSizeLimit() const {\n return session_->GetHpackDecoderSizeLimit();\n}\nHttp2StreamId OgHttp2Adapter::GetHighestReceivedStreamId() const {\n return session_->GetHighestReceivedStreamId();\n}\nvoid OgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id,\n size_t num_bytes) {\n session_->Consume(stream_id, num_bytes);\n}\nvoid OgHttp2Adapter::SubmitRst(Http2StreamId stream_id,\n Http2ErrorCode error_code) {\n session_->EnqueueFrame(std::make_unique(\n stream_id, TranslateErrorCode(error_code)));\n}\nint32_t OgHttp2Adapter::SubmitRequest(\n absl::Span headers,\n std::unique_ptr data_source, bool end_stream,\n void* user_data) {\n return session_->SubmitRequest(headers, std::move(data_source), end_stream,\n user_data);\n}\nint OgHttp2Adapter::SubmitResponse(Http2StreamId stream_id,\n absl::Span headers,\n std::unique_ptr data_source,\n bool end_stream) {\n return session_->SubmitResponse(stream_id, headers, std::move(data_source),\n end_stream);\n}\nint OgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id,\n absl::Span trailers) {\n return session_->SubmitTrailer(stream_id, trailers);\n}\nvoid OgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id,\n void* user_data) {\n session_->SetStreamUserData(stream_id, user_data);\n}\nvoid* OgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) {\n return session_->GetStreamUserData(stream_id);\n}\nbool OgHttp2Adapter::ResumeStream(Http2StreamId stream_id) {\n return session_->ResumeStream(stream_id);\n}\nOgHttp2Adapter::OgHttp2Adapter(Http2VisitorInterface& visitor, Options options)\n : Http2Adapter(visitor),\n session_(std::make_unique(visitor, std::move(options))) {}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/adapter/oghttp2_adapter.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"absl/strings/str_join.h\"\n#include \"quiche/http2/adapter/http2_protocol.h\"\n#include \"quiche/http2/adapter/http2_visitor_interface.h\"\n#include \"quiche/http2/adapter/mock_http2_visitor.h\"\n#include \"quiche/http2/adapter/oghttp2_util.h\"\n#include \"quiche/http2/adapter/test_frame_sequence.h\"\n#include \"quiche/http2/adapter/test_utils.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\n#include \"quiche/spdy/core/http2_header_block.h\"\nnamespace http2 {\nnamespace adapter {\nnamespace test {\nnamespace {\nusing ConnectionError = Http2VisitorInterface::ConnectionError;\nusing spdy::SpdyFrameType;\nusing testing::_;\nenum FrameType {\n DATA,\n HEADERS,\n PRIORITY,\n RST_STREAM,\n SETTINGS,\n PUSH_PROMISE,\n PING,\n GOAWAY,\n WINDOW_UPDATE,\n CONTINUATION,\n};\nTEST(OgHttp2AdapterTest, IsServerSession) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n EXPECT_TRUE(adapter->IsServerSession());\n}\nTEST(OgHttp2AdapterTest, ProcessBytes) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n testing::InSequence seq;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, 4, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(0, 8, 6, 0));\n EXPECT_CALL(visitor, OnPing(17, false));\n adapter->ProcessBytes(\n TestFrameSequence().ClientPreface().Ping(17).Serialize());\n}\nTEST(OgHttp2AdapterTest, HeaderValuesWithObsTextAllowedByDefault) {\n TestVisitor visitor;\n OgHttp2Session::Options options;\n options.perspective = Perspective::kServer;\n ASSERT_TRUE(options.allow_obs_text);\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames = TestFrameSequence()\n .ClientPreface()\n .Headers(1,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/\"},\n {\"name\", \"val\\xa1ue\"}},\n true)\n .Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":authority\", \"example.com\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":path\", \"/\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \"name\", \"val\\xa1ue\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(1));\n EXPECT_CALL(visitor, OnEndStream(1));\n const int64_t result = adapter->ProcessBytes(frames);\n EXPECT_EQ(frames.size(), static_cast(result));\n}\nTEST(OgHttp2AdapterTest, HeaderValuesWithObsTextDisallowed) {\n TestVisitor visitor;\n OgHttp2Session::Options options;\n options.allow_obs_text = false;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames = TestFrameSequence()\n .ClientPreface()\n .Headers(1,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/\"},\n {\"name\", \"val\\xa1ue\"}},\n true)\n .Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":authority\", \"example.com\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":path\", \"/\"));\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));\n const int64_t result = adapter->ProcessBytes(frames);\n EXPECT_EQ(frames.size(), static_cast(result));\n}\nTEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTab) {\n TestVisitor visitor;\n OgHttp2Session::Options options;\n options.allow_obs_text = false;\n options.perspective = Perspective::kServer;\n ASSERT_EQ(false, options.validate_path);\n options.validate_path = true;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames = TestFrameSequence()\n .ClientPreface()\n .Headers(1,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/ fragment\"}},\n true)\n .Headers(3,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/\\tfragment2\"}},\n true)\n .Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":authority\", \"example.com\"));\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));\n EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(3));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":authority\", \"example.com\"));\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));\n const int64_t result = adapter->ProcessBytes(frames);\n EXPECT_EQ(frames.size(), static_cast(result));\n}\nTEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTabNoPathValidation) {\n TestVisitor visitor;\n OgHttp2Session::Options options;\n options.allow_obs_text = false;\n options.perspective = Perspective::kServer;\n ASSERT_EQ(false, options.validate_path);\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames = TestFrameSequence()\n .ClientPreface()\n .Headers(1,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/ fragment\"}},\n true)\n .Headers(3,\n {{\":method\", \"GET\"},\n {\":scheme\", \"https\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/\\tfragment2\"}},\n true)\n .Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":authority\", \"example.com\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":path\", \"/ fragment\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(1));\n EXPECT_CALL(visitor, OnEndStream(1));\n EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(3));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":method\", \"GET\"));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":scheme\", \"https\"));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":authority\", \"example.com\"));\n EXPECT_CALL(visitor, OnHeaderForStream(3, \":path\", \"/\\tfragment2\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(3));\n EXPECT_CALL(visitor, OnEndStream(3));\n const int64_t result = adapter->ProcessBytes(frames);\n EXPECT_EQ(frames.size(), static_cast(result));\n}\nTEST(OgHttp2AdapterTest, InitialSettingsNoExtendedConnect) {\n TestVisitor client_visitor;\n OgHttp2Adapter::Options client_options;\n client_options.perspective = Perspective::kClient;\n client_options.max_header_list_bytes = 42;\n client_options.allow_extended_connect = false;\n auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options);\n TestVisitor server_visitor;\n OgHttp2Adapter::Options server_options;\n server_options.perspective = Perspective::kServer;\n server_options.allow_extended_connect = false;\n auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options);\n testing::InSequence s;\n EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0));\n EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0));\n {\n int result = client_adapter->Send();\n EXPECT_EQ(0, result);\n absl::string_view data = client_visitor.data();\n EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));\n data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));\n EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));\n }\n EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0));\n EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0));\n {\n int result = server_adapter->Send();\n EXPECT_EQ(0, result);\n absl::string_view data = server_visitor.data();\n EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));\n }\n EXPECT_CALL(client_visitor, OnFrameHeader(0, 0, SETTINGS, 0x0));\n EXPECT_CALL(client_visitor, OnSettingsStart());\n EXPECT_CALL(client_visitor, OnSettingsEnd());\n {\n const int64_t result = client_adapter->ProcessBytes(server_visitor.data());\n EXPECT_EQ(server_visitor.data().size(), static_cast(result));\n }\n EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0));\n EXPECT_CALL(server_visitor, OnSettingsStart());\n EXPECT_CALL(server_visitor,\n OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u}));\n EXPECT_CALL(\n server_visitor,\n OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u}));\n EXPECT_CALL(server_visitor, OnSettingsEnd());\n {\n const int64_t result = server_adapter->ProcessBytes(client_visitor.data());\n EXPECT_EQ(client_visitor.data().size(), static_cast(result));\n }\n}\nTEST(OgHttp2AdapterTest, InitialSettings) {\n TestVisitor client_visitor;\n OgHttp2Adapter::Options client_options;\n client_options.perspective = Perspective::kClient;\n client_options.max_header_list_bytes = 42;\n ASSERT_TRUE(client_options.allow_extended_connect);\n auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options);\n TestVisitor server_visitor;\n OgHttp2Adapter::Options server_options;\n server_options.perspective = Perspective::kServer;\n ASSERT_TRUE(server_options.allow_extended_connect);\n auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options);\n testing::InSequence s;\n EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0));\n EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0));\n {\n int result = client_adapter->Send();\n EXPECT_EQ(0, result);\n absl::string_view data = client_visitor.data();\n EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));\n data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));\n EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));\n }\n EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));\n EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));\n {\n int result = server_adapter->Send();\n EXPECT_EQ(0, result);\n absl::string_view data = server_visitor.data();\n EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));\n }\n EXPECT_CALL(client_visitor, OnFrameHeader(0, 6, SETTINGS, 0x0));\n EXPECT_CALL(client_visitor, OnSettingsStart());\n EXPECT_CALL(client_visitor,\n OnSetting(Http2Setting{\n Http2KnownSettingsId::ENABLE_CONNECT_PROTOCOL, 1u}));\n EXPECT_CALL(client_visitor, OnSettingsEnd());\n {\n const int64_t result = client_adapter->ProcessBytes(server_visitor.data());\n EXPECT_EQ(server_visitor.data().size(), static_cast(result));\n }\n EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0));\n EXPECT_CALL(server_visitor, OnSettingsStart());\n EXPECT_CALL(server_visitor,\n OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u}));\n EXPECT_CALL(\n server_visitor,\n OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u}));\n EXPECT_CALL(server_visitor, OnSettingsEnd());\n {\n const int64_t result = server_adapter->ProcessBytes(client_visitor.data());\n EXPECT_EQ(client_visitor.data().size(), static_cast(result));\n }\n}\nTEST(OgHttp2AdapterTest, AutomaticSettingsAndPingAcks) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames =\n TestFrameSequence().ClientPreface().Ping(42).Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));\n EXPECT_CALL(visitor, OnPing(42, false));\n const int64_t read_result = adapter->ProcessBytes(frames);\n EXPECT_EQ(static_cast(read_result), frames.size());\n EXPECT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0));\n int send_result = adapter->Send();\n EXPECT_EQ(0, send_result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,\n SpdyFrameType::PING}));\n}\nTEST(OgHttp2AdapterTest, AutomaticPingAcksDisabled) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n options.auto_ping_ack = false;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames =\n TestFrameSequence().ClientPreface().Ping(42).Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));\n EXPECT_CALL(visitor, OnPing(42, false));\n const int64_t read_result = adapter->ProcessBytes(frames);\n EXPECT_EQ(static_cast(read_result), frames.size());\n EXPECT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));\n int send_result = adapter->Send();\n EXPECT_EQ(0, send_result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));\n}\nTEST(OgHttp2AdapterTest, InvalidMaxFrameSizeSetting) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames =\n TestFrameSequence().ClientPreface({{MAX_FRAME_SIZE, 3u}}).Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));\n EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));\n const int64_t read_result = adapter->ProcessBytes(frames);\n EXPECT_EQ(static_cast(read_result), frames.size());\n EXPECT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));\n EXPECT_CALL(visitor,\n OnFrameSent(GOAWAY, 0, _, 0x0,\n static_cast(Http2ErrorCode::PROTOCOL_ERROR)));\n int send_result = adapter->Send();\n EXPECT_EQ(0, send_result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));\n}\nTEST(OgHttp2AdapterTest, InvalidPushSetting) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames =\n TestFrameSequence().ClientPreface({{ENABLE_PUSH, 3u}}).Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));\n EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));\n const int64_t read_result = adapter->ProcessBytes(frames);\n EXPECT_EQ(static_cast(read_result), frames.size());\n EXPECT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));\n EXPECT_CALL(visitor,\n OnFrameSent(GOAWAY, 0, _, 0x0,\n static_cast(Http2ErrorCode::PROTOCOL_ERROR)));\n int send_result = adapter->Send();\n EXPECT_EQ(0, send_result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));\n}\nTEST(OgHttp2AdapterTest, InvalidConnectProtocolSetting) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kServer;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n const std::string frames = TestFrameSequence()\n .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 3u}})\n .Serialize();\n testing::InSequence s;\n EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));\n EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));\n int64_t read_result = adapter->ProcessBytes(frames);\n EXPECT_EQ(static_cast(read_result), frames.size());\n EXPECT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));\n EXPECT_CALL(visitor,\n OnFrameSent(GOAWAY, 0, _, 0x0,\n static_cast(Http2ErrorCode::PROTOCOL_ERROR)));\n int send_result = adapter->Send();\n EXPECT_EQ(0, send_result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));\n auto adapter2 = OgHttp2Adapter::Create(visitor, options);\n const std::string frames2 = TestFrameSequence()\n .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 1}})\n .Settings({{ENABLE_CONNECT_PROTOCOL, 0}})\n .Serialize();\n EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 1u}));\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(\n visitor,\n OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));\n EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));\n read_result = adapter2->ProcessBytes(frames2);\n EXPECT_EQ(static_cast(read_result), frames2.size());\n EXPECT_TRUE(adapter2->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));\n EXPECT_CALL(visitor,\n OnFrameSent(GOAWAY, 0, _, 0x0,\n static_cast(Http2ErrorCode::PROTOCOL_ERROR)));\n adapter2->Send();\n}\nTEST(OgHttp2AdapterTest, ClientSetsRemoteMaxStreamOption) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kClient;\n options.remote_max_concurrent_streams = 3;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n testing::InSequence s;\n const std::vector
headers = ToHeaders({{\":method\", \"GET\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/\"}});\n const int32_t stream_id1 =\n adapter->SubmitRequest(headers, nullptr, true, nullptr);\n const int32_t stream_id2 =\n adapter->SubmitRequest(headers, nullptr, true, nullptr);\n const int32_t stream_id3 =\n adapter->SubmitRequest(headers, nullptr, true, nullptr);\n const int32_t stream_id4 =\n adapter->SubmitRequest(headers, nullptr, true, nullptr);\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n int result = adapter->Send();\n EXPECT_EQ(0, result);\n visitor.Clear();\n const std::string stream_frames =\n TestFrameSequence()\n .ServerPreface()\n .Headers(stream_id1,\n {{\":status\", \"200\"},\n {\"server\", \"my-fake-server\"},\n {\"date\", \"Tue, 6 Apr 2021 12:54:01 GMT\"}},\n true)\n .Serialize();\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(stream_id1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id1));\n EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, \":status\", \"200\"));\n EXPECT_CALL(visitor,\n OnHeaderForStream(stream_id1, \"server\", \"my-fake-server\"));\n EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, \"date\",\n \"Tue, 6 Apr 2021 12:54:01 GMT\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id1));\n EXPECT_CALL(visitor, OnEndStream(stream_id1));\n EXPECT_CALL(visitor,\n OnCloseStream(stream_id1, Http2ErrorCode::HTTP2_NO_ERROR));\n const int64_t stream_result = adapter->ProcessBytes(stream_frames);\n EXPECT_EQ(stream_frames.size(), static_cast(stream_result));\n ASSERT_TRUE(adapter->want_write());\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id4, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id4, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n result = adapter->Send();\n EXPECT_EQ(0, result);\n}\nTEST(OgHttp2AdapterTest, ClientHandles100Headers) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kClient;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n testing::InSequence s;\n const std::vector
headers1 =\n ToHeaders({{\":method\", \"GET\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/this/is/request/one\"}});\n const int32_t stream_id1 =\n adapter->SubmitRequest(headers1, nullptr, true, nullptr);\n ASSERT_GT(stream_id1, 0);\n QUICHE_LOG(INFO) << \"Created stream: \" << stream_id1;\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n int result = adapter->Send();\n EXPECT_EQ(0, result);\n visitor.Clear();\n const std::string stream_frames =\n TestFrameSequence()\n .ServerPreface()\n .Headers(1, {{\":status\", \"100\"}},\n false)\n .Ping(101)\n .Headers(1,\n {{\":status\", \"200\"},\n {\"server\", \"my-fake-server\"},\n {\"date\", \"Tue, 6 Apr 2021 12:54:01 GMT\"}},\n true)\n .Serialize();\n EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));\n EXPECT_CALL(visitor, OnSettingsStart());\n EXPECT_CALL(visitor, OnSettingsEnd());\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":status\", \"100\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(1));\n EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));\n EXPECT_CALL(visitor, OnPing(101, false));\n EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));\n EXPECT_CALL(visitor, OnBeginHeadersForStream(1));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \":status\", \"200\"));\n EXPECT_CALL(visitor, OnHeaderForStream(1, \"server\", \"my-fake-server\"));\n EXPECT_CALL(visitor,\n OnHeaderForStream(1, \"date\", \"Tue, 6 Apr 2021 12:54:01 GMT\"));\n EXPECT_CALL(visitor, OnEndHeadersForStream(1));\n EXPECT_CALL(visitor, OnEndStream(1));\n EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));\n const int64_t stream_result = adapter->ProcessBytes(stream_frames);\n EXPECT_EQ(stream_frames.size(), static_cast(stream_result));\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0));\n EXPECT_TRUE(adapter->want_write());\n result = adapter->Send();\n EXPECT_EQ(0, result);\n EXPECT_THAT(visitor.data(),\n EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));\n}\nTEST(OgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kClient;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize);\n adapter->SubmitWindowUpdate(0, 10000);\n EXPECT_EQ(adapter->GetReceiveWindowSize(),\n kInitialFlowControlWindowSize + 10000);\n const std::vector
headers =\n ToHeaders({{\":method\", \"GET\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"/this/is/request/one\"}});\n const int32_t stream_id =\n adapter->SubmitRequest(headers, nullptr, true, nullptr);\n EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));\n EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));\n EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _,\n END_STREAM_FLAG | END_HEADERS_FLAG));\n EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _,\n END_STREAM_FLAG | END_HEADERS_FLAG, 0));\n int result = adapter->Send();\n EXPECT_EQ(0, result);\n EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),\n kInitialFlowControlWindowSize);\n adapter->SubmitWindowUpdate(1, 20000);\n EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),\n kInitialFlowControlWindowSize + 20000);\n}\nTEST(OgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) {\n TestVisitor visitor;\n OgHttp2Adapter::Options options;\n options.perspective = Perspective::kClient;\n auto adapter = OgHttp2Adapter::Create(visitor, options);\n testing::InSequence s;\n const std::vector
headers ="}}},{"rowIdx":416,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_HTTP2_FRAME_DECODER_H_\n#define QUICHE_HTTP2_DECODER_HTTP2_FRAME_DECODER_H_\n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/data_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/headers_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/ping_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/priority_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/settings_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h\"\n#include \"quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace test {\nclass Http2FrameDecoderPeer;\n} \nclass QUICHE_EXPORT Http2FrameDecoder {\n public:\n explicit Http2FrameDecoder(Http2FrameDecoderListener* listener);\n Http2FrameDecoder(const Http2FrameDecoder&) = delete;\n Http2FrameDecoder& operator=(const Http2FrameDecoder&) = delete;\n void set_listener(Http2FrameDecoderListener* listener);\n Http2FrameDecoderListener* listener() const;\n void set_maximum_payload_size(size_t v) { maximum_payload_size_ = v; }\n size_t maximum_payload_size() const { return maximum_payload_size_; }\n DecodeStatus DecodeFrame(DecodeBuffer* db);\n bool IsDiscardingPayload() const { return state_ == State::kDiscardPayload; }\n size_t remaining_payload() const;\n uint32_t remaining_padding() const;\n private:\n enum class State {\n kStartDecodingHeader,\n kResumeDecodingHeader,\n kResumeDecodingPayload,\n kDiscardPayload,\n };\n friend class test::Http2FrameDecoderPeer;\n QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& out, State v);\n DecodeStatus StartDecodingPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(DecodeBuffer* db);\n DecodeStatus DiscardPayload(DecodeBuffer* db);\n const Http2FrameHeader& frame_header() const {\n return frame_decoder_state_.frame_header();\n }\n void RetainFlags(uint8_t valid_flags);\n void ClearFlags();\n DecodeStatus StartDecodingAltSvcPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingContinuationPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingDataPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingGoAwayPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingHeadersPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingPingPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingPriorityPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingPriorityUpdatePayload(DecodeBuffer* db);\n DecodeStatus StartDecodingPushPromisePayload(DecodeBuffer* db);\n DecodeStatus StartDecodingRstStreamPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingSettingsPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingUnknownPayload(DecodeBuffer* db);\n DecodeStatus StartDecodingWindowUpdatePayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingAltSvcPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingContinuationPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingDataPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingGoAwayPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingHeadersPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingPingPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingPriorityPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingPriorityUpdatePayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingPushPromisePayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingRstStreamPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingSettingsPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingUnknownPayload(DecodeBuffer* db);\n DecodeStatus ResumeDecodingWindowUpdatePayload(DecodeBuffer* db);\n FrameDecoderState frame_decoder_state_;\n union {\n AltSvcPayloadDecoder altsvc_payload_decoder_;\n ContinuationPayloadDecoder continuation_payload_decoder_;\n DataPayloadDecoder data_payload_decoder_;\n GoAwayPayloadDecoder goaway_payload_decoder_;\n HeadersPayloadDecoder headers_payload_decoder_;\n PingPayloadDecoder ping_payload_decoder_;\n PriorityPayloadDecoder priority_payload_decoder_;\n PriorityUpdatePayloadDecoder priority_payload_update_decoder_;\n PushPromisePayloadDecoder push_promise_payload_decoder_;\n RstStreamPayloadDecoder rst_stream_payload_decoder_;\n SettingsPayloadDecoder settings_payload_decoder_;\n UnknownPayloadDecoder unknown_payload_decoder_;\n WindowUpdatePayloadDecoder window_update_payload_decoder_;\n };\n State state_;\n size_t maximum_payload_size_;\n Http2FrameDecoderNoOpListener no_op_listener_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/http2_frame_decoder.h\"\n#include \n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/hpack/varint/hpack_varint_decoder.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out, Http2FrameDecoder::State v) {\n switch (v) {\n case Http2FrameDecoder::State::kStartDecodingHeader:\n return out << \"kStartDecodingHeader\";\n case Http2FrameDecoder::State::kResumeDecodingHeader:\n return out << \"kResumeDecodingHeader\";\n case Http2FrameDecoder::State::kResumeDecodingPayload:\n return out << \"kResumeDecodingPayload\";\n case Http2FrameDecoder::State::kDiscardPayload:\n return out << \"kDiscardPayload\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_155_1) << \"Http2FrameDecoder::State \" << unknown;\n return out << \"Http2FrameDecoder::State(\" << unknown << \")\";\n}\nHttp2FrameDecoder::Http2FrameDecoder(Http2FrameDecoderListener* listener)\n : state_(State::kStartDecodingHeader),\n maximum_payload_size_(Http2SettingsInfo::DefaultMaxFrameSize()) {\n set_listener(listener);\n}\nvoid Http2FrameDecoder::set_listener(Http2FrameDecoderListener* listener) {\n if (listener == nullptr) {\n listener = &no_op_listener_;\n }\n frame_decoder_state_.set_listener(listener);\n}\nHttp2FrameDecoderListener* Http2FrameDecoder::listener() const {\n return frame_decoder_state_.listener();\n}\nDecodeStatus Http2FrameDecoder::DecodeFrame(DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"Http2FrameDecoder::DecodeFrame state=\" << state_;\n switch (state_) {\n case State::kStartDecodingHeader:\n if (frame_decoder_state_.StartDecodingFrameHeader(db)) {\n return StartDecodingPayload(db);\n }\n state_ = State::kResumeDecodingHeader;\n return DecodeStatus::kDecodeInProgress;\n case State::kResumeDecodingHeader:\n if (frame_decoder_state_.ResumeDecodingFrameHeader(db)) {\n return StartDecodingPayload(db);\n }\n return DecodeStatus::kDecodeInProgress;\n case State::kResumeDecodingPayload:\n return ResumeDecodingPayload(db);\n case State::kDiscardPayload:\n return DiscardPayload(db);\n }\n QUICHE_NOTREACHED();\n return DecodeStatus::kDecodeError;\n}\nsize_t Http2FrameDecoder::remaining_payload() const {\n return frame_decoder_state_.remaining_payload();\n}\nuint32_t Http2FrameDecoder::remaining_padding() const {\n return frame_decoder_state_.remaining_padding();\n}\nDecodeStatus Http2FrameDecoder::StartDecodingPayload(DecodeBuffer* db) {\n const Http2FrameHeader& header = frame_header();\n if (!listener()->OnFrameHeader(header)) {\n QUICHE_DVLOG(2)\n << \"OnFrameHeader rejected the frame, will discard; header: \" << header;\n state_ = State::kDiscardPayload;\n frame_decoder_state_.InitializeRemainders();\n return DecodeStatus::kDecodeError;\n }\n if (header.payload_length > maximum_payload_size_) {\n QUICHE_DVLOG(2) << \"Payload length is greater than allowed: \"\n << header.payload_length << \" > \" << maximum_payload_size_\n << \"\\n header: \" << header;\n state_ = State::kDiscardPayload;\n frame_decoder_state_.InitializeRemainders();\n listener()->OnFrameSizeError(header);\n return DecodeStatus::kDecodeError;\n }\n DecodeBufferSubset subset(db, header.payload_length);\n DecodeStatus status;\n switch (header.type) {\n case Http2FrameType::DATA:\n status = StartDecodingDataPayload(&subset);\n break;\n case Http2FrameType::HEADERS:\n status = StartDecodingHeadersPayload(&subset);\n break;\n case Http2FrameType::PRIORITY:\n status = StartDecodingPriorityPayload(&subset);\n break;\n case Http2FrameType::RST_STREAM:\n status = StartDecodingRstStreamPayload(&subset);\n break;\n case Http2FrameType::SETTINGS:\n status = StartDecodingSettingsPayload(&subset);\n break;\n case Http2FrameType::PUSH_PROMISE:\n status = StartDecodingPushPromisePayload(&subset);\n break;\n case Http2FrameType::PING:\n status = StartDecodingPingPayload(&subset);\n break;\n case Http2FrameType::GOAWAY:\n status = StartDecodingGoAwayPayload(&subset);\n break;\n case Http2FrameType::WINDOW_UPDATE:\n status = StartDecodingWindowUpdatePayload(&subset);\n break;\n case Http2FrameType::CONTINUATION:\n status = StartDecodingContinuationPayload(&subset);\n break;\n case Http2FrameType::ALTSVC:\n status = StartDecodingAltSvcPayload(&subset);\n break;\n case Http2FrameType::PRIORITY_UPDATE:\n status = StartDecodingPriorityUpdatePayload(&subset);\n break;\n default:\n status = StartDecodingUnknownPayload(&subset);\n break;\n }\n if (status == DecodeStatus::kDecodeDone) {\n state_ = State::kStartDecodingHeader;\n return status;\n } else if (status == DecodeStatus::kDecodeInProgress) {\n state_ = State::kResumeDecodingPayload;\n return status;\n } else {\n state_ = State::kDiscardPayload;\n return status;\n }\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingPayload(DecodeBuffer* db) {\n size_t remaining = frame_decoder_state_.remaining_total_payload();\n QUICHE_DCHECK_LE(remaining, frame_header().payload_length);\n DecodeBufferSubset subset(db, remaining);\n DecodeStatus status;\n switch (frame_header().type) {\n case Http2FrameType::DATA:\n status = ResumeDecodingDataPayload(&subset);\n break;\n case Http2FrameType::HEADERS:\n status = ResumeDecodingHeadersPayload(&subset);\n break;\n case Http2FrameType::PRIORITY:\n status = ResumeDecodingPriorityPayload(&subset);\n break;\n case Http2FrameType::RST_STREAM:\n status = ResumeDecodingRstStreamPayload(&subset);\n break;\n case Http2FrameType::SETTINGS:\n status = ResumeDecodingSettingsPayload(&subset);\n break;\n case Http2FrameType::PUSH_PROMISE:\n status = ResumeDecodingPushPromisePayload(&subset);\n break;\n case Http2FrameType::PING:\n status = ResumeDecodingPingPayload(&subset);\n break;\n case Http2FrameType::GOAWAY:\n status = ResumeDecodingGoAwayPayload(&subset);\n break;\n case Http2FrameType::WINDOW_UPDATE:\n status = ResumeDecodingWindowUpdatePayload(&subset);\n break;\n case Http2FrameType::CONTINUATION:\n status = ResumeDecodingContinuationPayload(&subset);\n break;\n case Http2FrameType::ALTSVC:\n status = ResumeDecodingAltSvcPayload(&subset);\n break;\n case Http2FrameType::PRIORITY_UPDATE:\n status = ResumeDecodingPriorityUpdatePayload(&subset);\n break;\n default:\n status = ResumeDecodingUnknownPayload(&subset);\n break;\n }\n if (status == DecodeStatus::kDecodeDone) {\n state_ = State::kStartDecodingHeader;\n return status;\n } else if (status == DecodeStatus::kDecodeInProgress) {\n return status;\n } else {\n state_ = State::kDiscardPayload;\n return status;\n }\n}\nvoid Http2FrameDecoder::RetainFlags(uint8_t valid_flags) {\n frame_decoder_state_.RetainFlags(valid_flags);\n}\nvoid Http2FrameDecoder::ClearFlags() { frame_decoder_state_.ClearFlags(); }\nDecodeStatus Http2FrameDecoder::StartDecodingAltSvcPayload(DecodeBuffer* db) {\n ClearFlags();\n return altsvc_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingAltSvcPayload(DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return altsvc_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingContinuationPayload(\n DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::END_HEADERS);\n return continuation_payload_decoder_.StartDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingContinuationPayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return continuation_payload_decoder_.ResumeDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingDataPayload(DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED);\n return data_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingDataPayload(DecodeBuffer* db) {\n return data_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingGoAwayPayload(DecodeBuffer* db) {\n ClearFlags();\n return goaway_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingGoAwayPayload(DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return goaway_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingHeadersPayload(DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS |\n Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY);\n return headers_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingHeadersPayload(DecodeBuffer* db) {\n QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(),\n frame_header().payload_length);\n return headers_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingPingPayload(DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::ACK);\n return ping_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingPingPayload(DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return ping_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingPriorityPayload(DecodeBuffer* db) {\n ClearFlags();\n return priority_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingPriorityPayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return priority_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingPriorityUpdatePayload(\n DecodeBuffer* db) {\n ClearFlags();\n return priority_payload_update_decoder_.StartDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingPriorityUpdatePayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return priority_payload_update_decoder_.ResumeDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingPushPromisePayload(\n DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED);\n return push_promise_payload_decoder_.StartDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingPushPromisePayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(),\n frame_header().payload_length);\n return push_promise_payload_decoder_.ResumeDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingRstStreamPayload(\n DecodeBuffer* db) {\n ClearFlags();\n return rst_stream_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingRstStreamPayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return rst_stream_payload_decoder_.ResumeDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingSettingsPayload(DecodeBuffer* db) {\n RetainFlags(Http2FrameFlag::ACK);\n return settings_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingSettingsPayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return settings_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingUnknownPayload(DecodeBuffer* db) {\n return unknown_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingUnknownPayload(DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return unknown_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,\n db);\n}\nDecodeStatus Http2FrameDecoder::StartDecodingWindowUpdatePayload(\n DecodeBuffer* db) {\n ClearFlags();\n return window_update_payload_decoder_.StartDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::ResumeDecodingWindowUpdatePayload(\n DecodeBuffer* db) {\n QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),\n frame_decoder_state_.remaining_payload());\n return window_update_payload_decoder_.ResumeDecodingPayload(\n &frame_decoder_state_, db);\n}\nDecodeStatus Http2FrameDecoder::DiscardPayload(DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"remaining_payload=\"\n << frame_decoder_state_.remaining_payload_\n << \"; remaining_padding=\"\n << frame_decoder_state_.remaining_padding_;\n frame_decoder_state_.remaining_payload_ +=\n frame_decoder_state_.remaining_padding_;\n frame_decoder_state_.remaining_padding_ = 0;\n const size_t avail = frame_decoder_state_.AvailablePayload(db);\n QUICHE_DVLOG(2) << \"avail=\" << avail;\n if (avail > 0) {\n frame_decoder_state_.ConsumePayload(avail);\n db->AdvanceCursor(avail);\n }\n if (frame_decoder_state_.remaining_payload_ == 0) {\n state_ = State::kStartDecodingHeader;\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/http2_frame_decoder.h\"\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector_listener.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nclass Http2FrameDecoderPeer {\n public:\n static size_t remaining_total_payload(Http2FrameDecoder* decoder) {\n return decoder->frame_decoder_state_.remaining_total_payload();\n }\n};\nnamespace {\nclass Http2FrameDecoderTest : public RandomDecoderTest {\n protected:\n DecodeStatus StartDecoding(DecodeBuffer* db) override {\n QUICHE_DVLOG(2) << \"StartDecoding, db->Remaining=\" << db->Remaining();\n collector_.Reset();\n PrepareDecoder();\n DecodeStatus status = decoder_->DecodeFrame(db);\n if (status != DecodeStatus::kDecodeInProgress) {\n ++fast_decode_count_;\n if (status == DecodeStatus::kDecodeError) {\n ConfirmDiscardsRemainingPayload();\n }\n }\n return status;\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* db) override {\n QUICHE_DVLOG(2) << \"ResumeDecoding, db->Remaining=\" << db->Remaining();\n DecodeStatus status = decoder_->DecodeFrame(db);\n if (status != DecodeStatus::kDecodeInProgress) {\n ++slow_decode_count_;\n if (status == DecodeStatus::kDecodeError) {\n ConfirmDiscardsRemainingPayload();\n }\n }\n return status;\n }\n void ConfirmDiscardsRemainingPayload() {\n ASSERT_TRUE(decoder_->IsDiscardingPayload());\n size_t remaining =\n Http2FrameDecoderPeer::remaining_total_payload(decoder_.get());\n size_t extra = 10;\n std::string junk(remaining + extra, '0');\n DecodeBuffer tmp(junk);\n EXPECT_EQ(DecodeStatus::kDecodeDone, decoder_->DecodeFrame(&tmp));\n EXPECT_EQ(remaining, tmp.Offset());\n EXPECT_EQ(extra, tmp.Remaining());\n EXPECT_FALSE(decoder_->IsDiscardingPayload());\n }\n void PrepareDecoder() {\n decoder_ = std::make_unique(&collector_);\n decoder_->set_maximum_payload_size(maximum_payload_size_);\n }\n void ResetDecodeSpeedCounters() {\n fast_decode_count_ = 0;\n slow_decode_count_ = 0;\n }\n AssertionResult VerifyCollected(const FrameParts& expected) {\n HTTP2_VERIFY_FALSE(collector_.IsInProgress());\n HTTP2_VERIFY_EQ(1u, collector_.size());\n return expected.VerifyEquals(*collector_.frame(0));\n }\n AssertionResult DecodePayloadAndValidateSeveralWays(absl::string_view payload,\n Validator validator) {\n DecodeBuffer db(payload);\n bool start_decoding_requires_non_empty = false;\n return DecodeAndValidateSeveralWays(&db, start_decoding_requires_non_empty,\n validator);\n }\n AssertionResult DecodePayloadAndValidateSeveralWays(\n absl::string_view payload, const FrameParts& expected) {\n auto validator = [&expected, this](const DecodeBuffer& ,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);\n return VerifyCollected(expected);\n };\n ResetDecodeSpeedCounters();\n HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays(\n payload, ValidateDoneAndEmpty(validator)));\n HTTP2_VERIFY_GT(fast_decode_count_, 0u);\n HTTP2_VERIFY_GT(slow_decode_count_, 0u);\n std::string next_frame = Random().RandString(10);\n std::string input(payload.data(), payload.size());\n input += next_frame;\n ResetDecodeSpeedCounters();\n HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays(\n payload, ValidateDoneAndOffset(payload.size(), validator)));\n HTTP2_VERIFY_GT(fast_decode_count_, 0u);\n HTTP2_VERIFY_GT(slow_decode_count_, 0u);\n return AssertionSuccess();\n }\n template \n AssertionResult DecodePayloadAndValidateSeveralWays(\n const char (&buf)[N], const FrameParts& expected) {\n return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N),\n expected);\n }\n template \n AssertionResult DecodePayloadAndValidateSeveralWays(\n const char (&buf)[N], const Http2FrameHeader& header) {\n return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N),\n FrameParts(header));\n }\n template \n AssertionResult DecodePayloadExpectingError(const char (&buf)[N],\n const FrameParts& expected) {\n auto validator = [&expected, this](const DecodeBuffer& ,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeError);\n return VerifyCollected(expected);\n };\n ResetDecodeSpeedCounters();\n EXPECT_TRUE(\n DecodePayloadAndValidateSeveralWays(ToStringPiece(buf), validator));\n EXPECT_GT(fast_decode_count_, 0u);\n EXPECT_GT(slow_decode_count_, 0u);\n return AssertionSuccess();\n }\n template \n AssertionResult DecodePayloadExpectingFrameSizeError(const char (&buf)[N],\n FrameParts expected) {\n expected.SetHasFrameSizeError(true);\n return DecodePayloadExpectingError(buf, expected);\n }\n template \n AssertionResult DecodePayloadExpectingFrameSizeError(\n const char (&buf)[N], const Http2FrameHeader& header) {\n return DecodePayloadExpectingFrameSizeError(buf, FrameParts(header));\n }\n size_t fast_decode_count_ = 0;\n size_t slow_decode_count_ = 0;\n uint32_t maximum_payload_size_ = Http2SettingsInfo::DefaultMaxFrameSize();\n FramePartsCollectorListener collector_;\n std::unique_ptr decoder_;\n};\nTEST_F(Http2FrameDecoderTest, DataEmpty) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x00', \n '\\x00', \n '\\x00', '\\x00', '\\x00',\n '\\x00', \n };\n Http2FrameHeader header(0, Http2FrameType::DATA, 0, 0);\n FrameParts expected(header, \"\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeadersEmpty) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x01', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x01', \n };\n Http2FrameHeader header(0, Http2FrameType::HEADERS, 0, 1);\n FrameParts expected(header, \"\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, Priority) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x05', \n '\\x02', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x80', '\\x00', '\\x00', '\\x01', \n '\\x10', \n };\n Http2FrameHeader header(5, Http2FrameType::PRIORITY, 0, 2);\n FrameParts expected(header);\n expected.SetOptPriority(Http2PriorityFields(1, 17, true));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, RstStream) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x04', \n '\\x03', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x00', '\\x00', '\\x00', '\\x01', \n };\n Http2FrameHeader header(4, Http2FrameType::RST_STREAM, 0, 1);\n FrameParts expected(header);\n expected.SetOptRstStreamErrorCode(Http2ErrorCode::PROTOCOL_ERROR);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, SettingsEmpty) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x04', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x01', \n };\n Http2FrameHeader header(0, Http2FrameType::SETTINGS, 0, 1);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, SettingsAck) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x04', \n '\\x01', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(0, Http2FrameType::SETTINGS, Http2FrameFlag::ACK, 0);\n FrameParts expected(header);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PushPromiseMinimal) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x04', \n '\\x05', \n '\\x04', \n '\\x00', '\\x00', '\\x00',\n '\\x02', \n '\\x00', '\\x00', '\\x00',\n '\\x01', \n };\n Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE,\n Http2FrameFlag::END_HEADERS, 2);\n FrameParts expected(header, \"\");\n expected.SetOptPushPromise(Http2PushPromiseFields{1});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, Ping) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x08', \n '\\x06', \n '\\xfe', \n '\\x00', '\\x00', '\\x00', '\\x00', \n 's', 'o', 'm', 'e', \n 'd', 'a', 't', 'a', \n };\n Http2FrameHeader header(8, Http2FrameType::PING, 0, 0);\n FrameParts expected(header);\n expected.SetOptPing(\n Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PingAck) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x08', \n '\\x06', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x00', \n 's', 'o', 'm', 'e', \n 'd', 'a', 't', 'a', \n };\n Http2FrameHeader header(8, Http2FrameType::PING, Http2FrameFlag::ACK, 0);\n FrameParts expected(header);\n expected.SetOptPing(\n Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, GoAwayMinimal) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x08', \n '\\x07', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x80', '\\x00', '\\x00', '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x09', \n };\n Http2FrameHeader header(8, Http2FrameType::GOAWAY, 0, 1);\n FrameParts expected(header);\n expected.SetOptGoaway(\n Http2GoAwayFields(255, Http2ErrorCode::COMPRESSION_ERROR));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, WindowUpdate) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x04', \n '\\x08', \n '\\x0f', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x80', '\\x00', '\\x04', '\\x00', \n };\n Http2FrameHeader header(4, Http2FrameType::WINDOW_UPDATE, 0, 1);\n FrameParts expected(header);\n expected.SetOptWindowUpdateIncrement(1024);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, ContinuationEmpty) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x09', \n '\\x00', \n '\\x00', '\\x00', '\\x00',\n '\\x00', \n };\n Http2FrameHeader header(0, Http2FrameType::CONTINUATION, 0, 0);\n FrameParts expected(header);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, AltSvcMinimal) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x02', \n '\\x0a', \n '\\xff', \n '\\x00', '\\x00', '\\x00',\n '\\x00', \n '\\x00', '\\x00', \n };\n Http2FrameHeader header(2, Http2FrameType::ALTSVC, 0, 0);\n FrameParts expected(header);\n expected.SetOptAltsvcOriginLength(0);\n expected.SetOptAltsvcValueLength(0);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, UnknownEmpty) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x20', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(0, static_cast(32), 0xff, 0);\n FrameParts expected(header);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, DataPayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x03', \n '\\x00', \n '\\x80', \n '\\x00', '\\x00', '\\x02', '\\x02', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(3, Http2FrameType::DATA, 0, 514);\n FrameParts expected(header, \"abc\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeadersPayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x03', \n '\\x01', \n '\\x05', \n '\\x00', '\\x00', '\\x00', '\\x02', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(\n 3, Http2FrameType::HEADERS,\n Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS, 2);\n FrameParts expected(header, \"abc\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeadersPriority) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x05', \n '\\x01', \n '\\x20', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\xff', \n };\n Http2FrameHeader header(5, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY,\n 2);\n FrameParts expected(header);\n expected.SetOptPriority(Http2PriorityFields(1, 256, false));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, Settings) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x0c', \n '\\x04', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x00', \n '\\x00', '\\x04', \n '\\x0a', '\\x0b', '\\x0c', '\\x0d', \n '\\x00', '\\x02', \n '\\x00', '\\x00', '\\x00', '\\x03', \n };\n Http2FrameHeader header(12, Http2FrameType::SETTINGS, 0, 0);\n FrameParts expected(header);\n expected.AppendSetting(Http2SettingFields(\n Http2SettingsParameter::INITIAL_WINDOW_SIZE, 168496141));\n expected.AppendSetting(\n Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PushPromisePayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', 7, \n '\\x05', \n '\\x04', \n '\\x00', '\\x00', '\\x00', '\\xff', \n '\\x00', '\\x00', '\\x01', '\\x00', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(7, Http2FrameType::PUSH_PROMISE,\n Http2FrameFlag::END_HEADERS, 255);\n FrameParts expected(header, \"abc\");\n expected.SetOptPushPromise(Http2PushPromiseFields{256});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, GoAwayOpaqueData) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x0e', \n '\\x07', \n '\\xff', \n '\\x80', '\\x00', '\\x00', '\\x00', \n '\\x00', '\\x00', '\\x01', '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x03', \n 'o', 'p', 'a', 'q', 'u', 'e',\n };\n Http2FrameHeader header(14, Http2FrameType::GOAWAY, 0, 0);\n FrameParts expected(header, \"opaque\");\n expected.SetOptGoaway(\n Http2GoAwayFields(256, Http2ErrorCode::FLOW_CONTROL_ERROR));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, ContinuationPayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x03', \n '\\x09', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x02', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(3, Http2FrameType::CONTINUATION,\n Http2FrameFlag::END_HEADERS, 2);\n FrameParts expected(header, \"abc\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, AltSvcPayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x08', \n '\\x0a', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x00', '\\x03', \n 'a', 'b', 'c', \n 'd', 'e', 'f', \n };\n Http2FrameHeader header(8, Http2FrameType::ALTSVC, 0, 2);\n FrameParts expected(header);\n expected.SetAltSvcExpected(\"abc\", \"def\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PriorityUpdatePayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x07', \n '\\x10', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x05', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(7, Http2FrameType::PRIORITY_UPDATE, 0, 0);\n FrameParts expected(header, \"abc\");\n expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{5});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, UnknownPayload) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x03', \n '\\x30', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x02', \n 'a', 'b', 'c', \n };\n Http2FrameHeader header(3, static_cast(48), 0, 2);\n FrameParts expected(header, \"abc\");\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, DataPayloadAndPadding) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x07', \n '\\x00', \n '\\x09', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x03', \n 'a', 'b', 'c', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(7, Http2FrameType::DATA,\n Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED,\n 2);\n size_t total_pad_length = 4; \n FrameParts expected(header, \"abc\", total_pad_length);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeadersPayloadAndPadding) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x07', \n '\\x01', \n '\\x08', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x03', \n 'a', 'b', 'c', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(7, Http2FrameType::HEADERS, Http2FrameFlag::PADDED,\n 2);\n size_t total_pad_length = 4; \n FrameParts expected(header, \"abc\", total_pad_length);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeadersPayloadPriorityAndPadding) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x0c', \n '\\x01', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x03', \n '\\x80', '\\x00', '\\x00', '\\x01', \n '\\x10', \n 'a', 'b', 'c', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(12, Http2FrameType::HEADERS,\n Http2FrameFlag::END_STREAM |\n Http2FrameFlag::END_HEADERS |\n Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY,\n 2);\n size_t total_pad_length = 4; \n FrameParts expected(header, \"abc\", total_pad_length);\n expected.SetOptPriority(Http2PriorityFields(1, 17, true));\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PushPromisePayloadAndPadding) {\n const char kFrameData[] = {\n '\\x00', '\\x00', 11, \n '\\x05', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x03', \n '\\x00', '\\x00', '\\x00', '\\x02', \n 'a', 'b', 'c', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(11, Http2FrameType::PUSH_PROMISE,\n Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED,\n 1);\n size_t total_pad_length = 4; \n FrameParts expected(header, \"abc\", total_pad_length);\n expected.SetOptPushPromise(Http2PushPromiseFields{2});\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, DataMissingPadLengthField) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x00', \n '\\x08', \n '\\x00', '\\x00', '\\x00', '\\x01', \n };\n Http2FrameHeader header(0, Http2FrameType::DATA, Http2FrameFlag::PADDED, 1);\n FrameParts expected(header);\n expected.SetOptMissingLength(1);\n EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeaderPaddingTooLong) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x02', \n '\\x01', \n '\\x08', \n '\\x00', '\\x01', '\\x00', '\\x00', \n '\\xff', \n '\\x00', \n };\n Http2FrameHeader header(2, Http2FrameType::HEADERS, Http2FrameFlag::PADDED,\n 65536);\n FrameParts expected(header);\n expected.SetOptMissingLength(254);\n EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, HeaderMissingPriority) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x04', \n '\\x01', \n '\\x20', \n '\\x00', '\\x01', '\\x00', '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(4, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY,\n 65536);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, PriorityTooShort) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x04', \n '\\x02', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x02', \n '\\x80', '\\x00', '\\x00', '\\x01', \n };\n Http2FrameHeader header(4, Http2FrameType::PRIORITY, 0, 2);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, RstStreamTooShort) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x03', \n '\\x03', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(3, Http2FrameType::RST_STREAM, 0, 1);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, SettingsWrongSize) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x09', \n '\\x04', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x00', \n '\\x00', '\\x02', \n '\\x00', '\\x00', '\\x00', '\\x03', \n '\\x00', '\\x04', \n '\\x00', \n };\n Http2FrameHeader header(9, Http2FrameType::SETTINGS, 0, 0);\n FrameParts expected(header);\n expected.AppendSetting(\n Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3));\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, expected));\n}\nTEST_F(Http2FrameDecoderTest, PushPromiseTooShort) {\n const char kFrameData[] = {\n '\\x00', '\\x00', 3, \n '\\x05', \n '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(3, Http2FrameType::PUSH_PROMISE, 0, 1);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, PushPromisePaddedTruncatedPromise) {\n const char kFrameData[] = {\n '\\x00', '\\x00', 4, \n '\\x05', \n '\\x08', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x00', \n '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE,\n Http2FrameFlag::PADDED, 1);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, PingTooShort) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x07', \n '\\x06', \n '\\xfe', \n '\\x00', '\\x00', '\\x00', '\\x00', \n 's', 'o', 'm', 'e', \n 'd', 'a', 't', \n };\n Http2FrameHeader header(7, Http2FrameType::PING, 0, 0);\n EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));\n}\nTEST_F(Http2FrameDecoderTest, GoAwayTooShort) {\n const char kFrameData[] = {\n '\\x00', '\\x00', '\\x00', \n '\\x07', \n '\\xff', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n Http2FrameHeader header(0,"}}},{"rowIdx":417,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_DECODE_BUFFER_H_\n#define QUICHE_HTTP2_DECODER_DECODE_BUFFER_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nclass DecodeBufferSubset;\nclass QUICHE_EXPORT DecodeBuffer {\n public:\n static constexpr size_t kMaxDecodeBufferLength = 1 << 25;\n DecodeBuffer(const char* buffer, size_t len)\n : buffer_(buffer), cursor_(buffer), beyond_(buffer + len) {\n QUICHE_DCHECK(buffer != nullptr);\n QUICHE_DCHECK_LE(len, kMaxDecodeBufferLength);\n }\n explicit DecodeBuffer(absl::string_view s)\n : DecodeBuffer(s.data(), s.size()) {}\n template \n explicit DecodeBuffer(const char (&buf)[N]) : DecodeBuffer(buf, N) {}\n DecodeBuffer(const DecodeBuffer&) = delete;\n DecodeBuffer operator=(const DecodeBuffer&) = delete;\n bool Empty() const { return cursor_ >= beyond_; }\n bool HasData() const { return cursor_ < beyond_; }\n size_t Remaining() const {\n QUICHE_DCHECK_LE(cursor_, beyond_);\n return beyond_ - cursor_;\n }\n size_t Offset() const { return cursor_ - buffer_; }\n size_t FullSize() const { return beyond_ - buffer_; }\n size_t MinLengthRemaining(size_t length) const {\n return std::min(length, Remaining());\n }\n const char* cursor() const { return cursor_; }\n void AdvanceCursor(size_t amount) {\n QUICHE_DCHECK_LE(amount,\n Remaining()); \n QUICHE_DCHECK_EQ(subset_, nullptr)\n << \"Access via subset only when present.\";\n cursor_ += amount;\n }\n char DecodeChar() {\n QUICHE_DCHECK_LE(1u, Remaining()); \n QUICHE_DCHECK_EQ(subset_, nullptr)\n << \"Access via subset only when present.\";\n return *cursor_++;\n }\n uint8_t DecodeUInt8();\n uint16_t DecodeUInt16();\n uint32_t DecodeUInt24();\n uint32_t DecodeUInt31();\n uint32_t DecodeUInt32();\n protected:\n#ifndef NDEBUG\n void set_subset_of_base(DecodeBuffer* base, const DecodeBufferSubset* subset);\n void clear_subset_of_base(DecodeBuffer* base,\n const DecodeBufferSubset* subset);\n#endif\n private:\n#ifndef NDEBUG\n void set_subset(const DecodeBufferSubset* subset);\n void clear_subset(const DecodeBufferSubset* subset);\n#endif\n static void* operator new(size_t s);\n static void* operator new[](size_t s);\n static void operator delete(void* p);\n static void operator delete[](void* p);\n const char* const buffer_;\n const char* cursor_;\n const char* const beyond_;\n const DecodeBufferSubset* subset_ = nullptr; \n};\nclass QUICHE_EXPORT DecodeBufferSubset : public DecodeBuffer {\n public:\n DecodeBufferSubset(DecodeBuffer* base, size_t subset_len)\n : DecodeBuffer(base->cursor(), base->MinLengthRemaining(subset_len)),\n base_buffer_(base) {\n#ifndef NDEBUG\n DebugSetup();\n#endif\n }\n DecodeBufferSubset(const DecodeBufferSubset&) = delete;\n DecodeBufferSubset operator=(const DecodeBufferSubset&) = delete;\n ~DecodeBufferSubset() {\n size_t offset = Offset();\n#ifndef NDEBUG\n DebugTearDown();\n#endif\n base_buffer_->AdvanceCursor(offset);\n }\n private:\n DecodeBuffer* const base_buffer_;\n#ifndef NDEBUG\n size_t start_base_offset_; \n size_t max_base_offset_; \n void DebugSetup();\n void DebugTearDown();\n#endif\n};\n} \n#endif \n#include \"quiche/http2/decoder/decode_buffer.h\"\nnamespace http2 {\nuint8_t DecodeBuffer::DecodeUInt8() {\n return static_cast(DecodeChar());\n}\nuint16_t DecodeBuffer::DecodeUInt16() {\n QUICHE_DCHECK_LE(2u, Remaining());\n const uint8_t b1 = DecodeUInt8();\n const uint8_t b2 = DecodeUInt8();\n return b1 << 8 | b2;\n}\nuint32_t DecodeBuffer::DecodeUInt24() {\n QUICHE_DCHECK_LE(3u, Remaining());\n const uint8_t b1 = DecodeUInt8();\n const uint8_t b2 = DecodeUInt8();\n const uint8_t b3 = DecodeUInt8();\n return b1 << 16 | b2 << 8 | b3;\n}\nuint32_t DecodeBuffer::DecodeUInt31() {\n QUICHE_DCHECK_LE(4u, Remaining());\n const uint8_t b1 = DecodeUInt8() & 0x7f; \n const uint8_t b2 = DecodeUInt8();\n const uint8_t b3 = DecodeUInt8();\n const uint8_t b4 = DecodeUInt8();\n return b1 << 24 | b2 << 16 | b3 << 8 | b4;\n}\nuint32_t DecodeBuffer::DecodeUInt32() {\n QUICHE_DCHECK_LE(4u, Remaining());\n const uint8_t b1 = DecodeUInt8();\n const uint8_t b2 = DecodeUInt8();\n const uint8_t b3 = DecodeUInt8();\n const uint8_t b4 = DecodeUInt8();\n return b1 << 24 | b2 << 16 | b3 << 8 | b4;\n}\n#ifndef NDEBUG\nvoid DecodeBuffer::set_subset_of_base(DecodeBuffer* base,\n const DecodeBufferSubset* subset) {\n QUICHE_DCHECK_EQ(this, subset);\n base->set_subset(subset);\n}\nvoid DecodeBuffer::clear_subset_of_base(DecodeBuffer* base,\n const DecodeBufferSubset* subset) {\n QUICHE_DCHECK_EQ(this, subset);\n base->clear_subset(subset);\n}\nvoid DecodeBuffer::set_subset(const DecodeBufferSubset* subset) {\n QUICHE_DCHECK(subset != nullptr);\n QUICHE_DCHECK_EQ(subset_, nullptr) << \"There is already a subset\";\n subset_ = subset;\n}\nvoid DecodeBuffer::clear_subset(const DecodeBufferSubset* subset) {\n QUICHE_DCHECK(subset != nullptr);\n QUICHE_DCHECK_EQ(subset_, subset);\n subset_ = nullptr;\n}\nvoid DecodeBufferSubset::DebugSetup() {\n start_base_offset_ = base_buffer_->Offset();\n max_base_offset_ = start_base_offset_ + FullSize();\n QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize());\n set_subset_of_base(base_buffer_, this);\n}\nvoid DecodeBufferSubset::DebugTearDown() {\n QUICHE_DCHECK_EQ(start_base_offset_, base_buffer_->Offset())\n << \"The base buffer was modified\";\n size_t offset = Offset();\n QUICHE_DCHECK_LE(offset, FullSize());\n QUICHE_DCHECK_LE(start_base_offset_ + offset, max_base_offset_);\n QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize());\n clear_subset_of_base(base_buffer_, this);\n}\n#endif\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nenum class TestEnumClass32 {\n kValue1 = 1,\n kValue99 = 99,\n kValue1M = 1000000,\n};\nenum class TestEnumClass8 {\n kValue1 = 1,\n kValue2 = 1,\n kValue99 = 99,\n kValue255 = 255,\n};\nenum TestEnum8 {\n kMaskLo = 0x01,\n kMaskHi = 0x80,\n};\nstruct TestStruct {\n uint8_t f1;\n uint16_t f2;\n uint32_t f3; \n uint32_t f4;\n uint32_t f5; \n TestEnumClass32 f6;\n TestEnumClass8 f7;\n TestEnum8 f8;\n};\nclass DecodeBufferTest : public quiche::test::QuicheTest {\n protected:\n Http2Random random_;\n uint32_t decode_offset_;\n};\nTEST_F(DecodeBufferTest, DecodesFixedInts) {\n const char data[] = \"\\x01\\x12\\x23\\x34\\x45\\x56\\x67\\x78\\x89\\x9a\";\n DecodeBuffer b1(data, strlen(data));\n EXPECT_EQ(1, b1.DecodeUInt8());\n EXPECT_EQ(0x1223u, b1.DecodeUInt16());\n EXPECT_EQ(0x344556u, b1.DecodeUInt24());\n EXPECT_EQ(0x6778899Au, b1.DecodeUInt32());\n}\nTEST_F(DecodeBufferTest, HasNotCopiedInput) {\n const char data[] = \"ab\";\n DecodeBuffer b1(data, 2);\n EXPECT_EQ(2u, b1.Remaining());\n EXPECT_EQ(0u, b1.Offset());\n EXPECT_FALSE(b1.Empty());\n EXPECT_EQ(data, b1.cursor()); \n EXPECT_TRUE(b1.HasData());\n b1.AdvanceCursor(1);\n EXPECT_EQ(1u, b1.Remaining());\n EXPECT_EQ(1u, b1.Offset());\n EXPECT_FALSE(b1.Empty());\n EXPECT_EQ(&data[1], b1.cursor());\n EXPECT_TRUE(b1.HasData());\n b1.AdvanceCursor(1);\n EXPECT_EQ(0u, b1.Remaining());\n EXPECT_EQ(2u, b1.Offset());\n EXPECT_TRUE(b1.Empty());\n EXPECT_EQ(&data[2], b1.cursor());\n EXPECT_FALSE(b1.HasData());\n DecodeBuffer b2(data, 0);\n EXPECT_EQ(0u, b2.Remaining());\n EXPECT_EQ(0u, b2.Offset());\n EXPECT_TRUE(b2.Empty());\n EXPECT_EQ(data, b2.cursor());\n EXPECT_FALSE(b2.HasData());\n}\nTEST_F(DecodeBufferTest, DecodeBufferSubsetLimited) {\n const char data[] = \"abc\";\n DecodeBuffer base(data, 3);\n base.AdvanceCursor(1);\n DecodeBufferSubset subset(&base, 100);\n EXPECT_EQ(2u, subset.FullSize());\n}\nTEST_F(DecodeBufferTest, DecodeBufferSubsetAdvancesCursor) {\n const char data[] = \"abc\";\n const size_t size = sizeof(data) - 1;\n EXPECT_EQ(3u, size);\n DecodeBuffer base(data, size);\n {\n DecodeBufferSubset subset(&base, size + 100);\n EXPECT_EQ(size, subset.FullSize());\n EXPECT_EQ(base.FullSize(), subset.FullSize());\n EXPECT_EQ(0u, subset.Offset());\n }\n EXPECT_EQ(0u, base.Offset());\n EXPECT_EQ(size, base.Remaining());\n}\n#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG)\nTEST(DecodeBufferDeathTest, NonNullBufferRequired) {\n EXPECT_QUICHE_DEBUG_DEATH({ DecodeBuffer b(nullptr, 3); }, \"nullptr\");\n}\nTEST(DecodeBufferDeathTest, ModestBufferSizeRequired) {\n EXPECT_QUICHE_DEBUG_DEATH(\n {\n constexpr size_t kLength = DecodeBuffer::kMaxDecodeBufferLength + 1;\n auto data = std::make_unique(kLength);\n DecodeBuffer b(data.get(), kLength);\n },\n \"Max.*Length\");\n}\nTEST(DecodeBufferDeathTest, LimitedAdvance) {\n {\n const char data[] = \"abc\";\n DecodeBuffer b(data, 3);\n b.AdvanceCursor(3); \n EXPECT_TRUE(b.Empty());\n }\n EXPECT_QUICHE_DEBUG_DEATH(\n {\n const char data[] = \"abc\";\n DecodeBuffer b(data, 3);\n b.AdvanceCursor(4);\n },\n \"Remaining\");\n}\nTEST(DecodeBufferDeathTest, DecodeUInt8PastEnd) {\n const char data[] = {0x12, 0x23};\n DecodeBuffer b(data, sizeof data);\n EXPECT_EQ(2u, b.FullSize());\n EXPECT_EQ(0x1223, b.DecodeUInt16());\n EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt8(); }, \"Remaining\");\n}\nTEST(DecodeBufferDeathTest, DecodeUInt16OverEnd) {\n const char data[] = {0x12, 0x23, 0x34};\n DecodeBuffer b(data, sizeof data);\n EXPECT_EQ(3u, b.FullSize());\n EXPECT_EQ(0x1223, b.DecodeUInt16());\n EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt16(); }, \"Remaining\");\n}\nTEST(DecodeBufferSubsetDeathTest, TwoSubsets) {\n const char data[] = \"abc\";\n DecodeBuffer base(data, 3);\n DecodeBufferSubset subset1(&base, 1);\n EXPECT_QUICHE_DEBUG_DEATH({ DecodeBufferSubset subset2(&base, 1); },\n \"There is already a subset\");\n}\nTEST(DecodeBufferSubsetDeathTest, BaseCursorAdvanced) {\n const char data[] = \"abc\";\n DecodeBuffer base(data, 3);\n base.AdvanceCursor(1);\n EXPECT_QUICHE_DEBUG_DEATH(\n {\n DecodeBufferSubset subset1(&base, 2);\n base.AdvanceCursor(1);\n },\n \"Access via subset only when present\");\n}\n#endif \n} \n} \n} "}}},{"rowIdx":418,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_HTTP2_STRUCTURE_DECODER_H_\n#define QUICHE_HTTP2_DECODER_HTTP2_STRUCTURE_DECODER_H_\n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_http2_structures.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace test {\nclass Http2StructureDecoderPeer;\n} \nclass QUICHE_EXPORT Http2StructureDecoder {\n public:\n template \n bool Start(S* out, DecodeBuffer* db) {\n static_assert(S::EncodedSize() <= sizeof buffer_, \"buffer_ is too small\");\n QUICHE_DVLOG(2) << __func__ << \"@\" << this\n << \": db->Remaining=\" << db->Remaining()\n << \"; EncodedSize=\" << S::EncodedSize();\n if (db->Remaining() >= S::EncodedSize()) {\n DoDecode(out, db);\n return true;\n }\n IncompleteStart(db, S::EncodedSize());\n return false;\n }\n template \n bool Resume(S* out, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << __func__ << \"@\" << this << \": offset_=\" << offset_\n << \"; db->Remaining=\" << db->Remaining();\n if (ResumeFillingBuffer(db, S::EncodedSize())) {\n QUICHE_DVLOG(2) << __func__ << \"@\" << this << \" offset_=\" << offset_\n << \" Ready to decode from buffer_.\";\n DecodeBuffer buffer_db(buffer_, S::EncodedSize());\n DoDecode(out, &buffer_db);\n return true;\n }\n QUICHE_DCHECK_LT(offset_, S::EncodedSize());\n return false;\n }\n template \n DecodeStatus Start(S* out, DecodeBuffer* db, uint32_t* remaining_payload) {\n static_assert(S::EncodedSize() <= sizeof buffer_, \"buffer_ is too small\");\n QUICHE_DVLOG(2) << __func__ << \"@\" << this\n << \": *remaining_payload=\" << *remaining_payload\n << \"; db->Remaining=\" << db->Remaining()\n << \"; EncodedSize=\" << S::EncodedSize();\n if (db->MinLengthRemaining(*remaining_payload) >= S::EncodedSize()) {\n DoDecode(out, db);\n *remaining_payload -= S::EncodedSize();\n return DecodeStatus::kDecodeDone;\n }\n return IncompleteStart(db, remaining_payload, S::EncodedSize());\n }\n template \n bool Resume(S* out, DecodeBuffer* db, uint32_t* remaining_payload) {\n QUICHE_DVLOG(3) << __func__ << \"@\" << this << \": offset_=\" << offset_\n << \"; *remaining_payload=\" << *remaining_payload\n << \"; db->Remaining=\" << db->Remaining()\n << \"; EncodedSize=\" << S::EncodedSize();\n if (ResumeFillingBuffer(db, remaining_payload, S::EncodedSize())) {\n QUICHE_DVLOG(2) << __func__ << \"@\" << this << \": offset_=\" << offset_\n << \"; Ready to decode from buffer_.\";\n DecodeBuffer buffer_db(buffer_, S::EncodedSize());\n DoDecode(out, &buffer_db);\n return true;\n }\n QUICHE_DCHECK_LT(offset_, S::EncodedSize());\n return false;\n }\n uint32_t offset() const { return offset_; }\n private:\n friend class test::Http2StructureDecoderPeer;\n uint32_t IncompleteStart(DecodeBuffer* db, uint32_t target_size);\n DecodeStatus IncompleteStart(DecodeBuffer* db, uint32_t* remaining_payload,\n uint32_t target_size);\n bool ResumeFillingBuffer(DecodeBuffer* db, uint32_t target_size);\n bool ResumeFillingBuffer(DecodeBuffer* db, uint32_t* remaining_payload,\n uint32_t target_size);\n uint32_t offset_;\n char buffer_[Http2FrameHeader::EncodedSize()];\n};\n} \n#endif \n#include \"quiche/http2/decoder/http2_structure_decoder.h\"\n#include \n#include \n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\nnamespace http2 {\nuint32_t Http2StructureDecoder::IncompleteStart(DecodeBuffer* db,\n uint32_t target_size) {\n if (target_size > sizeof buffer_) {\n QUICHE_BUG(http2_bug_154_1)\n << \"target_size too large for buffer: \" << target_size;\n return 0;\n }\n const uint32_t num_to_copy = db->MinLengthRemaining(target_size);\n memcpy(buffer_, db->cursor(), num_to_copy);\n offset_ = num_to_copy;\n db->AdvanceCursor(num_to_copy);\n return num_to_copy;\n}\nDecodeStatus Http2StructureDecoder::IncompleteStart(DecodeBuffer* db,\n uint32_t* remaining_payload,\n uint32_t target_size) {\n QUICHE_DVLOG(1) << \"IncompleteStart@\" << this\n << \": *remaining_payload=\" << *remaining_payload\n << \"; target_size=\" << target_size\n << \"; db->Remaining=\" << db->Remaining();\n *remaining_payload -=\n IncompleteStart(db, std::min(target_size, *remaining_payload));\n if (*remaining_payload > 0 && db->Empty()) {\n return DecodeStatus::kDecodeInProgress;\n }\n QUICHE_DVLOG(1) << \"IncompleteStart: kDecodeError\";\n return DecodeStatus::kDecodeError;\n}\nbool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db,\n uint32_t target_size) {\n QUICHE_DVLOG(2) << \"ResumeFillingBuffer@\" << this\n << \": target_size=\" << target_size << \"; offset_=\" << offset_\n << \"; db->Remaining=\" << db->Remaining();\n if (target_size < offset_) {\n QUICHE_BUG(http2_bug_154_2)\n << \"Already filled buffer_! target_size=\" << target_size\n << \" offset_=\" << offset_;\n return false;\n }\n const uint32_t needed = target_size - offset_;\n const uint32_t num_to_copy = db->MinLengthRemaining(needed);\n QUICHE_DVLOG(2) << \"ResumeFillingBuffer num_to_copy=\" << num_to_copy;\n memcpy(&buffer_[offset_], db->cursor(), num_to_copy);\n db->AdvanceCursor(num_to_copy);\n offset_ += num_to_copy;\n return needed == num_to_copy;\n}\nbool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db,\n uint32_t* remaining_payload,\n uint32_t target_size) {\n QUICHE_DVLOG(2) << \"ResumeFillingBuffer@\" << this\n << \": target_size=\" << target_size << \"; offset_=\" << offset_\n << \"; *remaining_payload=\" << *remaining_payload\n << \"; db->Remaining=\" << db->Remaining();\n if (target_size < offset_) {\n QUICHE_BUG(http2_bug_154_3)\n << \"Already filled buffer_! target_size=\" << target_size\n << \" offset_=\" << offset_;\n return false;\n }\n const uint32_t needed = target_size - offset_;\n const uint32_t num_to_copy =\n db->MinLengthRemaining(std::min(needed, *remaining_payload));\n QUICHE_DVLOG(2) << \"ResumeFillingBuffer num_to_copy=\" << num_to_copy;\n memcpy(&buffer_[offset_], db->cursor(), num_to_copy);\n db->AdvanceCursor(num_to_copy);\n offset_ += num_to_copy;\n *remaining_payload -= num_to_copy;\n return needed == num_to_copy;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/http2_structure_decoder.h\"\n#include \n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nnamespace {\nconst bool kMayReturnZeroOnFirst = false;\ntemplate \nclass Http2StructureDecoderTest : public RandomDecoderTest {\n protected:\n typedef S Structure;\n Http2StructureDecoderTest() {\n stop_decode_on_done_ = true;\n }\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n structure_ = std::make_unique();\n uint32_t old_remaining = b->Remaining();\n if (structure_decoder_.Start(structure_.get(), b)) {\n EXPECT_EQ(old_remaining - S::EncodedSize(), b->Remaining());\n ++fast_decode_count_;\n return DecodeStatus::kDecodeDone;\n } else {\n EXPECT_LT(structure_decoder_.offset(), S::EncodedSize());\n EXPECT_EQ(0u, b->Remaining());\n EXPECT_EQ(old_remaining - structure_decoder_.offset(), b->Remaining());\n ++incomplete_start_count_;\n return DecodeStatus::kDecodeInProgress;\n }\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n uint32_t old_offset = structure_decoder_.offset();\n EXPECT_LT(old_offset, S::EncodedSize());\n uint32_t avail = b->Remaining();\n if (structure_decoder_.Resume(structure_.get(), b)) {\n EXPECT_LE(S::EncodedSize(), old_offset + avail);\n EXPECT_EQ(b->Remaining(), avail - (S::EncodedSize() - old_offset));\n ++slow_decode_count_;\n return DecodeStatus::kDecodeDone;\n } else {\n EXPECT_LT(structure_decoder_.offset(), S::EncodedSize());\n EXPECT_EQ(0u, b->Remaining());\n EXPECT_GT(S::EncodedSize(), old_offset + avail);\n ++incomplete_resume_count_;\n return DecodeStatus::kDecodeInProgress;\n }\n }\n AssertionResult DecodeLeadingStructure(const S* expected,\n absl::string_view data) {\n HTTP2_VERIFY_LE(S::EncodedSize(), data.size());\n DecodeBuffer original(data);\n Validator validator;\n if (expected != nullptr) {\n validator = [expected, this](const DecodeBuffer& ,\n DecodeStatus ) -> AssertionResult {\n HTTP2_VERIFY_EQ(*expected, *structure_);\n return AssertionSuccess();\n };\n }\n validator = ValidateDoneAndOffset(S::EncodedSize(), std::move(validator));\n fast_decode_count_ = 0;\n slow_decode_count_ = 0;\n incomplete_start_count_ = 0;\n incomplete_resume_count_ = 0;\n HTTP2_VERIFY_SUCCESS(DecodeAndValidateSeveralWays(\n &original, kMayReturnZeroOnFirst, validator));\n HTTP2_VERIFY_FALSE(HasFailure());\n HTTP2_VERIFY_EQ(S::EncodedSize(), structure_decoder_.offset());\n HTTP2_VERIFY_EQ(S::EncodedSize(), original.Offset());\n HTTP2_VERIFY_LT(0u, fast_decode_count_);\n HTTP2_VERIFY_LT(0u, slow_decode_count_);\n HTTP2_VERIFY_LT(0u, incomplete_start_count_);\n if (S::EncodedSize() >= 2) {\n HTTP2_VERIFY_LE(0u, incomplete_resume_count_);\n } else {\n HTTP2_VERIFY_EQ(0u, incomplete_resume_count_);\n }\n if (expected != nullptr) {\n QUICHE_DVLOG(1) << \"DecodeLeadingStructure expected: \" << *expected;\n QUICHE_DVLOG(1) << \"DecodeLeadingStructure actual: \" << *structure_;\n HTTP2_VERIFY_EQ(*expected, *structure_);\n }\n return AssertionSuccess();\n }\n template \n AssertionResult DecodeLeadingStructure(const char (&data)[N]) {\n return DecodeLeadingStructure(nullptr, absl::string_view(data, N));\n }\n template \n AssertionResult DecodeLeadingStructure(const unsigned char (&data)[N]) {\n return DecodeLeadingStructure(nullptr, ToStringPiece(data));\n }\n AssertionResult EncodeThenDecode(const S& in_s) {\n std::string bytes = SerializeStructure(in_s);\n HTTP2_VERIFY_EQ(S::EncodedSize(), bytes.size());\n return DecodeLeadingStructure(&in_s, bytes);\n }\n AssertionResult TestDecodingRandomizedStructures(size_t count) {\n for (size_t i = 0; i < count; ++i) {\n Structure input;\n Randomize(&input, RandomPtr());\n HTTP2_VERIFY_SUCCESS(EncodeThenDecode(input));\n }\n return AssertionSuccess();\n }\n AssertionResult TestDecodingRandomizedStructures() {\n HTTP2_VERIFY_SUCCESS(TestDecodingRandomizedStructures(100));\n return AssertionSuccess();\n }\n uint32_t decode_offset_ = 0;\n std::unique_ptr structure_;\n Http2StructureDecoder structure_decoder_;\n size_t fast_decode_count_ = 0;\n size_t slow_decode_count_ = 0;\n size_t incomplete_start_count_ = 0;\n size_t incomplete_resume_count_ = 0;\n};\nclass Http2FrameHeaderDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2FrameHeaderDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x00, 0x05, \n 0x01, \n 0x08, \n 0x00, 0x00, 0x00, 0x01, \n 0x04, \n 0x00, 0x00, 0x00, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(5u, structure_->payload_length);\n EXPECT_EQ(Http2FrameType::HEADERS, structure_->type);\n EXPECT_EQ(Http2FrameFlag::PADDED, structure_->flags);\n EXPECT_EQ(1u, structure_->stream_id);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, \n 0xff, \n 0xff, \n 0xff, 0xff, 0xff, 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ((1u << 24) - 1u, structure_->payload_length);\n EXPECT_EQ(static_cast(255), structure_->type);\n EXPECT_EQ(255, structure_->flags);\n EXPECT_EQ(0x7FFFFFFFu, structure_->stream_id);\n }\n}\nTEST_F(Http2FrameHeaderDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2PriorityFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2PriorityFieldsDecoderTest, DecodesLiteral) {\n {\n const unsigned char kData[] = {\n 0x80, 0x00, 0x00, 0x05, \n 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(5u, structure_->stream_dependency);\n EXPECT_EQ(256u, structure_->weight);\n EXPECT_EQ(true, structure_->is_exclusive);\n }\n {\n const unsigned char kData[] = {\n 0x7f, 0xff, 0xff, 0xff, \n 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(StreamIdMask(), structure_->stream_dependency);\n EXPECT_EQ(1u, structure_->weight);\n EXPECT_FALSE(structure_->is_exclusive);\n }\n}\nTEST_F(Http2PriorityFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2RstStreamFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2RstStreamFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x00, 0x00, 0x01, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_TRUE(structure_->IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_->error_code);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_FALSE(structure_->IsSupportedErrorCode());\n EXPECT_EQ(static_cast(0xffffffff), structure_->error_code);\n }\n}\nTEST_F(Http2RstStreamFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2SettingFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2SettingFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x01, \n 0x00, 0x00, 0x40, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_TRUE(structure_->IsSupportedParameter());\n EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, structure_->parameter);\n EXPECT_EQ(1u << 14, structure_->value);\n }\n {\n const unsigned char kData[] = {\n 0x00, 0x00, \n 0xff, 0xff, 0xff, 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_FALSE(structure_->IsSupportedParameter());\n EXPECT_EQ(static_cast(0), structure_->parameter);\n }\n}\nTEST_F(Http2SettingFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2PushPromiseFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2PushPromiseFieldsDecoderTest, DecodesLiteral) {\n {\n const unsigned char kData[] = {\n 0x00, 0x01, 0x8a, 0x92, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(101010u, structure_->promised_stream_id);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, 0xff,\n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(StreamIdMask(), structure_->promised_stream_id);\n }\n}\nTEST_F(Http2PushPromiseFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2PingFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2PingFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));\n }\n {\n const char kData[] = {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));\n }\n}\nTEST_F(Http2PingFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2GoAwayFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2GoAwayFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x00, 0x00, 0x00, \n 0x00, 0x00, 0x00, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(0u, structure_->last_stream_id);\n EXPECT_TRUE(structure_->IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_->error_code);\n }\n {\n const char kData[] = {\n 0x00, 0x00, 0x00, 0x01, \n 0x00, 0x00, 0x00, 0x0d, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(1u, structure_->last_stream_id);\n EXPECT_TRUE(structure_->IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_->error_code);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, 0xff, \n 0xff, 0xff, 0xff, 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(StreamIdMask(), structure_->last_stream_id); \n EXPECT_FALSE(structure_->IsSupportedErrorCode());\n EXPECT_EQ(static_cast(0xffffffff), structure_->error_code);\n }\n}\nTEST_F(Http2GoAwayFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2WindowUpdateFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x01, 0x00, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(1u << 16, structure_->window_size_increment);\n }\n {\n const char kData[] = {\n 0x00, 0x00, 0x00, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(0u, structure_->window_size_increment);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, 0xff, 0xff,\n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(StreamIdMask(), structure_->window_size_increment);\n }\n}\nTEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\nclass Http2AltSvcFieldsDecoderTest\n : public Http2StructureDecoderTest {};\nTEST_F(Http2AltSvcFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n 0x00, 0x00, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(0, structure_->origin_length);\n }\n {\n const char kData[] = {\n 0x00, 0x14, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(20, structure_->origin_length);\n }\n {\n const unsigned char kData[] = {\n 0xff, 0xff, \n };\n ASSERT_TRUE(DecodeLeadingStructure(kData));\n EXPECT_EQ(65535, structure_->origin_length);\n }\n}\nTEST_F(Http2AltSvcFieldsDecoderTest, DecodesRandomized) {\n EXPECT_TRUE(TestDecodingRandomizedStructures());\n}\n} \n} \n} "}}},{"rowIdx":419,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_\n#define QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nQUICHE_EXPORT void DoDecode(Http2FrameHeader* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2PriorityFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2SettingFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2PingFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b);\nQUICHE_EXPORT void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b);\n} \n#endif \n#include \"quiche/http2/decoder/decode_http2_structures.h\"\n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nvoid DoDecode(Http2FrameHeader* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2FrameHeader::EncodedSize(), b->Remaining());\n out->payload_length = b->DecodeUInt24();\n out->type = static_cast(b->DecodeUInt8());\n out->flags = static_cast(b->DecodeUInt8());\n out->stream_id = b->DecodeUInt31();\n}\nvoid DoDecode(Http2PriorityFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2PriorityFields::EncodedSize(), b->Remaining());\n uint32_t stream_id_and_flag = b->DecodeUInt32();\n out->stream_dependency = stream_id_and_flag & StreamIdMask();\n if (out->stream_dependency == stream_id_and_flag) {\n out->is_exclusive = false;\n } else {\n out->is_exclusive = true;\n }\n out->weight = b->DecodeUInt8() + 1;\n}\nvoid DoDecode(Http2RstStreamFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2RstStreamFields::EncodedSize(), b->Remaining());\n out->error_code = static_cast(b->DecodeUInt32());\n}\nvoid DoDecode(Http2SettingFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2SettingFields::EncodedSize(), b->Remaining());\n out->parameter = static_cast(b->DecodeUInt16());\n out->value = b->DecodeUInt32();\n}\nvoid DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2PushPromiseFields::EncodedSize(), b->Remaining());\n out->promised_stream_id = b->DecodeUInt31();\n}\nvoid DoDecode(Http2PingFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2PingFields::EncodedSize(), b->Remaining());\n memcpy(out->opaque_bytes, b->cursor(), Http2PingFields::EncodedSize());\n b->AdvanceCursor(Http2PingFields::EncodedSize());\n}\nvoid DoDecode(Http2GoAwayFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2GoAwayFields::EncodedSize(), b->Remaining());\n out->last_stream_id = b->DecodeUInt31();\n out->error_code = static_cast(b->DecodeUInt32());\n}\nvoid DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2WindowUpdateFields::EncodedSize(), b->Remaining());\n out->window_size_increment = b->DecodeUInt31();\n}\nvoid DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2PriorityUpdateFields::EncodedSize(), b->Remaining());\n out->prioritized_stream_id = b->DecodeUInt31();\n}\nvoid DoDecode(Http2AltSvcFields* out, DecodeBuffer* b) {\n QUICHE_DCHECK_NE(nullptr, out);\n QUICHE_DCHECK_NE(nullptr, b);\n QUICHE_DCHECK_LE(Http2AltSvcFields::EncodedSize(), b->Remaining());\n out->origin_length = b->DecodeUInt16();\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/decode_http2_structures.h\"\n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\ntemplate \nabsl::string_view ToStringPiece(T (&data)[N]) {\n return absl::string_view(reinterpret_cast(data), N * sizeof(T));\n}\ntemplate \nstd::string SerializeStructure(const S& s) {\n Http2FrameBuilder fb;\n fb.Append(s);\n EXPECT_EQ(S::EncodedSize(), fb.size());\n return fb.buffer();\n}\ntemplate \nclass StructureDecoderTest : public quiche::test::QuicheTest {\n protected:\n typedef S Structure;\n StructureDecoderTest() : random_(), random_decode_count_(100) {}\n void Randomize(S* p) { ::http2::test::Randomize(p, &random_); }\n void DecodeLeadingStructure(const S* expected, absl::string_view data) {\n ASSERT_LE(S::EncodedSize(), data.size());\n DecodeBuffer db(data);\n Randomize(&structure_);\n DoDecode(&structure_, &db);\n EXPECT_EQ(db.Offset(), S::EncodedSize());\n if (expected != nullptr) {\n EXPECT_EQ(structure_, *expected);\n }\n }\n template \n void DecodeLeadingStructure(const char (&data)[N]) {\n DecodeLeadingStructure(nullptr, absl::string_view(data, N));\n }\n void EncodeThenDecode(const S& in_s) {\n std::string bytes = SerializeStructure(in_s);\n EXPECT_EQ(S::EncodedSize(), bytes.size());\n DecodeLeadingStructure(&in_s, bytes);\n }\n void TestDecodingRandomizedStructures(size_t count) {\n for (size_t i = 0; i < count && !HasFailure(); ++i) {\n Structure input;\n Randomize(&input);\n EncodeThenDecode(input);\n }\n }\n void TestDecodingRandomizedStructures() {\n TestDecodingRandomizedStructures(random_decode_count_);\n }\n Http2Random random_;\n const size_t random_decode_count_;\n uint32_t decode_offset_ = 0;\n S structure_;\n size_t fast_decode_count_ = 0;\n size_t slow_decode_count_ = 0;\n};\nclass FrameHeaderDecoderTest : public StructureDecoderTest {};\nTEST_F(FrameHeaderDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x05', \n '\\x01', \n '\\x08', \n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x04', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(5u, structure_.payload_length);\n EXPECT_EQ(Http2FrameType::HEADERS, structure_.type);\n EXPECT_EQ(Http2FrameFlag::PADDED, structure_.flags);\n EXPECT_EQ(1u, structure_.stream_id);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', '\\xff', \n '\\xff', \n '\\xff', \n '\\xff', '\\xff', '\\xff', '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ((1u << 24) - 1, structure_.payload_length);\n EXPECT_EQ(static_cast(255), structure_.type);\n EXPECT_EQ(255, structure_.flags);\n EXPECT_EQ(0x7FFFFFFFu, structure_.stream_id);\n }\n }\n}\nTEST_F(FrameHeaderDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass PriorityFieldsDecoderTest\n : public StructureDecoderTest {};\nTEST_F(PriorityFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x80', '\\x00', '\\x00', '\\x05', \n '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(5u, structure_.stream_dependency);\n EXPECT_EQ(256u, structure_.weight);\n EXPECT_EQ(true, structure_.is_exclusive);\n }\n }\n {\n const char kData[] = {\n '\\x7f', '\\xff',\n '\\xff', '\\xff', \n '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(StreamIdMask(), structure_.stream_dependency);\n EXPECT_EQ(1u, structure_.weight);\n EXPECT_FALSE(structure_.is_exclusive);\n }\n }\n}\nTEST_F(PriorityFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass RstStreamFieldsDecoderTest\n : public StructureDecoderTest {};\nTEST_F(RstStreamFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x00', '\\x01', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_TRUE(structure_.IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_.error_code);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', '\\xff',\n '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_FALSE(structure_.IsSupportedErrorCode());\n EXPECT_EQ(static_cast(0xffffffff), structure_.error_code);\n }\n }\n}\nTEST_F(RstStreamFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass SettingFieldsDecoderTest\n : public StructureDecoderTest {};\nTEST_F(SettingFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x01', \n '\\x00', '\\x00', '\\x40', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_TRUE(structure_.IsSupportedParameter());\n EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE,\n structure_.parameter);\n EXPECT_EQ(1u << 14, structure_.value);\n }\n }\n {\n const char kData[] = {\n '\\x00', '\\x00', \n '\\xff', '\\xff', '\\xff', '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_FALSE(structure_.IsSupportedParameter());\n EXPECT_EQ(static_cast(0), structure_.parameter);\n }\n }\n}\nTEST_F(SettingFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass PushPromiseFieldsDecoderTest\n : public StructureDecoderTest {};\nTEST_F(PushPromiseFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x01', '\\x8a', '\\x92', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(101010u, structure_.promised_stream_id);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', '\\xff',\n '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(StreamIdMask(), structure_.promised_stream_id);\n }\n }\n}\nTEST_F(PushPromiseFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass PingFieldsDecoderTest : public StructureDecoderTest {};\nTEST_F(PingFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\x07',\n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(absl::string_view(kData, 8),\n ToStringPiece(structure_.opaque_bytes));\n }\n }\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(absl::string_view(kData, 8),\n ToStringPiece(structure_.opaque_bytes));\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(absl::string_view(kData, 8),\n ToStringPiece(structure_.opaque_bytes));\n }\n }\n}\nTEST_F(PingFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass GoAwayFieldsDecoderTest : public StructureDecoderTest {\n};\nTEST_F(GoAwayFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x00', '\\x00', \n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(0u, structure_.last_stream_id);\n EXPECT_TRUE(structure_.IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_.error_code);\n }\n }\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x00', '\\x01', \n '\\x00', '\\x00', '\\x00', '\\x0d', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(1u, structure_.last_stream_id);\n EXPECT_TRUE(structure_.IsSupportedErrorCode());\n EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_.error_code);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff',\n '\\xff', '\\xff', \n '\\xff', '\\xff',\n '\\xff', '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(StreamIdMask(), structure_.last_stream_id); \n EXPECT_FALSE(structure_.IsSupportedErrorCode());\n EXPECT_EQ(static_cast(0xffffffff), structure_.error_code);\n }\n }\n}\nTEST_F(GoAwayFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass WindowUpdateFieldsDecoderTest\n : public StructureDecoderTest {};\nTEST_F(WindowUpdateFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x01', '\\x00', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(1u << 16, structure_.window_size_increment);\n }\n }\n {\n const char kData[] = {\n '\\x00', '\\x00', '\\x00', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(0u, structure_.window_size_increment);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', '\\xff', '\\xff',\n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(StreamIdMask(), structure_.window_size_increment);\n }\n }\n}\nTEST_F(WindowUpdateFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\nclass AltSvcFieldsDecoderTest : public StructureDecoderTest {\n};\nTEST_F(AltSvcFieldsDecoderTest, DecodesLiteral) {\n {\n const char kData[] = {\n '\\x00', '\\x00', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(0, structure_.origin_length);\n }\n }\n {\n const char kData[] = {\n '\\x00', '\\x14', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(20, structure_.origin_length);\n }\n }\n {\n const char kData[] = {\n '\\xff', '\\xff', \n };\n DecodeLeadingStructure(kData);\n if (!HasFailure()) {\n EXPECT_EQ(65535, structure_.origin_length);\n }\n }\n}\nTEST_F(AltSvcFieldsDecoderTest, DecodesRandomized) {\n TestDecodingRandomizedStructures();\n}\n} \n} \n} "}}},{"rowIdx":420,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_GOAWAY_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_GOAWAY_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass GoAwayPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT GoAwayPayloadDecoder {\n public:\n enum class PayloadState {\n kStartDecodingFixedFields,\n kHandleFixedFieldsStatus,\n kReadOpaqueData,\n kResumeDecodingFixedFields,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::GoAwayPayloadDecoderPeer;\n Http2GoAwayFields goaway_fields_;\n PayloadState payload_state_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n GoAwayPayloadDecoder::PayloadState v) {\n switch (v) {\n case GoAwayPayloadDecoder::PayloadState::kStartDecodingFixedFields:\n return out << \"kStartDecodingFixedFields\";\n case GoAwayPayloadDecoder::PayloadState::kHandleFixedFieldsStatus:\n return out << \"kHandleFixedFieldsStatus\";\n case GoAwayPayloadDecoder::PayloadState::kReadOpaqueData:\n return out << \"kReadOpaqueData\";\n case GoAwayPayloadDecoder::PayloadState::kResumeDecodingFixedFields:\n return out << \"kResumeDecodingFixedFields\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_167_1)\n << \"Invalid GoAwayPayloadDecoder::PayloadState: \" << unknown;\n return out << \"GoAwayPayloadDecoder::PayloadState(\" << unknown << \")\";\n}\nDecodeStatus GoAwayPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"GoAwayPayloadDecoder::StartDecodingPayload: \"\n << state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n QUICHE_DCHECK_EQ(0, state->frame_header().flags);\n state->InitializeRemainders();\n payload_state_ = PayloadState::kStartDecodingFixedFields;\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus GoAwayPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2)\n << \"GoAwayPayloadDecoder::ResumeDecodingPayload: remaining_payload=\"\n << state->remaining_payload() << \", db->Remaining=\" << db->Remaining();\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);\n QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_);\n DecodeStatus status = DecodeStatus::kDecodeError;\n size_t avail;\n while (true) {\n QUICHE_DVLOG(2)\n << \"GoAwayPayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n switch (payload_state_) {\n case PayloadState::kStartDecodingFixedFields:\n status = state->StartDecodingStructureInPayload(&goaway_fields_, db);\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kHandleFixedFieldsStatus:\n if (status == DecodeStatus::kDecodeDone) {\n state->listener()->OnGoAwayStart(frame_header, goaway_fields_);\n } else {\n QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError &&\n state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n payload_state_ = PayloadState::kResumeDecodingFixedFields;\n return status;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kReadOpaqueData:\n avail = db->Remaining();\n if (avail > 0) {\n state->listener()->OnGoAwayOpaqueData(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() > 0) {\n payload_state_ = PayloadState::kReadOpaqueData;\n return DecodeStatus::kDecodeInProgress;\n }\n state->listener()->OnGoAwayEnd();\n return DecodeStatus::kDecodeDone;\n case PayloadState::kResumeDecodingFixedFields:\n status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db);\n payload_state_ = PayloadState::kHandleFixedFieldsStatus;\n continue;\n }\n QUICHE_BUG(http2_bug_167_2) << \"PayloadState: \" << payload_state_;\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass GoAwayPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() { return Http2FrameType::GOAWAY; }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnGoAwayStart(const Http2FrameHeader& header,\n const Http2GoAwayFields& goaway) override {\n QUICHE_VLOG(1) << \"OnGoAwayStart header: \" << header\n << \"; goaway: \" << goaway;\n StartFrame(header)->OnGoAwayStart(header, goaway);\n }\n void OnGoAwayOpaqueData(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnGoAwayOpaqueData: len=\" << len;\n CurrentFrame()->OnGoAwayOpaqueData(data, len);\n }\n void OnGoAwayEnd() override {\n QUICHE_VLOG(1) << \"OnGoAwayEnd\";\n EndFrame()->OnGoAwayEnd();\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass GoAwayPayloadDecoderTest\n : public AbstractPayloadDecoderTest {};\nTEST_F(GoAwayPayloadDecoderTest, Truncated) {\n auto approve_size = [](size_t size) {\n return size != Http2GoAwayFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(Http2GoAwayFields(123, Http2ErrorCode::ENHANCE_YOUR_CALM));\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nclass GoAwayOpaqueDataLengthTests\n : public GoAwayPayloadDecoderTest,\n public ::testing::WithParamInterface {\n protected:\n GoAwayOpaqueDataLengthTests() : length_(GetParam()) {\n QUICHE_VLOG(1) << \"################ length_=\" << length_\n << \" ################\";\n }\n const uint32_t length_;\n};\nINSTANTIATE_TEST_SUITE_P(VariousLengths, GoAwayOpaqueDataLengthTests,\n ::testing::Values(0, 1, 2, 3, 4, 5, 6));\nTEST_P(GoAwayOpaqueDataLengthTests, ValidLength) {\n Http2GoAwayFields goaway;\n Randomize(&goaway, RandomPtr());\n std::string opaque_data = Random().RandString(length_);\n Http2FrameBuilder fb;\n fb.Append(goaway);\n fb.Append(opaque_data);\n Http2FrameHeader header(fb.size(), Http2FrameType::GOAWAY, RandFlags(),\n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header, opaque_data);\n expected.SetOptGoaway(goaway);\n ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n}\n} \n} \n} "}}},{"rowIdx":421,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_CONTINUATION_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_CONTINUATION_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nclass QUICHE_EXPORT ContinuationPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus ContinuationPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"ContinuationPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS));\n state->InitializeRemainders();\n state->listener()->OnContinuationStart(frame_header);\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus ContinuationPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"ContinuationPayloadDecoder::ResumeDecodingPayload\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, state->frame_header().type);\n QUICHE_DCHECK_LE(state->remaining_payload(),\n state->frame_header().payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());\n size_t avail = db->Remaining();\n QUICHE_DCHECK_LE(avail, state->remaining_payload());\n if (avail > 0) {\n state->listener()->OnHpackFragment(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() == 0) {\n state->listener()->OnContinuationEnd();\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h\"\n#include \n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass ContinuationPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::CONTINUATION;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnContinuationStart(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnContinuationStart: \" << header;\n StartFrame(header)->OnContinuationStart(header);\n }\n void OnHpackFragment(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnHpackFragment: len=\" << len;\n CurrentFrame()->OnHpackFragment(data, len);\n }\n void OnContinuationEnd() override {\n QUICHE_VLOG(1) << \"OnContinuationEnd\";\n EndFrame()->OnContinuationEnd();\n }\n};\nclass ContinuationPayloadDecoderTest\n : public AbstractPayloadDecoderTest<\n ContinuationPayloadDecoder, ContinuationPayloadDecoderPeer, Listener>,\n public ::testing::WithParamInterface {\n protected:\n ContinuationPayloadDecoderTest() : length_(GetParam()) {\n QUICHE_VLOG(1) << \"################ length_=\" << length_\n << \" ################\";\n }\n const uint32_t length_;\n};\nINSTANTIATE_TEST_SUITE_P(VariousLengths, ContinuationPayloadDecoderTest,\n ::testing::Values(0, 1, 2, 3, 4, 5, 6));\nTEST_P(ContinuationPayloadDecoderTest, ValidLength) {\n std::string hpack_payload = Random().RandString(length_);\n Http2FrameHeader frame_header(length_, Http2FrameType::CONTINUATION,\n RandFlags(), RandStreamId());\n set_frame_header(frame_header);\n FrameParts expected(frame_header, hpack_payload);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(hpack_payload, expected));\n}\n} \n} \n} "}}},{"rowIdx":422,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PING_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PING_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass PingPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT PingPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::PingPayloadDecoderPeer;\n DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);\n Http2PingFields ping_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/ping_payload_decoder.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace {\nconstexpr auto kOpaqueSize = Http2PingFields::EncodedSize();\n}\nDecodeStatus PingPayloadDecoder::StartDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"PingPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::PING, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK));\n if (db->Remaining() == kOpaqueSize && total_length == kOpaqueSize) {\n static_assert(sizeof(Http2PingFields) == kOpaqueSize,\n \"If not, then can't enter this block!\");\n auto* ping = reinterpret_cast(db->cursor());\n if (frame_header.IsAck()) {\n state->listener()->OnPingAck(frame_header, *ping);\n } else {\n state->listener()->OnPing(frame_header, *ping);\n }\n db->AdvanceCursor(kOpaqueSize);\n return DecodeStatus::kDecodeDone;\n }\n state->InitializeRemainders();\n return HandleStatus(\n state, state->StartDecodingStructureInPayload(&ping_fields_, db));\n}\nDecodeStatus PingPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"ResumeDecodingPayload: remaining_payload=\"\n << state->remaining_payload();\n QUICHE_DCHECK_EQ(Http2FrameType::PING, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n return HandleStatus(\n state, state->ResumeDecodingStructureInPayload(&ping_fields_, db));\n}\nDecodeStatus PingPayloadDecoder::HandleStatus(FrameDecoderState* state,\n DecodeStatus status) {\n QUICHE_DVLOG(2) << \"HandleStatus: status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n if (status == DecodeStatus::kDecodeDone) {\n if (state->remaining_payload() == 0) {\n const Http2FrameHeader& frame_header = state->frame_header();\n if (frame_header.IsAck()) {\n state->listener()->OnPingAck(frame_header, ping_fields_);\n } else {\n state->listener()->OnPing(frame_header, ping_fields_);\n }\n return DecodeStatus::kDecodeDone;\n }\n return state->ReportFrameSizeError();\n }\n QUICHE_DCHECK(\n (status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n return status;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/ping_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass PingPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() { return Http2FrameType::PING; }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnPing(const Http2FrameHeader& header,\n const Http2PingFields& ping) override {\n QUICHE_VLOG(1) << \"OnPing: \" << header << \"; \" << ping;\n StartAndEndFrame(header)->OnPing(header, ping);\n }\n void OnPingAck(const Http2FrameHeader& header,\n const Http2PingFields& ping) override {\n QUICHE_VLOG(1) << \"OnPingAck: \" << header << \"; \" << ping;\n StartAndEndFrame(header)->OnPingAck(header, ping);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass PingPayloadDecoderTest\n : public AbstractPayloadDecoderTest {\n protected:\n Http2PingFields RandPingFields() {\n Http2PingFields fields;\n test::Randomize(&fields, RandomPtr());\n return fields;\n }\n};\nTEST_F(PingPayloadDecoderTest, WrongSize) {\n auto approve_size = [](size_t size) {\n return size != Http2PingFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(RandPingFields());\n fb.Append(RandPingFields());\n fb.Append(RandPingFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nTEST_F(PingPayloadDecoderTest, Ping) {\n for (int n = 0; n < 100; ++n) {\n Http2PingFields fields = RandPingFields();\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::PING,\n RandFlags() & ~Http2FrameFlag::ACK, RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetOptPing(fields);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n}\nTEST_F(PingPayloadDecoderTest, PingAck) {\n for (int n = 0; n < 100; ++n) {\n Http2PingFields fields;\n Randomize(&fields, RandomPtr());\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::PING,\n RandFlags() | Http2FrameFlag::ACK, RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetOptPing(fields);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n}\n} \n} \n} "}}},{"rowIdx":423,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_HEADERS_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_HEADERS_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass HeadersPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT HeadersPayloadDecoder {\n public:\n enum class PayloadState {\n kReadPadLength,\n kStartDecodingPriorityFields,\n kReadPayload,\n kSkipPadding,\n kResumeDecodingPriorityFields,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::HeadersPayloadDecoderPeer;\n PayloadState payload_state_;\n Http2PriorityFields priority_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/headers_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n HeadersPayloadDecoder::PayloadState v) {\n switch (v) {\n case HeadersPayloadDecoder::PayloadState::kReadPadLength:\n return out << \"kReadPadLength\";\n case HeadersPayloadDecoder::PayloadState::kStartDecodingPriorityFields:\n return out << \"kStartDecodingPriorityFields\";\n case HeadersPayloadDecoder::PayloadState::kResumeDecodingPriorityFields:\n return out << \"kResumeDecodingPriorityFields\";\n case HeadersPayloadDecoder::PayloadState::kReadPayload:\n return out << \"kReadPayload\";\n case HeadersPayloadDecoder::PayloadState::kSkipPadding:\n return out << \"kSkipPadding\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_189_1)\n << \"Invalid HeadersPayloadDecoder::PayloadState: \" << unknown;\n return out << \"HeadersPayloadDecoder::PayloadState(\" << unknown << \")\";\n}\nDecodeStatus HeadersPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"HeadersPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(\n 0, frame_header.flags &\n ~(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS |\n Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY));\n const auto payload_flags = Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY;\n if (!frame_header.HasAnyFlags(payload_flags)) {\n QUICHE_DVLOG(2) << \"StartDecodingPayload !IsPadded && !HasPriority\";\n if (db->Remaining() == total_length) {\n QUICHE_DVLOG(2) << \"StartDecodingPayload all present\";\n state->listener()->OnHeadersStart(frame_header);\n if (total_length > 0) {\n state->listener()->OnHpackFragment(db->cursor(), total_length);\n db->AdvanceCursor(total_length);\n }\n state->listener()->OnHeadersEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kReadPayload;\n } else if (frame_header.IsPadded()) {\n payload_state_ = PayloadState::kReadPadLength;\n } else {\n QUICHE_DCHECK(frame_header.HasPriority()) << frame_header;\n payload_state_ = PayloadState::kStartDecodingPriorityFields;\n }\n state->InitializeRemainders();\n state->listener()->OnHeadersStart(frame_header);\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus HeadersPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"HeadersPayloadDecoder::ResumeDecodingPayload \"\n << \"remaining_payload=\" << state->remaining_payload()\n << \"; db->Remaining=\" << db->Remaining();\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type);\n QUICHE_DCHECK_LE(state->remaining_payload_and_padding(),\n frame_header.payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding());\n DecodeStatus status;\n size_t avail;\n while (true) {\n QUICHE_DVLOG(2)\n << \"HeadersPayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n switch (payload_state_) {\n case PayloadState::kReadPadLength:\n status = state->ReadPadLength(db, true);\n if (status != DecodeStatus::kDecodeDone) {\n return status;\n }\n if (!frame_header.HasPriority()) {\n payload_state_ = PayloadState::kReadPayload;\n continue;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kStartDecodingPriorityFields:\n status = state->StartDecodingStructureInPayload(&priority_fields_, db);\n if (status != DecodeStatus::kDecodeDone) {\n payload_state_ = PayloadState::kResumeDecodingPriorityFields;\n return status;\n }\n state->listener()->OnHeadersPriority(priority_fields_);\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kReadPayload:\n avail = state->AvailablePayload(db);\n if (avail > 0) {\n state->listener()->OnHpackFragment(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() > 0) {\n payload_state_ = PayloadState::kReadPayload;\n return DecodeStatus::kDecodeInProgress;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kSkipPadding:\n if (state->SkipPadding(db)) {\n state->listener()->OnHeadersEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kSkipPadding;\n return DecodeStatus::kDecodeInProgress;\n case PayloadState::kResumeDecodingPriorityFields:\n status = state->ResumeDecodingStructureInPayload(&priority_fields_, db);\n if (status != DecodeStatus::kDecodeDone) {\n return status;\n }\n state->listener()->OnHeadersPriority(priority_fields_);\n payload_state_ = PayloadState::kReadPayload;\n continue;\n }\n QUICHE_BUG(http2_bug_189_2) << \"PayloadState: \" << payload_state_;\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/headers_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass HeadersPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::HEADERS;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() {\n return Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY;\n }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnHeadersStart(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnHeadersStart: \" << header;\n StartFrame(header)->OnHeadersStart(header);\n }\n void OnHeadersPriority(const Http2PriorityFields& priority) override {\n QUICHE_VLOG(1) << \"OnHeadersPriority: \" << priority;\n CurrentFrame()->OnHeadersPriority(priority);\n }\n void OnHpackFragment(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnHpackFragment: len=\" << len;\n CurrentFrame()->OnHpackFragment(data, len);\n }\n void OnHeadersEnd() override {\n QUICHE_VLOG(1) << \"OnHeadersEnd\";\n EndFrame()->OnHeadersEnd();\n }\n void OnPadLength(size_t pad_length) override {\n QUICHE_VLOG(1) << \"OnPadLength: \" << pad_length;\n CurrentFrame()->OnPadLength(pad_length);\n }\n void OnPadding(const char* padding, size_t skipped_length) override {\n QUICHE_VLOG(1) << \"OnPadding: \" << skipped_length;\n CurrentFrame()->OnPadding(padding, skipped_length);\n }\n void OnPaddingTooLong(const Http2FrameHeader& header,\n size_t missing_length) override {\n QUICHE_VLOG(1) << \"OnPaddingTooLong: \" << header\n << \"; missing_length: \" << missing_length;\n FrameError(header)->OnPaddingTooLong(header, missing_length);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass HeadersPayloadDecoderTest\n : public AbstractPaddablePayloadDecoderTest<\n HeadersPayloadDecoder, HeadersPayloadDecoderPeer, Listener> {};\nINSTANTIATE_TEST_SUITE_P(VariousPadLengths, HeadersPayloadDecoderTest,\n ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));\nTEST_P(HeadersPayloadDecoderTest, VariousHpackPayloadSizes) {\n for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) {\n QUICHE_LOG(INFO) << \"########### hpack_size = \" << hpack_size\n << \" ###########\";\n Http2PriorityFields priority(RandStreamId(), 1 + Random().Rand8(),\n Random().OneIn(2));\n for (bool has_priority : {false, true}) {\n Reset();\n ASSERT_EQ(IsPadded() ? 1u : 0u, frame_builder_.size());\n uint8_t flags = RandFlags();\n if (has_priority) {\n flags |= Http2FrameFlag::PRIORITY;\n frame_builder_.Append(priority);\n }\n std::string hpack_payload = Random().RandString(hpack_size);\n frame_builder_.Append(hpack_payload);\n MaybeAppendTrailingPadding();\n Http2FrameHeader frame_header(frame_builder_.size(),\n Http2FrameType::HEADERS, flags,\n RandStreamId());\n set_frame_header(frame_header);\n ScrubFlagsOfHeader(&frame_header);\n FrameParts expected(frame_header, hpack_payload, total_pad_length_);\n if (has_priority) {\n expected.SetOptPriority(priority);\n }\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(),\n expected));\n }\n }\n}\nTEST_P(HeadersPayloadDecoderTest, Truncated) {\n auto approve_size = [](size_t size) {\n return size != Http2PriorityFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(Http2PriorityFields(RandStreamId(), 1 + Random().Rand8(),\n Random().OneIn(2)));\n EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(\n Http2FrameFlag::PRIORITY, fb.buffer(), approve_size, total_pad_length_));\n}\nTEST_P(HeadersPayloadDecoderTest, PaddingTooLong) {\n EXPECT_TRUE(VerifyDetectsPaddingTooLong());\n}\n} \n} \n} "}}},{"rowIdx":424,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_ALTSVC_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_ALTSVC_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass AltSvcPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT AltSvcPayloadDecoder {\n public:\n enum class PayloadState {\n kStartDecodingStruct,\n kMaybeDecodedStruct,\n kDecodingStrings,\n kResumeDecodingStruct,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::AltSvcPayloadDecoderPeer;\n DecodeStatus DecodeStrings(FrameDecoderState* state, DecodeBuffer* db);\n Http2AltSvcFields altsvc_fields_;\n PayloadState payload_state_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n AltSvcPayloadDecoder::PayloadState v) {\n switch (v) {\n case AltSvcPayloadDecoder::PayloadState::kStartDecodingStruct:\n return out << \"kStartDecodingStruct\";\n case AltSvcPayloadDecoder::PayloadState::kMaybeDecodedStruct:\n return out << \"kMaybeDecodedStruct\";\n case AltSvcPayloadDecoder::PayloadState::kDecodingStrings:\n return out << \"kDecodingStrings\";\n case AltSvcPayloadDecoder::PayloadState::kResumeDecodingStruct:\n return out << \"kResumeDecodingStruct\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_163_1)\n << \"Invalid AltSvcPayloadDecoder::PayloadState: \" << unknown;\n return out << \"AltSvcPayloadDecoder::PayloadState(\" << unknown << \")\";\n}\nDecodeStatus AltSvcPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"AltSvcPayloadDecoder::StartDecodingPayload: \"\n << state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n QUICHE_DCHECK_EQ(0, state->frame_header().flags);\n state->InitializeRemainders();\n payload_state_ = PayloadState::kStartDecodingStruct;\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus AltSvcPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DVLOG(2) << \"AltSvcPayloadDecoder::ResumeDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, frame_header.type);\n QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());\n QUICHE_DCHECK_NE(PayloadState::kMaybeDecodedStruct, payload_state_);\n DecodeStatus status = DecodeStatus::kDecodeError;\n while (true) {\n QUICHE_DVLOG(2)\n << \"AltSvcPayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n switch (payload_state_) {\n case PayloadState::kStartDecodingStruct:\n status = state->StartDecodingStructureInPayload(&altsvc_fields_, db);\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kMaybeDecodedStruct:\n if (status == DecodeStatus::kDecodeDone &&\n altsvc_fields_.origin_length <= state->remaining_payload()) {\n size_t origin_length = altsvc_fields_.origin_length;\n size_t value_length = state->remaining_payload() - origin_length;\n state->listener()->OnAltSvcStart(frame_header, origin_length,\n value_length);\n } else if (status != DecodeStatus::kDecodeDone) {\n QUICHE_DCHECK(state->remaining_payload() > 0 ||\n status == DecodeStatus::kDecodeError)\n << \"\\nremaining_payload: \" << state->remaining_payload()\n << \"\\nstatus: \" << status << \"\\nheader: \" << frame_header;\n payload_state_ = PayloadState::kResumeDecodingStruct;\n return status;\n } else {\n QUICHE_DCHECK_GT(altsvc_fields_.origin_length,\n state->remaining_payload());\n return state->ReportFrameSizeError();\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kDecodingStrings:\n return DecodeStrings(state, db);\n case PayloadState::kResumeDecodingStruct:\n status = state->ResumeDecodingStructureInPayload(&altsvc_fields_, db);\n payload_state_ = PayloadState::kMaybeDecodedStruct;\n continue;\n }\n QUICHE_BUG(http2_bug_163_2) << \"PayloadState: \" << payload_state_;\n }\n}\nDecodeStatus AltSvcPayloadDecoder::DecodeStrings(FrameDecoderState* state,\n DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"AltSvcPayloadDecoder::DecodeStrings remaining_payload=\"\n << state->remaining_payload()\n << \", db->Remaining=\" << db->Remaining();\n size_t origin_length = altsvc_fields_.origin_length;\n size_t value_length = state->frame_header().payload_length - origin_length -\n Http2AltSvcFields::EncodedSize();\n if (state->remaining_payload() > value_length) {\n size_t remaining_origin_length = state->remaining_payload() - value_length;\n size_t avail = db->MinLengthRemaining(remaining_origin_length);\n state->listener()->OnAltSvcOriginData(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n if (remaining_origin_length > avail) {\n payload_state_ = PayloadState::kDecodingStrings;\n return DecodeStatus::kDecodeInProgress;\n }\n }\n QUICHE_DCHECK_LE(state->remaining_payload(), value_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());\n if (db->HasData()) {\n size_t avail = db->Remaining();\n state->listener()->OnAltSvcValueData(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() == 0) {\n state->listener()->OnAltSvcEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kDecodingStrings;\n return DecodeStatus::kDecodeInProgress;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h\"\n#include \n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass AltSvcPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() { return Http2FrameType::ALTSVC; }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnAltSvcStart(const Http2FrameHeader& header, size_t origin_length,\n size_t value_length) override {\n QUICHE_VLOG(1) << \"OnAltSvcStart header: \" << header\n << \"; origin_length=\" << origin_length\n << \"; value_length=\" << value_length;\n StartFrame(header)->OnAltSvcStart(header, origin_length, value_length);\n }\n void OnAltSvcOriginData(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnAltSvcOriginData: len=\" << len;\n CurrentFrame()->OnAltSvcOriginData(data, len);\n }\n void OnAltSvcValueData(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnAltSvcValueData: len=\" << len;\n CurrentFrame()->OnAltSvcValueData(data, len);\n }\n void OnAltSvcEnd() override {\n QUICHE_VLOG(1) << \"OnAltSvcEnd\";\n EndFrame()->OnAltSvcEnd();\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass AltSvcPayloadDecoderTest\n : public AbstractPayloadDecoderTest {};\nTEST_F(AltSvcPayloadDecoderTest, Truncated) {\n Http2FrameBuilder fb;\n fb.Append(Http2AltSvcFields{0xffff}); \n fb.Append(\"Too little origin!\");\n EXPECT_TRUE(\n VerifyDetectsFrameSizeError(0, fb.buffer(), nullptr));\n}\nclass AltSvcPayloadLengthTests\n : public AltSvcPayloadDecoderTest,\n public ::testing::WithParamInterface> {\n protected:\n AltSvcPayloadLengthTests()\n : origin_length_(std::get<0>(GetParam())),\n value_length_(std::get<1>(GetParam())) {\n QUICHE_VLOG(1) << \"################ origin_length_=\" << origin_length_\n << \" value_length_=\" << value_length_\n << \" ################\";\n }\n const uint16_t origin_length_;\n const uint32_t value_length_;\n};\nINSTANTIATE_TEST_SUITE_P(VariousOriginAndValueLengths, AltSvcPayloadLengthTests,\n ::testing::Combine(::testing::Values(0, 1, 3, 65535),\n ::testing::Values(0, 1, 3, 65537)));\nTEST_P(AltSvcPayloadLengthTests, ValidOriginAndValueLength) {\n std::string origin = Random().RandString(origin_length_);\n std::string value = Random().RandString(value_length_);\n Http2FrameBuilder fb;\n fb.Append(Http2AltSvcFields{origin_length_});\n fb.Append(origin);\n fb.Append(value);\n Http2FrameHeader header(fb.size(), Http2FrameType::ALTSVC, RandFlags(),\n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetAltSvcExpected(origin, value);\n ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n}\n} \n} \n} "}}},{"rowIdx":425,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass PriorityPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT PriorityPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::PriorityPayloadDecoderPeer;\n DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);\n Http2PriorityFields priority_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/priority_payload_decoder.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus PriorityPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"PriorityPayloadDecoder::StartDecodingPayload: \"\n << state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n QUICHE_DCHECK_EQ(0, state->frame_header().flags);\n state->InitializeRemainders();\n return HandleStatus(\n state, state->StartDecodingStructureInPayload(&priority_fields_, db));\n}\nDecodeStatus PriorityPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"PriorityPayloadDecoder::ResumeDecodingPayload\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n return HandleStatus(\n state, state->ResumeDecodingStructureInPayload(&priority_fields_, db));\n}\nDecodeStatus PriorityPayloadDecoder::HandleStatus(FrameDecoderState* state,\n DecodeStatus status) {\n if (status == DecodeStatus::kDecodeDone) {\n if (state->remaining_payload() == 0) {\n state->listener()->OnPriorityFrame(state->frame_header(),\n priority_fields_);\n return DecodeStatus::kDecodeDone;\n }\n return state->ReportFrameSizeError();\n }\n QUICHE_DCHECK(\n (status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n return status;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/priority_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass PriorityPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::PRIORITY;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnPriorityFrame(const Http2FrameHeader& header,\n const Http2PriorityFields& priority_fields) override {\n QUICHE_VLOG(1) << \"OnPriority: \" << header << \"; \" << priority_fields;\n StartAndEndFrame(header)->OnPriorityFrame(header, priority_fields);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass PriorityPayloadDecoderTest\n : public AbstractPayloadDecoderTest {\n protected:\n Http2PriorityFields RandPriorityFields() {\n Http2PriorityFields fields;\n test::Randomize(&fields, RandomPtr());\n return fields;\n }\n};\nTEST_F(PriorityPayloadDecoderTest, WrongSize) {\n auto approve_size = [](size_t size) {\n return size != Http2PriorityFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(RandPriorityFields());\n fb.Append(RandPriorityFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nTEST_F(PriorityPayloadDecoderTest, VariousPayloads) {\n for (int n = 0; n < 100; ++n) {\n Http2PriorityFields fields = RandPriorityFields();\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY, RandFlags(),\n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetOptPriority(fields);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n}\n} \n} \n} "}}},{"rowIdx":426,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_UNKNOWN_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_UNKNOWN_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nclass QUICHE_EXPORT UnknownPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus UnknownPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DVLOG(2) << \"UnknownPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK(!IsSupportedHttp2FrameType(frame_header.type)) << frame_header;\n QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);\n state->InitializeRemainders();\n state->listener()->OnUnknownStart(frame_header);\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus UnknownPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"UnknownPayloadDecoder::ResumeDecodingPayload \"\n << \"remaining_payload=\" << state->remaining_payload()\n << \"; db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK(!IsSupportedHttp2FrameType(state->frame_header().type))\n << state->frame_header();\n QUICHE_DCHECK_LE(state->remaining_payload(),\n state->frame_header().payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());\n size_t avail = db->Remaining();\n if (avail > 0) {\n state->listener()->OnUnknownPayload(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() == 0) {\n state->listener()->OnUnknownEnd();\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h\"\n#include \n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nHttp2FrameType g_unknown_frame_type;\n} \nclass UnknownPayloadDecoderPeer {\n public:\n static Http2FrameType FrameType() { return g_unknown_frame_type; }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnUnknownStart(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnUnknownStart: \" << header;\n StartFrame(header)->OnUnknownStart(header);\n }\n void OnUnknownPayload(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnUnknownPayload: len=\" << len;\n CurrentFrame()->OnUnknownPayload(data, len);\n }\n void OnUnknownEnd() override {\n QUICHE_VLOG(1) << \"OnUnknownEnd\";\n EndFrame()->OnUnknownEnd();\n }\n};\nconstexpr bool SupportedFrameType = false;\nclass UnknownPayloadDecoderTest\n : public AbstractPayloadDecoderTest,\n public ::testing::WithParamInterface {\n protected:\n UnknownPayloadDecoderTest() : length_(GetParam()) {\n QUICHE_VLOG(1) << \"################ length_=\" << length_\n << \" ################\";\n do {\n g_unknown_frame_type = static_cast(Random().Rand8());\n } while (IsSupportedHttp2FrameType(g_unknown_frame_type));\n }\n const uint32_t length_;\n};\nINSTANTIATE_TEST_SUITE_P(VariousLengths, UnknownPayloadDecoderTest,\n ::testing::Values(0, 1, 2, 3, 255, 256));\nTEST_P(UnknownPayloadDecoderTest, ValidLength) {\n std::string unknown_payload = Random().RandString(length_);\n Http2FrameHeader frame_header(length_, g_unknown_frame_type, Random().Rand8(),\n RandStreamId());\n set_frame_header(frame_header);\n FrameParts expected(frame_header, unknown_payload);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(unknown_payload, expected));\n}\n} \n} \n} "}}},{"rowIdx":427,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_WINDOW_UPDATE_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_WINDOW_UPDATE_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass WindowUpdatePayloadDecoderPeer;\n} \nclass QUICHE_EXPORT WindowUpdatePayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::WindowUpdatePayloadDecoderPeer;\n DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);\n Http2WindowUpdateFields window_update_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_http2_structures.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus WindowUpdatePayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"WindowUpdatePayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags);\n if (db->Remaining() == Http2WindowUpdateFields::EncodedSize() &&\n total_length == Http2WindowUpdateFields::EncodedSize()) {\n DoDecode(&window_update_fields_, db);\n state->listener()->OnWindowUpdate(\n frame_header, window_update_fields_.window_size_increment);\n return DecodeStatus::kDecodeDone;\n }\n state->InitializeRemainders();\n return HandleStatus(state, state->StartDecodingStructureInPayload(\n &window_update_fields_, db));\n}\nDecodeStatus WindowUpdatePayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"ResumeDecodingPayload: remaining_payload=\"\n << state->remaining_payload()\n << \"; db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n return HandleStatus(state, state->ResumeDecodingStructureInPayload(\n &window_update_fields_, db));\n}\nDecodeStatus WindowUpdatePayloadDecoder::HandleStatus(FrameDecoderState* state,\n DecodeStatus status) {\n QUICHE_DVLOG(2) << \"HandleStatus: status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n if (status == DecodeStatus::kDecodeDone) {\n if (state->remaining_payload() == 0) {\n state->listener()->OnWindowUpdate(\n state->frame_header(), window_update_fields_.window_size_increment);\n return DecodeStatus::kDecodeDone;\n }\n return state->ReportFrameSizeError();\n }\n QUICHE_DCHECK(\n (status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n return status;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass WindowUpdatePayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::WINDOW_UPDATE;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnWindowUpdate(const Http2FrameHeader& header,\n uint32_t window_size_increment) override {\n QUICHE_VLOG(1) << \"OnWindowUpdate: \" << header\n << \"; window_size_increment=\" << window_size_increment;\n EXPECT_EQ(Http2FrameType::WINDOW_UPDATE, header.type);\n StartAndEndFrame(header)->OnWindowUpdate(header, window_size_increment);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass WindowUpdatePayloadDecoderTest\n : public AbstractPayloadDecoderTest {\n protected:\n Http2WindowUpdateFields RandWindowUpdateFields() {\n Http2WindowUpdateFields fields;\n test::Randomize(&fields, RandomPtr());\n QUICHE_VLOG(3) << \"RandWindowUpdateFields: \" << fields;\n return fields;\n }\n};\nTEST_F(WindowUpdatePayloadDecoderTest, WrongSize) {\n auto approve_size = [](size_t size) {\n return size != Http2WindowUpdateFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(RandWindowUpdateFields());\n fb.Append(RandWindowUpdateFields());\n fb.Append(RandWindowUpdateFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nTEST_F(WindowUpdatePayloadDecoderTest, VariousPayloads) {\n for (int n = 0; n < 100; ++n) {\n uint32_t stream_id = n == 0 ? 0 : RandStreamId();\n Http2WindowUpdateFields fields = RandWindowUpdateFields();\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::WINDOW_UPDATE,\n RandFlags(), stream_id);\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetOptWindowUpdateIncrement(fields.window_size_increment);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n}\n} \n} \n} "}}},{"rowIdx":428,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PUSH_PROMISE_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PUSH_PROMISE_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass PushPromisePayloadDecoderPeer;\n} \nclass QUICHE_EXPORT PushPromisePayloadDecoder {\n public:\n enum class PayloadState {\n kReadPadLength,\n kStartDecodingPushPromiseFields,\n kReadPayload,\n kSkipPadding,\n kResumeDecodingPushPromiseFields,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::PushPromisePayloadDecoderPeer;\n void ReportPushPromise(FrameDecoderState* state);\n PayloadState payload_state_;\n Http2PushPromiseFields push_promise_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n PushPromisePayloadDecoder::PayloadState v) {\n switch (v) {\n case PushPromisePayloadDecoder::PayloadState::kReadPadLength:\n return out << \"kReadPadLength\";\n case PushPromisePayloadDecoder::PayloadState::\n kStartDecodingPushPromiseFields:\n return out << \"kStartDecodingPushPromiseFields\";\n case PushPromisePayloadDecoder::PayloadState::kReadPayload:\n return out << \"kReadPayload\";\n case PushPromisePayloadDecoder::PayloadState::kSkipPadding:\n return out << \"kSkipPadding\";\n case PushPromisePayloadDecoder::PayloadState::\n kResumeDecodingPushPromiseFields:\n return out << \"kResumeDecodingPushPromiseFields\";\n }\n return out << static_cast(v);\n}\nDecodeStatus PushPromisePayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"PushPromisePayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS |\n Http2FrameFlag::PADDED));\n if (!frame_header.IsPadded()) {\n payload_state_ = PayloadState::kStartDecodingPushPromiseFields;\n } else {\n payload_state_ = PayloadState::kReadPadLength;\n }\n state->InitializeRemainders();\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus PushPromisePayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"UnknownPayloadDecoder::ResumeDecodingPayload\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type);\n QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);\n DecodeStatus status;\n while (true) {\n QUICHE_DVLOG(2)\n << \"PushPromisePayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n switch (payload_state_) {\n case PayloadState::kReadPadLength:\n QUICHE_DCHECK_EQ(state->remaining_payload(),\n frame_header.payload_length);\n status = state->ReadPadLength(db, false);\n if (status != DecodeStatus::kDecodeDone) {\n payload_state_ = PayloadState::kReadPadLength;\n return status;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kStartDecodingPushPromiseFields:\n status =\n state->StartDecodingStructureInPayload(&push_promise_fields_, db);\n if (status != DecodeStatus::kDecodeDone) {\n payload_state_ = PayloadState::kResumeDecodingPushPromiseFields;\n return status;\n }\n ReportPushPromise(state);\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kReadPayload:\n QUICHE_DCHECK_LT(state->remaining_payload(),\n frame_header.payload_length);\n QUICHE_DCHECK_LE(state->remaining_payload(),\n frame_header.payload_length -\n Http2PushPromiseFields::EncodedSize());\n QUICHE_DCHECK_LE(\n state->remaining_payload(),\n frame_header.payload_length -\n Http2PushPromiseFields::EncodedSize() -\n (frame_header.IsPadded() ? (1 + state->remaining_padding())\n : 0));\n {\n size_t avail = state->AvailablePayload(db);\n state->listener()->OnHpackFragment(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() > 0) {\n payload_state_ = PayloadState::kReadPayload;\n return DecodeStatus::kDecodeInProgress;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kSkipPadding:\n if (state->SkipPadding(db)) {\n state->listener()->OnPushPromiseEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kSkipPadding;\n return DecodeStatus::kDecodeInProgress;\n case PayloadState::kResumeDecodingPushPromiseFields:\n status =\n state->ResumeDecodingStructureInPayload(&push_promise_fields_, db);\n if (status == DecodeStatus::kDecodeDone) {\n ReportPushPromise(state);\n payload_state_ = PayloadState::kReadPayload;\n continue;\n }\n payload_state_ = PayloadState::kResumeDecodingPushPromiseFields;\n return status;\n }\n QUICHE_BUG(http2_bug_183_1) << \"PayloadState: \" << payload_state_;\n }\n}\nvoid PushPromisePayloadDecoder::ReportPushPromise(FrameDecoderState* state) {\n const Http2FrameHeader& frame_header = state->frame_header();\n if (frame_header.IsPadded()) {\n state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_,\n 1 + state->remaining_padding());\n } else {\n state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_,\n 0);\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass PushPromisePayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::PUSH_PROMISE;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() {\n return Http2FrameFlag::PADDED;\n }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnPushPromiseStart(const Http2FrameHeader& header,\n const Http2PushPromiseFields& promise,\n size_t total_padding_length) override {\n QUICHE_VLOG(1) << \"OnPushPromiseStart header: \" << header\n << \" promise: \" << promise\n << \" total_padding_length: \" << total_padding_length;\n EXPECT_EQ(Http2FrameType::PUSH_PROMISE, header.type);\n StartFrame(header)->OnPushPromiseStart(header, promise,\n total_padding_length);\n }\n void OnHpackFragment(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnHpackFragment: len=\" << len;\n CurrentFrame()->OnHpackFragment(data, len);\n }\n void OnPushPromiseEnd() override {\n QUICHE_VLOG(1) << \"OnPushPromiseEnd\";\n EndFrame()->OnPushPromiseEnd();\n }\n void OnPadding(const char* padding, size_t skipped_length) override {\n QUICHE_VLOG(1) << \"OnPadding: \" << skipped_length;\n CurrentFrame()->OnPadding(padding, skipped_length);\n }\n void OnPaddingTooLong(const Http2FrameHeader& header,\n size_t missing_length) override {\n QUICHE_VLOG(1) << \"OnPaddingTooLong: \" << header\n << \"; missing_length: \" << missing_length;\n FrameError(header)->OnPaddingTooLong(header, missing_length);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass PushPromisePayloadDecoderTest\n : public AbstractPaddablePayloadDecoderTest<\n PushPromisePayloadDecoder, PushPromisePayloadDecoderPeer, Listener> {\n};\nINSTANTIATE_TEST_SUITE_P(VariousPadLengths, PushPromisePayloadDecoderTest,\n ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));\nTEST_P(PushPromisePayloadDecoderTest, VariousHpackPayloadSizes) {\n for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) {\n QUICHE_LOG(INFO) << \"########### hpack_size = \" << hpack_size\n << \" ###########\";\n Reset();\n std::string hpack_payload = Random().RandString(hpack_size);\n Http2PushPromiseFields push_promise{RandStreamId()};\n frame_builder_.Append(push_promise);\n frame_builder_.Append(hpack_payload);\n MaybeAppendTrailingPadding();\n Http2FrameHeader frame_header(frame_builder_.size(),\n Http2FrameType::PUSH_PROMISE, RandFlags(),\n RandStreamId());\n set_frame_header(frame_header);\n FrameParts expected(frame_header, hpack_payload, total_pad_length_);\n expected.SetOptPushPromise(push_promise);\n EXPECT_TRUE(\n DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected));\n }\n}\nTEST_P(PushPromisePayloadDecoderTest, Truncated) {\n auto approve_size = [](size_t size) {\n return size != Http2PushPromiseFields::EncodedSize();\n };\n Http2PushPromiseFields push_promise{RandStreamId()};\n Http2FrameBuilder fb;\n fb.Append(push_promise);\n EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(0, fb.buffer(), approve_size,\n total_pad_length_));\n}\nTEST_P(PushPromisePayloadDecoderTest, PaddingTooLong) {\n EXPECT_TRUE(VerifyDetectsPaddingTooLong());\n}\n} \n} \n} "}}},{"rowIdx":429,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_UPDATE_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_UPDATE_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass PriorityUpdatePayloadDecoderPeer;\n} \nclass QUICHE_EXPORT PriorityUpdatePayloadDecoder {\n public:\n enum class PayloadState {\n kStartDecodingFixedFields,\n kResumeDecodingFixedFields,\n kHandleFixedFieldsStatus,\n kReadPriorityFieldValue,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::PriorityUpdatePayloadDecoderPeer;\n Http2PriorityUpdateFields priority_update_fields_;\n PayloadState payload_state_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n PriorityUpdatePayloadDecoder::PayloadState v) {\n switch (v) {\n case PriorityUpdatePayloadDecoder::PayloadState::kStartDecodingFixedFields:\n return out << \"kStartDecodingFixedFields\";\n case PriorityUpdatePayloadDecoder::PayloadState::kResumeDecodingFixedFields:\n return out << \"kResumeDecodingFixedFields\";\n case PriorityUpdatePayloadDecoder::PayloadState::kHandleFixedFieldsStatus:\n return out << \"kHandleFixedFieldsStatus\";\n case PriorityUpdatePayloadDecoder::PayloadState::kReadPriorityFieldValue:\n return out << \"kReadPriorityFieldValue\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_173_1)\n << \"Invalid PriorityUpdatePayloadDecoder::PayloadState: \" << unknown;\n return out << \"PriorityUpdatePayloadDecoder::PayloadState(\" << unknown << \")\";\n}\nDecodeStatus PriorityUpdatePayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"PriorityUpdatePayloadDecoder::StartDecodingPayload: \"\n << state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n QUICHE_DCHECK_EQ(0, state->frame_header().flags);\n state->InitializeRemainders();\n payload_state_ = PayloadState::kStartDecodingFixedFields;\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus PriorityUpdatePayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"PriorityUpdatePayloadDecoder::ResumeDecodingPayload: \"\n \"remaining_payload=\"\n << state->remaining_payload()\n << \", db->Remaining=\" << db->Remaining();\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);\n QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_);\n DecodeStatus status = DecodeStatus::kDecodeError;\n size_t avail;\n while (true) {\n QUICHE_DVLOG(2)\n << \"PriorityUpdatePayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n switch (payload_state_) {\n case PayloadState::kStartDecodingFixedFields:\n status = state->StartDecodingStructureInPayload(\n &priority_update_fields_, db);\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kHandleFixedFieldsStatus:\n if (status == DecodeStatus::kDecodeDone) {\n state->listener()->OnPriorityUpdateStart(frame_header,\n priority_update_fields_);\n } else {\n QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError &&\n state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n payload_state_ = PayloadState::kResumeDecodingFixedFields;\n return status;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kReadPriorityFieldValue:\n avail = db->Remaining();\n if (avail > 0) {\n state->listener()->OnPriorityUpdatePayload(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() > 0) {\n payload_state_ = PayloadState::kReadPriorityFieldValue;\n return DecodeStatus::kDecodeInProgress;\n }\n state->listener()->OnPriorityUpdateEnd();\n return DecodeStatus::kDecodeDone;\n case PayloadState::kResumeDecodingFixedFields:\n status = state->ResumeDecodingStructureInPayload(\n &priority_update_fields_, db);\n payload_state_ = PayloadState::kHandleFixedFieldsStatus;\n continue;\n }\n QUICHE_BUG(http2_bug_173_2) << \"PayloadState: \" << payload_state_;\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass PriorityUpdatePayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::PRIORITY_UPDATE;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnPriorityUpdateStart(\n const Http2FrameHeader& header,\n const Http2PriorityUpdateFields& priority_update) override {\n QUICHE_VLOG(1) << \"OnPriorityUpdateStart header: \" << header\n << \"; priority_update: \" << priority_update;\n StartFrame(header)->OnPriorityUpdateStart(header, priority_update);\n }\n void OnPriorityUpdatePayload(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnPriorityUpdatePayload: len=\" << len;\n CurrentFrame()->OnPriorityUpdatePayload(data, len);\n }\n void OnPriorityUpdateEnd() override {\n QUICHE_VLOG(1) << \"OnPriorityUpdateEnd\";\n EndFrame()->OnPriorityUpdateEnd();\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass PriorityUpdatePayloadDecoderTest\n : public AbstractPayloadDecoderTest {};\nTEST_F(PriorityUpdatePayloadDecoderTest, Truncated) {\n auto approve_size = [](size_t size) {\n return size != Http2PriorityUpdateFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(Http2PriorityUpdateFields(123));\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nclass PriorityUpdatePayloadLengthTests\n : public AbstractPayloadDecoderTest,\n public ::testing::WithParamInterface {\n protected:\n PriorityUpdatePayloadLengthTests() : length_(GetParam()) {\n QUICHE_VLOG(1) << \"################ length_=\" << length_\n << \" ################\";\n }\n const uint32_t length_;\n};\nINSTANTIATE_TEST_SUITE_P(VariousLengths, PriorityUpdatePayloadLengthTests,\n ::testing::Values(0, 1, 2, 3, 4, 5, 6));\nTEST_P(PriorityUpdatePayloadLengthTests, ValidLength) {\n Http2PriorityUpdateFields priority_update;\n Randomize(&priority_update, RandomPtr());\n std::string priority_field_value = Random().RandString(length_);\n Http2FrameBuilder fb;\n fb.Append(priority_update);\n fb.Append(priority_field_value);\n Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY_UPDATE,\n RandFlags(), RandStreamId());\n set_frame_header(header);\n FrameParts expected(header, priority_field_value);\n expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{priority_update});\n ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n}\n} \n} \n} "}}},{"rowIdx":430,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_RST_STREAM_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_RST_STREAM_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass RstStreamPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT RstStreamPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::RstStreamPayloadDecoderPeer;\n DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);\n Http2RstStreamFields rst_stream_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus RstStreamPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"RstStreamPayloadDecoder::StartDecodingPayload: \"\n << state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n QUICHE_DCHECK_EQ(0, state->frame_header().flags);\n state->InitializeRemainders();\n return HandleStatus(\n state, state->StartDecodingStructureInPayload(&rst_stream_fields_, db));\n}\nDecodeStatus RstStreamPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"RstStreamPayloadDecoder::ResumeDecodingPayload\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n return HandleStatus(\n state, state->ResumeDecodingStructureInPayload(&rst_stream_fields_, db));\n}\nDecodeStatus RstStreamPayloadDecoder::HandleStatus(FrameDecoderState* state,\n DecodeStatus status) {\n QUICHE_DVLOG(2) << \"HandleStatus: status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n if (status == DecodeStatus::kDecodeDone) {\n if (state->remaining_payload() == 0) {\n state->listener()->OnRstStream(state->frame_header(),\n rst_stream_fields_.error_code);\n return DecodeStatus::kDecodeDone;\n }\n return state->ReportFrameSizeError();\n }\n QUICHE_DCHECK(\n (status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload();\n return status;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h\"\n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_constants_test_util.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass RstStreamPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::RST_STREAM;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnRstStream(const Http2FrameHeader& header,\n Http2ErrorCode error_code) override {\n QUICHE_VLOG(1) << \"OnRstStream: \" << header\n << \"; error_code=\" << error_code;\n StartAndEndFrame(header)->OnRstStream(header, error_code);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass RstStreamPayloadDecoderTest\n : public AbstractPayloadDecoderTest {\n protected:\n Http2RstStreamFields RandRstStreamFields() {\n Http2RstStreamFields fields;\n test::Randomize(&fields, RandomPtr());\n return fields;\n }\n};\nTEST_F(RstStreamPayloadDecoderTest, WrongSize) {\n auto approve_size = [](size_t size) {\n return size != Http2RstStreamFields::EncodedSize();\n };\n Http2FrameBuilder fb;\n fb.Append(RandRstStreamFields());\n fb.Append(RandRstStreamFields());\n fb.Append(RandRstStreamFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nTEST_F(RstStreamPayloadDecoderTest, AllErrors) {\n for (auto error_code : AllHttp2ErrorCodes()) {\n Http2RstStreamFields fields{error_code};\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::RST_STREAM, RandFlags(),\n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.SetOptRstStreamErrorCode(error_code);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n}\n} \n} \n} "}}},{"rowIdx":431,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_DATA_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_DATA_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass DataPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT DataPayloadDecoder {\n public:\n enum class PayloadState {\n kReadPadLength,\n kReadPayload,\n kSkipPadding,\n };\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::DataPayloadDecoderPeer;\n PayloadState payload_state_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/data_payload_decoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n DataPayloadDecoder::PayloadState v) {\n switch (v) {\n case DataPayloadDecoder::PayloadState::kReadPadLength:\n return out << \"kReadPadLength\";\n case DataPayloadDecoder::PayloadState::kReadPayload:\n return out << \"kReadPayload\";\n case DataPayloadDecoder::PayloadState::kSkipPadding:\n return out << \"kSkipPadding\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_174_1)\n << \"Invalid DataPayloadDecoder::PayloadState: \" << unknown;\n return out << \"DataPayloadDecoder::PayloadState(\" << unknown << \")\";\n}\nDecodeStatus DataPayloadDecoder::StartDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"DataPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_STREAM |\n Http2FrameFlag::PADDED));\n QUICHE_DVLOG(2) << \"StartDecodingPayload total_length=\" << total_length;\n if (!frame_header.IsPadded()) {\n QUICHE_DVLOG(2) << \"StartDecodingPayload !IsPadded\";\n if (db->Remaining() == total_length) {\n QUICHE_DVLOG(2) << \"StartDecodingPayload all present\";\n state->listener()->OnDataStart(frame_header);\n if (total_length > 0) {\n state->listener()->OnDataPayload(db->cursor(), total_length);\n db->AdvanceCursor(total_length);\n }\n state->listener()->OnDataEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kReadPayload;\n } else {\n payload_state_ = PayloadState::kReadPadLength;\n }\n state->InitializeRemainders();\n state->listener()->OnDataStart(frame_header);\n return ResumeDecodingPayload(state, db);\n}\nDecodeStatus DataPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"DataPayloadDecoder::ResumeDecodingPayload payload_state_=\"\n << payload_state_;\n const Http2FrameHeader& frame_header = state->frame_header();\n QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type);\n QUICHE_DCHECK_LE(state->remaining_payload_and_padding(),\n frame_header.payload_length);\n QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding());\n DecodeStatus status;\n size_t avail;\n switch (payload_state_) {\n case PayloadState::kReadPadLength:\n status = state->ReadPadLength(db, true);\n if (status != DecodeStatus::kDecodeDone) {\n return status;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kReadPayload:\n avail = state->AvailablePayload(db);\n if (avail > 0) {\n state->listener()->OnDataPayload(db->cursor(), avail);\n db->AdvanceCursor(avail);\n state->ConsumePayload(avail);\n }\n if (state->remaining_payload() > 0) {\n payload_state_ = PayloadState::kReadPayload;\n return DecodeStatus::kDecodeInProgress;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case PayloadState::kSkipPadding:\n if (state->SkipPadding(db)) {\n state->listener()->OnDataEnd();\n return DecodeStatus::kDecodeDone;\n }\n payload_state_ = PayloadState::kSkipPadding;\n return DecodeStatus::kDecodeInProgress;\n }\n QUICHE_BUG(http2_bug_174_2) << \"PayloadState: \" << payload_state_;\n return DecodeStatus::kDecodeError;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/data_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass DataPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() { return Http2FrameType::DATA; }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() {\n return Http2FrameFlag::PADDED;\n }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnDataStart(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnDataStart: \" << header;\n StartFrame(header)->OnDataStart(header);\n }\n void OnDataPayload(const char* data, size_t len) override {\n QUICHE_VLOG(1) << \"OnDataPayload: len=\" << len;\n CurrentFrame()->OnDataPayload(data, len);\n }\n void OnDataEnd() override {\n QUICHE_VLOG(1) << \"OnDataEnd\";\n EndFrame()->OnDataEnd();\n }\n void OnPadLength(size_t pad_length) override {\n QUICHE_VLOG(1) << \"OnPadLength: \" << pad_length;\n CurrentFrame()->OnPadLength(pad_length);\n }\n void OnPadding(const char* padding, size_t skipped_length) override {\n QUICHE_VLOG(1) << \"OnPadding: \" << skipped_length;\n CurrentFrame()->OnPadding(padding, skipped_length);\n }\n void OnPaddingTooLong(const Http2FrameHeader& header,\n size_t missing_length) override {\n QUICHE_VLOG(1) << \"OnPaddingTooLong: \" << header\n << \" missing_length: \" << missing_length;\n EndFrame()->OnPaddingTooLong(header, missing_length);\n }\n};\nclass DataPayloadDecoderTest\n : public AbstractPaddablePayloadDecoderTest<\n DataPayloadDecoder, DataPayloadDecoderPeer, Listener> {\n protected:\n AssertionResult CreateAndDecodeDataOfSize(size_t data_size) {\n Reset();\n uint8_t flags = RandFlags();\n std::string data_payload = Random().RandString(data_size);\n frame_builder_.Append(data_payload);\n MaybeAppendTrailingPadding();\n Http2FrameHeader frame_header(frame_builder_.size(), Http2FrameType::DATA,\n flags, RandStreamId());\n set_frame_header(frame_header);\n ScrubFlagsOfHeader(&frame_header);\n FrameParts expected(frame_header, data_payload, total_pad_length_);\n return DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(),\n expected);\n }\n};\nINSTANTIATE_TEST_SUITE_P(VariousPadLengths, DataPayloadDecoderTest,\n ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));\nTEST_P(DataPayloadDecoderTest, VariousDataPayloadSizes) {\n for (size_t data_size : {0, 1, 2, 3, 255, 256, 1024}) {\n EXPECT_TRUE(CreateAndDecodeDataOfSize(data_size));\n }\n}\n} \n} \n} "}}},{"rowIdx":432,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_SETTINGS_PAYLOAD_DECODER_H_\n#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_SETTINGS_PAYLOAD_DECODER_H_\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/decoder/frame_decoder_state.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass SettingsPayloadDecoderPeer;\n} \nclass QUICHE_EXPORT SettingsPayloadDecoder {\n public:\n DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);\n DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,\n DecodeBuffer* db);\n private:\n friend class test::SettingsPayloadDecoderPeer;\n DecodeStatus StartDecodingSettings(FrameDecoderState* state,\n DecodeBuffer* db);\n DecodeStatus HandleNotDone(FrameDecoderState* state, DecodeBuffer* db,\n DecodeStatus status);\n Http2SettingFields setting_fields_;\n};\n} \n#endif \n#include \"quiche/http2/decoder/payload_decoders/settings_payload_decoder.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus SettingsPayloadDecoder::StartDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n const Http2FrameHeader& frame_header = state->frame_header();\n const uint32_t total_length = frame_header.payload_length;\n QUICHE_DVLOG(2) << \"SettingsPayloadDecoder::StartDecodingPayload: \"\n << frame_header;\n QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, frame_header.type);\n QUICHE_DCHECK_LE(db->Remaining(), total_length);\n QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK));\n if (frame_header.IsAck()) {\n if (total_length == 0) {\n state->listener()->OnSettingsAck(frame_header);\n return DecodeStatus::kDecodeDone;\n } else {\n state->InitializeRemainders();\n return state->ReportFrameSizeError();\n }\n } else {\n state->InitializeRemainders();\n state->listener()->OnSettingsStart(frame_header);\n return StartDecodingSettings(state, db);\n }\n}\nDecodeStatus SettingsPayloadDecoder::ResumeDecodingPayload(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"SettingsPayloadDecoder::ResumeDecodingPayload\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, state->frame_header().type);\n QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);\n DecodeStatus status =\n state->ResumeDecodingStructureInPayload(&setting_fields_, db);\n if (status == DecodeStatus::kDecodeDone) {\n state->listener()->OnSetting(setting_fields_);\n return StartDecodingSettings(state, db);\n }\n return HandleNotDone(state, db, status);\n}\nDecodeStatus SettingsPayloadDecoder::StartDecodingSettings(\n FrameDecoderState* state, DecodeBuffer* db) {\n QUICHE_DVLOG(2) << \"SettingsPayloadDecoder::StartDecodingSettings\"\n << \" remaining_payload=\" << state->remaining_payload()\n << \" db->Remaining=\" << db->Remaining();\n while (state->remaining_payload() > 0) {\n DecodeStatus status =\n state->StartDecodingStructureInPayload(&setting_fields_, db);\n if (status == DecodeStatus::kDecodeDone) {\n state->listener()->OnSetting(setting_fields_);\n continue;\n }\n return HandleNotDone(state, db, status);\n }\n QUICHE_DVLOG(2) << \"LEAVING SettingsPayloadDecoder::StartDecodingSettings\"\n << \"\\n\\tdb->Remaining=\" << db->Remaining()\n << \"\\n\\t remaining_payload=\" << state->remaining_payload();\n state->listener()->OnSettingsEnd();\n return DecodeStatus::kDecodeDone;\n}\nDecodeStatus SettingsPayloadDecoder::HandleNotDone(FrameDecoderState* state,\n DecodeBuffer* db,\n DecodeStatus status) {\n QUICHE_DCHECK(\n (status == DecodeStatus::kDecodeInProgress &&\n state->remaining_payload() > 0) ||\n (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))\n << \"\\n status=\" << status\n << \"; remaining_payload=\" << state->remaining_payload()\n << \"; db->Remaining=\" << db->Remaining();\n return status;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/decoder/payload_decoders/settings_payload_decoder.h\"\n#include \n#include \n#include \"quiche/http2/decoder/http2_frame_decoder_listener.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/frame_parts.h\"\n#include \"quiche/http2/test_tools/frame_parts_collector.h\"\n#include \"quiche/http2/test_tools/http2_constants_test_util.h\"\n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/http2_structures_test_util.h\"\n#include \"quiche/http2/test_tools/payload_decoder_base_test_util.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass SettingsPayloadDecoderPeer {\n public:\n static constexpr Http2FrameType FrameType() {\n return Http2FrameType::SETTINGS;\n }\n static constexpr uint8_t FlagsAffectingPayloadDecoding() {\n return Http2FrameFlag::ACK;\n }\n};\nnamespace {\nstruct Listener : public FramePartsCollector {\n void OnSettingsStart(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnSettingsStart: \" << header;\n EXPECT_EQ(Http2FrameType::SETTINGS, header.type) << header;\n EXPECT_EQ(Http2FrameFlag(), header.flags) << header;\n StartFrame(header)->OnSettingsStart(header);\n }\n void OnSetting(const Http2SettingFields& setting_fields) override {\n QUICHE_VLOG(1) << \"Http2SettingFields: setting_fields=\" << setting_fields;\n CurrentFrame()->OnSetting(setting_fields);\n }\n void OnSettingsEnd() override {\n QUICHE_VLOG(1) << \"OnSettingsEnd\";\n EndFrame()->OnSettingsEnd();\n }\n void OnSettingsAck(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnSettingsAck: \" << header;\n StartAndEndFrame(header)->OnSettingsAck(header);\n }\n void OnFrameSizeError(const Http2FrameHeader& header) override {\n QUICHE_VLOG(1) << \"OnFrameSizeError: \" << header;\n FrameError(header)->OnFrameSizeError(header);\n }\n};\nclass SettingsPayloadDecoderTest\n : public AbstractPayloadDecoderTest {\n protected:\n Http2SettingFields RandSettingsFields() {\n Http2SettingFields fields;\n test::Randomize(&fields, RandomPtr());\n return fields;\n }\n};\nTEST_F(SettingsPayloadDecoderTest, SettingsWrongSize) {\n auto approve_size = [](size_t size) {\n return 0 != (size % Http2SettingFields::EncodedSize());\n };\n Http2FrameBuilder fb;\n fb.Append(RandSettingsFields());\n fb.Append(RandSettingsFields());\n fb.Append(RandSettingsFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));\n}\nTEST_F(SettingsPayloadDecoderTest, SettingsAkcWrongSize) {\n auto approve_size = [](size_t size) { return size != 0; };\n Http2FrameBuilder fb;\n fb.Append(RandSettingsFields());\n fb.Append(RandSettingsFields());\n fb.Append(RandSettingsFields());\n EXPECT_TRUE(VerifyDetectsFrameSizeError(Http2FrameFlag::ACK, fb.buffer(),\n approve_size));\n}\nTEST_F(SettingsPayloadDecoderTest, SettingsAck) {\n for (int stream_id = 0; stream_id < 3; ++stream_id) {\n Http2FrameHeader header(0, Http2FrameType::SETTINGS,\n RandFlags() | Http2FrameFlag::ACK, stream_id);\n set_frame_header(header);\n FrameParts expected(header);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(\"\", expected));\n }\n}\nTEST_F(SettingsPayloadDecoderTest, OneRealSetting) {\n std::vector values = {0, 1, 0xffffffff, Random().Rand32()};\n for (auto param : AllHttp2SettingsParameters()) {\n for (uint32_t value : values) {\n Http2SettingFields fields(param, value);\n Http2FrameBuilder fb;\n fb.Append(fields);\n Http2FrameHeader header(fb.size(), Http2FrameType::SETTINGS, RandFlags(),\n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n expected.AppendSetting(fields);\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n }\n }\n}\nTEST_F(SettingsPayloadDecoderTest, ManySettings) {\n const size_t num_settings = 100;\n const size_t size = Http2SettingFields::EncodedSize() * num_settings;\n Http2FrameHeader header(size, Http2FrameType::SETTINGS,\n RandFlags(), \n RandStreamId());\n set_frame_header(header);\n FrameParts expected(header);\n Http2FrameBuilder fb;\n for (size_t n = 0; n < num_settings; ++n) {\n Http2SettingFields fields(static_cast(n),\n Random().Rand32());\n fb.Append(fields);\n expected.AppendSetting(fields);\n }\n ASSERT_EQ(size, fb.size());\n EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));\n}\n} \n} \n} "}}},{"rowIdx":433,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_HTTP2_HPACK_CONSTANTS_H_\n#define QUICHE_HTTP2_HPACK_HTTP2_HPACK_CONSTANTS_H_\n#include \n#include \n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nconst size_t kFirstDynamicTableIndex = 62;\nenum class HpackEntryType {\n kIndexedHeader,\n kIndexedLiteralHeader,\n kUnindexedLiteralHeader,\n kNeverIndexedLiteralHeader,\n kDynamicTableSizeUpdate,\n};\nQUICHE_EXPORT std::string HpackEntryTypeToString(HpackEntryType v);\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out, HpackEntryType v);\n} \n#endif \n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \n#include \n#include \"absl/strings/str_cat.h\"\nnamespace http2 {\nstd::string HpackEntryTypeToString(HpackEntryType v) {\n switch (v) {\n case HpackEntryType::kIndexedHeader:\n return \"kIndexedHeader\";\n case HpackEntryType::kDynamicTableSizeUpdate:\n return \"kDynamicTableSizeUpdate\";\n case HpackEntryType::kIndexedLiteralHeader:\n return \"kIndexedLiteralHeader\";\n case HpackEntryType::kUnindexedLiteralHeader:\n return \"kUnindexedLiteralHeader\";\n case HpackEntryType::kNeverIndexedLiteralHeader:\n return \"kNeverIndexedLiteralHeader\";\n }\n return absl::StrCat(\"UnknownHpackEntryType(\", static_cast(v), \")\");\n}\nstd::ostream& operator<<(std::ostream& out, HpackEntryType v) {\n return out << HpackEntryTypeToString(v);\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(HpackEntryTypeTest, HpackEntryTypeToString) {\n EXPECT_EQ(\"kIndexedHeader\",\n HpackEntryTypeToString(HpackEntryType::kIndexedHeader));\n EXPECT_EQ(\"kDynamicTableSizeUpdate\",\n HpackEntryTypeToString(HpackEntryType::kDynamicTableSizeUpdate));\n EXPECT_EQ(\"kIndexedLiteralHeader\",\n HpackEntryTypeToString(HpackEntryType::kIndexedLiteralHeader));\n EXPECT_EQ(\"kUnindexedLiteralHeader\",\n HpackEntryTypeToString(HpackEntryType::kUnindexedLiteralHeader));\n EXPECT_EQ(\"kNeverIndexedLiteralHeader\",\n HpackEntryTypeToString(HpackEntryType::kNeverIndexedLiteralHeader));\n EXPECT_EQ(\"UnknownHpackEntryType(12321)\",\n HpackEntryTypeToString(static_cast(12321)));\n}\nTEST(HpackEntryTypeTest, OutputHpackEntryType) {\n {\n std::stringstream log;\n log << HpackEntryType::kIndexedHeader;\n EXPECT_EQ(\"kIndexedHeader\", log.str());\n }\n {\n std::stringstream log;\n log << HpackEntryType::kDynamicTableSizeUpdate;\n EXPECT_EQ(\"kDynamicTableSizeUpdate\", log.str());\n }\n {\n std::stringstream log;\n log << HpackEntryType::kIndexedLiteralHeader;\n EXPECT_EQ(\"kIndexedLiteralHeader\", log.str());\n }\n {\n std::stringstream log;\n log << HpackEntryType::kUnindexedLiteralHeader;\n EXPECT_EQ(\"kUnindexedLiteralHeader\", log.str());\n }\n {\n std::stringstream log;\n log << HpackEntryType::kNeverIndexedLiteralHeader;\n EXPECT_EQ(\"kNeverIndexedLiteralHeader\", log.str());\n }\n {\n std::stringstream log;\n log << static_cast(1234321);\n EXPECT_EQ(\"UnknownHpackEntryType(1234321)\", log.str());\n }\n}\n} \n} \n} "}}},{"rowIdx":434,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_TYPE_DECODER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_TYPE_DECODER_H_\n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/hpack/varint/hpack_varint_decoder.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackEntryTypeDecoder {\n public:\n DecodeStatus Start(DecodeBuffer* db);\n DecodeStatus Resume(DecodeBuffer* db) { return varint_decoder_.Resume(db); }\n HpackEntryType entry_type() const { return entry_type_; }\n uint64_t varint() const { return varint_decoder_.value(); }\n std::string DebugString() const;\n private:\n HpackVarintDecoder varint_decoder_;\n HpackEntryType entry_type_ = HpackEntryType::kIndexedHeader;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackEntryTypeDecoder& v);\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_entry_type_decoder.h\"\n#include \n#include \n#include \n#include \"absl/strings/str_cat.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::string HpackEntryTypeDecoder::DebugString() const {\n return absl::StrCat(\n \"HpackEntryTypeDecoder(varint_decoder=\", varint_decoder_.DebugString(),\n \", entry_type=\", entry_type_, \")\");\n}\nstd::ostream& operator<<(std::ostream& out, const HpackEntryTypeDecoder& v) {\n return out << v.DebugString();\n}\nDecodeStatus HpackEntryTypeDecoder::Start(DecodeBuffer* db) {\n QUICHE_DCHECK(db != nullptr);\n QUICHE_DCHECK(db->HasData());\n uint8_t byte = db->DecodeUInt8();\n switch (byte) {\n case 0b00000000:\n case 0b00000001:\n case 0b00000010:\n case 0b00000011:\n case 0b00000100:\n case 0b00000101:\n case 0b00000110:\n case 0b00000111:\n case 0b00001000:\n case 0b00001001:\n case 0b00001010:\n case 0b00001011:\n case 0b00001100:\n case 0b00001101:\n case 0b00001110:\n entry_type_ = HpackEntryType::kUnindexedLiteralHeader;\n varint_decoder_.set_value(byte);\n return DecodeStatus::kDecodeDone;\n case 0b00001111:\n entry_type_ = HpackEntryType::kUnindexedLiteralHeader;\n return varint_decoder_.StartExtended(4, db);\n case 0b00010000:\n case 0b00010001:\n case 0b00010010:\n case 0b00010011:\n case 0b00010100:\n case 0b00010101:\n case 0b00010110:\n case 0b00010111:\n case 0b00011000:\n case 0b00011001:\n case 0b00011010:\n case 0b00011011:\n case 0b00011100:\n case 0b00011101:\n case 0b00011110:\n entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader;\n varint_decoder_.set_value(byte & 0x0f);\n return DecodeStatus::kDecodeDone;\n case 0b00011111:\n entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader;\n return varint_decoder_.StartExtended(4, db);\n case 0b00100000:\n case 0b00100001:\n case 0b00100010:\n case 0b00100011:\n case 0b00100100:\n case 0b00100101:\n case 0b00100110:\n case 0b00100111:\n case 0b00101000:\n case 0b00101001:\n case 0b00101010:\n case 0b00101011:\n case 0b00101100:\n case 0b00101101:\n case 0b00101110:\n case 0b00101111:\n case 0b00110000:\n case 0b00110001:\n case 0b00110010:\n case 0b00110011:\n case 0b00110100:\n case 0b00110101:\n case 0b00110110:\n case 0b00110111:\n case 0b00111000:\n case 0b00111001:\n case 0b00111010:\n case 0b00111011:\n case 0b00111100:\n case 0b00111101:\n case 0b00111110:\n entry_type_ = HpackEntryType::kDynamicTableSizeUpdate;\n varint_decoder_.set_value(byte & 0x01f);\n return DecodeStatus::kDecodeDone;\n case 0b00111111:\n entry_type_ = HpackEntryType::kDynamicTableSizeUpdate;\n return varint_decoder_.StartExtended(5, db);\n case 0b01000000:\n case 0b01000001:\n case 0b01000010:\n case 0b01000011:\n case 0b01000100:\n case 0b01000101:\n case 0b01000110:\n case 0b01000111:\n case 0b01001000:\n case 0b01001001:\n case 0b01001010:\n case 0b01001011:\n case 0b01001100:\n case 0b01001101:\n case 0b01001110:\n case 0b01001111:\n case 0b01010000:\n case 0b01010001:\n case 0b01010010:\n case 0b01010011:\n case 0b01010100:\n case 0b01010101:\n case 0b01010110:\n case 0b01010111:\n case 0b01011000:\n case 0b01011001:\n case 0b01011010:\n case 0b01011011:\n case 0b01011100:\n case 0b01011101:\n case 0b01011110:\n case 0b01011111:\n case 0b01100000:\n case 0b01100001:\n case 0b01100010:\n case 0b01100011:\n case 0b01100100:\n case 0b01100101:\n case 0b01100110:\n case 0b01100111:\n case 0b01101000:\n case 0b01101001:\n case 0b01101010:\n case 0b01101011:\n case 0b01101100:\n case 0b01101101:\n case 0b01101110:\n case 0b01101111:\n case 0b01110000:\n case 0b01110001:\n case 0b01110010:\n case 0b01110011:\n case 0b01110100:\n case 0b01110101:\n case 0b01110110:\n case 0b01110111:\n case 0b01111000:\n case 0b01111001:\n case 0b01111010:\n case 0b01111011:\n case 0b01111100:\n case 0b01111101:\n case 0b01111110:\n entry_type_ = HpackEntryType::kIndexedLiteralHeader;\n varint_decoder_.set_value(byte & 0x03f);\n return DecodeStatus::kDecodeDone;\n case 0b01111111:\n entry_type_ = HpackEntryType::kIndexedLiteralHeader;\n return varint_decoder_.StartExtended(6, db);\n case 0b10000000:\n case 0b10000001:\n case 0b10000010:\n case 0b10000011:\n case 0b10000100:\n case 0b10000101:\n case 0b10000110:\n case 0b10000111:\n case 0b10001000:\n case 0b10001001:\n case 0b10001010:\n case 0b10001011:\n case 0b10001100:\n case 0b10001101:\n case 0b10001110:\n case 0b10001111:\n case 0b10010000:\n case 0b10010001:\n case 0b10010010:\n case 0b10010011:\n case 0b10010100:\n case 0b10010101:\n case 0b10010110:\n case 0b10010111:\n case 0b10011000:\n case 0b10011001:\n case 0b10011010:\n case 0b10011011:\n case 0b10011100:\n case 0b10011101:\n case 0b10011110:\n case 0b10011111:\n case 0b10100000:\n case 0b10100001:\n case 0b10100010:\n case 0b10100011:\n case 0b10100100:\n case 0b10100101:\n case 0b10100110:\n case 0b10100111:\n case 0b10101000:\n case 0b10101001:\n case 0b10101010:\n case 0b10101011:\n case 0b10101100:\n case 0b10101101:\n case 0b10101110:\n case 0b10101111:\n case 0b10110000:\n case 0b10110001:\n case 0b10110010:\n case 0b10110011:\n case 0b10110100:\n case 0b10110101:\n case 0b10110110:\n case 0b10110111:\n case 0b10111000:\n case 0b10111001:\n case 0b10111010:\n case 0b10111011:\n case 0b10111100:\n case 0b10111101:\n case 0b10111110:\n case 0b10111111:\n case 0b11000000:\n case 0b11000001:\n case 0b11000010:\n case 0b11000011:\n case 0b11000100:\n case 0b11000101:\n case 0b11000110:\n case 0b11000111:\n case 0b11001000:\n case 0b11001001:\n case 0b11001010:\n case 0b11001011:\n case 0b11001100:\n case 0b11001101:\n case 0b11001110:\n case 0b11001111:\n case 0b11010000:\n case 0b11010001:\n case 0b11010010:\n case 0b11010011:\n case 0b11010100:\n case 0b11010101:\n case 0b11010110:\n case 0b11010111:\n case 0b11011000:\n case 0b11011001:\n case 0b11011010:\n case 0b11011011:\n case 0b11011100:\n case 0b11011101:\n case 0b11011110:\n case 0b11011111:\n case 0b11100000:\n case 0b11100001:\n case 0b11100010:\n case 0b11100011:\n case 0b11100100:\n case 0b11100101:\n case 0b11100110:\n case 0b11100111:\n case 0b11101000:\n case 0b11101001:\n case 0b11101010:\n case 0b11101011:\n case 0b11101100:\n case 0b11101101:\n case 0b11101110:\n case 0b11101111:\n case 0b11110000:\n case 0b11110001:\n case 0b11110010:\n case 0b11110011:\n case 0b11110100:\n case 0b11110101:\n case 0b11110110:\n case 0b11110111:\n case 0b11111000:\n case 0b11111001:\n case 0b11111010:\n case 0b11111011:\n case 0b11111100:\n case 0b11111101:\n case 0b11111110:\n entry_type_ = HpackEntryType::kIndexedHeader;\n varint_decoder_.set_value(byte & 0x07f);\n return DecodeStatus::kDecodeDone;\n case 0b11111111:\n entry_type_ = HpackEntryType::kIndexedHeader;\n return varint_decoder_.StartExtended(7, db);\n }\n QUICHE_BUG(http2_bug_66_1)\n << \"Unreachable, byte=\" << std::hex << static_cast(byte);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 17, 23);\n return DecodeStatus::kDecodeError;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_entry_type_decoder.h\"\n#include \n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nnamespace {\nconst bool kReturnNonZeroOnFirst = true;\nclass HpackEntryTypeDecoderTest : public RandomDecoderTest {\n protected:\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n QUICHE_CHECK_LT(0u, b->Remaining());\n return decoder_.Start(b);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n return decoder_.Resume(b);\n }\n HpackEntryTypeDecoder decoder_;\n};\nTEST_F(HpackEntryTypeDecoderTest, DynamicTableSizeUpdate) {\n for (uint32_t size = 0; size < 1000 * 1000; size += 256) {\n HpackBlockBuilder bb;\n bb.AppendDynamicTableSizeUpdate(size);\n DecodeBuffer db(bb.buffer());\n auto validator = [size, this]() -> AssertionResult {\n HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate,\n decoder_.entry_type());\n HTTP2_VERIFY_EQ(size, decoder_.varint());\n return AssertionSuccess();\n };\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst,\n ValidateDoneAndEmpty(validator)))\n << \"\\nentry_type=kDynamicTableSizeUpdate, size=\" << size;\n EXPECT_TRUE(validator());\n }\n}\nTEST_F(HpackEntryTypeDecoderTest, HeaderWithIndex) {\n std::vector entry_types = {\n HpackEntryType::kIndexedHeader,\n HpackEntryType::kIndexedLiteralHeader,\n HpackEntryType::kUnindexedLiteralHeader,\n HpackEntryType::kNeverIndexedLiteralHeader,\n };\n for (const HpackEntryType entry_type : entry_types) {\n const uint32_t first = entry_type == HpackEntryType::kIndexedHeader ? 1 : 0;\n for (uint32_t index = first; index < 1000; ++index) {\n HpackBlockBuilder bb;\n bb.AppendEntryTypeAndVarint(entry_type, index);\n DecodeBuffer db(bb.buffer());\n auto validator = [entry_type, index, this]() -> AssertionResult {\n HTTP2_VERIFY_EQ(entry_type, decoder_.entry_type());\n HTTP2_VERIFY_EQ(index, decoder_.varint());\n return AssertionSuccess();\n };\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst,\n ValidateDoneAndEmpty(validator)))\n << \"\\nentry_type=\" << entry_type << \", index=\" << index;\n EXPECT_TRUE(validator());\n }\n }\n}\n} \n} \n} "}}},{"rowIdx":435,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_STRING_DECODER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_STRING_DECODER_H_\n#include \n#include \n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/hpack/varint/hpack_varint_decoder.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackStringDecoder {\n public:\n enum StringDecoderState {\n kStartDecodingLength,\n kDecodingString,\n kResumeDecodingLength,\n };\n template \n DecodeStatus Start(DecodeBuffer* db, Listener* cb) {\n if (db->HasData() && (*db->cursor() & 0x7f) != 0x7f) {\n uint8_t h_and_prefix = db->DecodeUInt8();\n uint8_t length = h_and_prefix & 0x7f;\n bool huffman_encoded = (h_and_prefix & 0x80) == 0x80;\n cb->OnStringStart(huffman_encoded, length);\n if (length <= db->Remaining()) {\n cb->OnStringData(db->cursor(), length);\n db->AdvanceCursor(length);\n cb->OnStringEnd();\n return DecodeStatus::kDecodeDone;\n }\n huffman_encoded_ = huffman_encoded;\n remaining_ = length;\n state_ = kDecodingString;\n return Resume(db, cb);\n }\n state_ = kStartDecodingLength;\n return Resume(db, cb);\n }\n template \n DecodeStatus Resume(DecodeBuffer* db, Listener* cb) {\n DecodeStatus status;\n while (true) {\n switch (state_) {\n case kStartDecodingLength:\n QUICHE_DVLOG(2) << \"kStartDecodingLength: db->Remaining=\"\n << db->Remaining();\n if (!StartDecodingLength(db, cb, &status)) {\n return status;\n }\n ABSL_FALLTHROUGH_INTENDED;\n case kDecodingString:\n QUICHE_DVLOG(2) << \"kDecodingString: db->Remaining=\"\n << db->Remaining() << \" remaining_=\" << remaining_;\n return DecodeString(db, cb);\n case kResumeDecodingLength:\n QUICHE_DVLOG(2) << \"kResumeDecodingLength: db->Remaining=\"\n << db->Remaining();\n if (!ResumeDecodingLength(db, cb, &status)) {\n return status;\n }\n }\n }\n }\n std::string DebugString() const;\n private:\n static std::string StateToString(StringDecoderState v);\n template \n bool StartDecodingLength(DecodeBuffer* db, Listener* cb,\n DecodeStatus* status) {\n if (db->Empty()) {\n *status = DecodeStatus::kDecodeInProgress;\n state_ = kStartDecodingLength;\n return false;\n }\n uint8_t h_and_prefix = db->DecodeUInt8();\n huffman_encoded_ = (h_and_prefix & 0x80) == 0x80;\n *status = length_decoder_.Start(h_and_prefix, 7, db);\n if (*status == DecodeStatus::kDecodeDone) {\n OnStringStart(cb, status);\n return true;\n }\n state_ = kResumeDecodingLength;\n return false;\n }\n template \n bool ResumeDecodingLength(DecodeBuffer* db, Listener* cb,\n DecodeStatus* status) {\n QUICHE_DCHECK_EQ(state_, kResumeDecodingLength);\n *status = length_decoder_.Resume(db);\n if (*status == DecodeStatus::kDecodeDone) {\n state_ = kDecodingString;\n OnStringStart(cb, status);\n return true;\n }\n return false;\n }\n template \n void OnStringStart(Listener* cb, DecodeStatus* ) {\n remaining_ = static_cast(length_decoder_.value());\n cb->OnStringStart(huffman_encoded_, remaining_);\n }\n template \n DecodeStatus DecodeString(DecodeBuffer* db, Listener* cb) {\n size_t len = std::min(remaining_, db->Remaining());\n if (len > 0) {\n cb->OnStringData(db->cursor(), len);\n db->AdvanceCursor(len);\n remaining_ -= len;\n }\n if (remaining_ == 0) {\n cb->OnStringEnd();\n return DecodeStatus::kDecodeDone;\n }\n state_ = kDecodingString;\n return DecodeStatus::kDecodeInProgress;\n }\n HpackVarintDecoder length_decoder_;\n size_t remaining_ = 0;\n StringDecoderState state_ = kStartDecodingLength;\n bool huffman_encoded_ = false;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackStringDecoder& v);\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_string_decoder.h\"\n#include \n#include \n#include \"absl/strings/str_cat.h\"\nnamespace http2 {\nstd::string HpackStringDecoder::DebugString() const {\n return absl::StrCat(\"HpackStringDecoder(state=\", StateToString(state_),\n \", length=\", length_decoder_.DebugString(),\n \", remaining=\", remaining_,\n \", huffman=\", huffman_encoded_ ? \"true)\" : \"false)\");\n}\nstd::string HpackStringDecoder::StateToString(StringDecoderState v) {\n switch (v) {\n case kStartDecodingLength:\n return \"kStartDecodingLength\";\n case kDecodingString:\n return \"kDecodingString\";\n case kResumeDecodingLength:\n return \"kResumeDecodingLength\";\n }\n return absl::StrCat(\"UNKNOWN_STATE(\", static_cast(v), \")\");\n}\nstd::ostream& operator<<(std::ostream& out, const HpackStringDecoder& v) {\n return out << v.DebugString();\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_string_decoder.h\"\n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/decoder/hpack_string_decoder_listener.h\"\n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_string_collector.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nconst bool kMayReturnZeroOnFirst = false;\nconst bool kCompressed = true;\nconst bool kUncompressed = false;\nclass HpackStringDecoderTest : public RandomDecoderTest {\n protected:\n HpackStringDecoderTest() : listener_(&collector_) {}\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n ++start_decoding_calls_;\n collector_.Clear();\n return decoder_.Start(b, &listener_);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n QUICHE_VLOG(1) << decoder_.DebugString();\n QUICHE_VLOG(2) << collector_;\n return decoder_.Resume(b, &listener_);\n }\n AssertionResult Collected(absl::string_view s, bool huffman_encoded) {\n QUICHE_VLOG(1) << collector_;\n return collector_.Collected(s, huffman_encoded);\n }\n Validator MakeValidator(const std::string& expected_str,\n bool expected_huffman) {\n return [expected_str, expected_huffman, this](\n const DecodeBuffer& ,\n DecodeStatus ) -> AssertionResult {\n AssertionResult result = Collected(expected_str, expected_huffman);\n if (result) {\n HTTP2_VERIFY_EQ(collector_,\n HpackStringCollector(expected_str, expected_huffman));\n } else {\n HTTP2_VERIFY_NE(collector_,\n HpackStringCollector(expected_str, expected_huffman));\n }\n QUICHE_VLOG(2) << collector_.ToString();\n collector_.Clear();\n QUICHE_VLOG(2) << collector_;\n return result;\n };\n }\n HpackStringDecoder decoder_;\n HpackStringCollector collector_;\n HpackStringDecoderVLoggingListener listener_;\n size_t start_decoding_calls_ = 0;\n};\nTEST_F(HpackStringDecoderTest, DecodeEmptyString) {\n {\n Validator validator = ValidateDoneAndEmpty(MakeValidator(\"\", kCompressed));\n const char kData[] = {'\\x80'};\n DecodeBuffer b(kData);\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));\n }\n {\n Validator validator =\n ValidateDoneAndOffset(1, MakeValidator(\"\", kUncompressed));\n const char kData[] = {'\\x00', '\\xff'};\n DecodeBuffer b(kData);\n EXPECT_EQ(2u, b.Remaining());\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));\n EXPECT_EQ(1u, b.Remaining());\n }\n}\nTEST_F(HpackStringDecoderTest, DecodeShortString) {\n {\n Validator validator =\n ValidateDoneAndOffset(11, MakeValidator(\"start end.\", kCompressed));\n const char kData[] = \"\\x8astart end.Don't peek at this.\";\n DecodeBuffer b(kData);\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));\n }\n {\n Validator validator =\n ValidateDoneAndOffset(11, MakeValidator(\"start end.\", kUncompressed));\n absl::string_view data(\"\\x0astart end.\");\n DecodeBuffer b(data);\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));\n }\n}\nTEST_F(HpackStringDecoderTest, DecodeLongStrings) {\n std::string name = Random().RandString(1024);\n std::string value = Random().RandString(65536);\n HpackBlockBuilder hbb;\n hbb.AppendString(false, name);\n uint32_t offset_after_name = hbb.size();\n EXPECT_EQ(3 + name.size(), offset_after_name);\n hbb.AppendString(true, value);\n uint32_t offset_after_value = hbb.size();\n EXPECT_EQ(3 + name.size() + 4 + value.size(), offset_after_value);\n DecodeBuffer b(hbb.buffer());\n EXPECT_TRUE(DecodeAndValidateSeveralWays(\n &b, kMayReturnZeroOnFirst,\n ValidateDoneAndOffset(offset_after_name,\n MakeValidator(name, kUncompressed))));\n EXPECT_EQ(offset_after_name, b.Offset());\n EXPECT_EQ(offset_after_value - offset_after_name, b.Remaining());\n EXPECT_TRUE(DecodeAndValidateSeveralWays(\n &b, kMayReturnZeroOnFirst,\n ValidateDoneAndOffset(offset_after_value - offset_after_name,\n MakeValidator(value, kCompressed))));\n EXPECT_EQ(offset_after_value, b.Offset());\n EXPECT_EQ(0u, b.Remaining());\n}\n} \n} \n} "}}},{"rowIdx":436,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/huffman/hpack_huffman_decoder.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackDecoderStringBuffer {\n public:\n enum class State : uint8_t { RESET, COLLECTING, COMPLETE };\n enum class Backing : uint8_t { RESET, UNBUFFERED, BUFFERED };\n HpackDecoderStringBuffer();\n ~HpackDecoderStringBuffer();\n HpackDecoderStringBuffer(const HpackDecoderStringBuffer&) = delete;\n HpackDecoderStringBuffer& operator=(const HpackDecoderStringBuffer&) = delete;\n void Reset();\n void OnStart(bool huffman_encoded, size_t len);\n bool OnData(const char* data, size_t len);\n bool OnEnd();\n void BufferStringIfUnbuffered();\n bool IsBuffered() const;\n size_t BufferedLength() const;\n absl::string_view str() const;\n absl::string_view GetStringIfComplete() const;\n std::string ReleaseString();\n State state_for_testing() const { return state_; }\n Backing backing_for_testing() const { return backing_; }\n void OutputDebugStringTo(std::ostream& out) const;\n private:\n std::string buffer_;\n absl::string_view value_;\n HpackHuffmanDecoder decoder_;\n size_t remaining_len_;\n bool is_huffman_encoded_;\n State state_;\n Backing backing_;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackDecoderStringBuffer& v);\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h\"\n#include \n#include \n#include \n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nstd::ostream& operator<<(std::ostream& out,\n const HpackDecoderStringBuffer::State v) {\n switch (v) {\n case HpackDecoderStringBuffer::State::RESET:\n return out << \"RESET\";\n case HpackDecoderStringBuffer::State::COLLECTING:\n return out << \"COLLECTING\";\n case HpackDecoderStringBuffer::State::COMPLETE:\n return out << \"COMPLETE\";\n }\n int unknown = static_cast(v);\n QUICHE_BUG(http2_bug_50_1)\n << \"Invalid HpackDecoderStringBuffer::State: \" << unknown;\n return out << \"HpackDecoderStringBuffer::State(\" << unknown << \")\";\n}\nstd::ostream& operator<<(std::ostream& out,\n const HpackDecoderStringBuffer::Backing v) {\n switch (v) {\n case HpackDecoderStringBuffer::Backing::RESET:\n return out << \"RESET\";\n case HpackDecoderStringBuffer::Backing::UNBUFFERED:\n return out << \"UNBUFFERED\";\n case HpackDecoderStringBuffer::Backing::BUFFERED:\n return out << \"BUFFERED\";\n }\n auto v2 = static_cast(v);\n QUICHE_BUG(http2_bug_50_2)\n << \"Invalid HpackDecoderStringBuffer::Backing: \" << v2;\n return out << \"HpackDecoderStringBuffer::Backing(\" << v2 << \")\";\n}\nHpackDecoderStringBuffer::HpackDecoderStringBuffer()\n : remaining_len_(0),\n is_huffman_encoded_(false),\n state_(State::RESET),\n backing_(Backing::RESET) {}\nHpackDecoderStringBuffer::~HpackDecoderStringBuffer() = default;\nvoid HpackDecoderStringBuffer::Reset() {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::Reset\";\n state_ = State::RESET;\n}\nvoid HpackDecoderStringBuffer::OnStart(bool huffman_encoded, size_t len) {\n QUICHE_DVLOG(2) << \"HpackDecoderStringBuffer::OnStart\";\n QUICHE_DCHECK_EQ(state_, State::RESET);\n remaining_len_ = len;\n is_huffman_encoded_ = huffman_encoded;\n state_ = State::COLLECTING;\n if (huffman_encoded) {\n decoder_.Reset();\n buffer_.clear();\n backing_ = Backing::BUFFERED;\n len = len * 8 / 5;\n if (buffer_.capacity() < len) {\n buffer_.reserve(len);\n }\n } else {\n backing_ = Backing::RESET;\n value_ = absl::string_view();\n }\n}\nbool HpackDecoderStringBuffer::OnData(const char* data, size_t len) {\n QUICHE_DVLOG(2) << \"HpackDecoderStringBuffer::OnData state=\" << state_\n << \", backing=\" << backing_;\n QUICHE_DCHECK_EQ(state_, State::COLLECTING);\n QUICHE_DCHECK_LE(len, remaining_len_);\n remaining_len_ -= len;\n if (is_huffman_encoded_) {\n QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);\n return decoder_.Decode(absl::string_view(data, len), &buffer_);\n }\n if (backing_ == Backing::RESET) {\n if (remaining_len_ == 0) {\n value_ = absl::string_view(data, len);\n backing_ = Backing::UNBUFFERED;\n return true;\n }\n backing_ = Backing::BUFFERED;\n buffer_.reserve(remaining_len_ + len);\n buffer_.assign(data, len);\n return true;\n }\n QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);\n buffer_.append(data, len);\n return true;\n}\nbool HpackDecoderStringBuffer::OnEnd() {\n QUICHE_DVLOG(2) << \"HpackDecoderStringBuffer::OnEnd\";\n QUICHE_DCHECK_EQ(state_, State::COLLECTING);\n QUICHE_DCHECK_EQ(0u, remaining_len_);\n if (is_huffman_encoded_) {\n QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);\n if (!decoder_.InputProperlyTerminated()) {\n return false; \n }\n value_ = buffer_;\n } else if (backing_ == Backing::BUFFERED) {\n value_ = buffer_;\n }\n state_ = State::COMPLETE;\n return true;\n}\nvoid HpackDecoderStringBuffer::BufferStringIfUnbuffered() {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::BufferStringIfUnbuffered state=\"\n << state_ << \", backing=\" << backing_;\n if (state_ != State::RESET && backing_ == Backing::UNBUFFERED) {\n QUICHE_DVLOG(2)\n << \"HpackDecoderStringBuffer buffering std::string of length \"\n << value_.size();\n buffer_.assign(value_.data(), value_.size());\n if (state_ == State::COMPLETE) {\n value_ = buffer_;\n }\n backing_ = Backing::BUFFERED;\n }\n}\nbool HpackDecoderStringBuffer::IsBuffered() const {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::IsBuffered\";\n return state_ != State::RESET && backing_ == Backing::BUFFERED;\n}\nsize_t HpackDecoderStringBuffer::BufferedLength() const {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::BufferedLength\";\n return IsBuffered() ? buffer_.size() : 0;\n}\nabsl::string_view HpackDecoderStringBuffer::str() const {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::str\";\n QUICHE_DCHECK_EQ(state_, State::COMPLETE);\n return value_;\n}\nabsl::string_view HpackDecoderStringBuffer::GetStringIfComplete() const {\n if (state_ != State::COMPLETE) {\n return {};\n }\n return str();\n}\nstd::string HpackDecoderStringBuffer::ReleaseString() {\n QUICHE_DVLOG(3) << \"HpackDecoderStringBuffer::ReleaseString\";\n QUICHE_DCHECK_EQ(state_, State::COMPLETE);\n QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);\n if (state_ == State::COMPLETE) {\n state_ = State::RESET;\n if (backing_ == Backing::BUFFERED) {\n return std::move(buffer_);\n } else {\n return std::string(value_);\n }\n }\n return \"\";\n}\nvoid HpackDecoderStringBuffer::OutputDebugStringTo(std::ostream& out) const {\n out << \"{state=\" << state_;\n if (state_ != State::RESET) {\n out << \", backing=\" << backing_;\n out << \", remaining_len=\" << remaining_len_;\n out << \", is_huffman_encoded=\" << is_huffman_encoded_;\n if (backing_ == Backing::BUFFERED) {\n out << \", buffer: \" << buffer_;\n } else {\n out << \", value: \" << value_;\n }\n }\n out << \"}\";\n}\nstd::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer& v) {\n v.OutputDebugStringTo(out);\n return out;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h\"\n#include \n#include \n#include \n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/match.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nusing ::testing::AssertionSuccess;\nusing ::testing::HasSubstr;\nnamespace http2 {\nnamespace test {\nnamespace {\nclass HpackDecoderStringBufferTest : public quiche::test::QuicheTest {\n protected:\n typedef HpackDecoderStringBuffer::State State;\n typedef HpackDecoderStringBuffer::Backing Backing;\n State state() const { return buf_.state_for_testing(); }\n Backing backing() const { return buf_.backing_for_testing(); }\n AssertionResult VerifyLogHasSubstrs(std::initializer_list strs) {\n QUICHE_VLOG(1) << buf_;\n std::ostringstream ss;\n buf_.OutputDebugStringTo(ss);\n std::string dbg_str(ss.str());\n for (const auto& expected : strs) {\n HTTP2_VERIFY_TRUE(absl::StrContains(dbg_str, expected));\n }\n return AssertionSuccess();\n }\n HpackDecoderStringBuffer buf_;\n};\nTEST_F(HpackDecoderStringBufferTest, PlainWhole) {\n absl::string_view data(\"some text.\");\n QUICHE_LOG(INFO) << buf_;\n EXPECT_EQ(state(), State::RESET);\n buf_.OnStart( false, data.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::RESET);\n QUICHE_LOG(INFO) << buf_;\n EXPECT_TRUE(buf_.OnData(data.data(), data.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::UNBUFFERED);\n EXPECT_TRUE(buf_.OnEnd());\n EXPECT_EQ(state(), State::COMPLETE);\n EXPECT_EQ(backing(), Backing::UNBUFFERED);\n EXPECT_EQ(0u, buf_.BufferedLength());\n EXPECT_TRUE(VerifyLogHasSubstrs(\n {\"state=COMPLETE\", \"backing=UNBUFFERED\", \"value: some text.\"}));\n EXPECT_EQ(data.data(), buf_.str().data());\n buf_.BufferStringIfUnbuffered();\n QUICHE_LOG(INFO) << buf_;\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), data.size());\n EXPECT_EQ(data, buf_.str());\n EXPECT_NE(data.data(), buf_.str().data());\n EXPECT_TRUE(VerifyLogHasSubstrs(\n {\"state=COMPLETE\", \"backing=BUFFERED\", \"buffer: some text.\"}));\n}\nTEST_F(HpackDecoderStringBufferTest, PlainSplit) {\n absl::string_view data(\"some text.\");\n absl::string_view part1 = data.substr(0, 1);\n absl::string_view part2 = data.substr(1);\n EXPECT_EQ(state(), State::RESET);\n buf_.OnStart( false, data.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::RESET);\n EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), part1.size());\n QUICHE_LOG(INFO) << buf_;\n EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), data.size());\n EXPECT_TRUE(buf_.OnEnd());\n EXPECT_EQ(state(), State::COMPLETE);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), data.size());\n QUICHE_LOG(INFO) << buf_;\n absl::string_view buffered = buf_.str();\n EXPECT_EQ(data, buffered);\n EXPECT_NE(data.data(), buffered.data());\n buf_.BufferStringIfUnbuffered();\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), data.size());\n EXPECT_EQ(buffered, buf_.str());\n EXPECT_EQ(buffered.data(), buf_.str().data());\n}\nTEST_F(HpackDecoderStringBufferTest, HuffmanWhole) {\n std::string encoded;\n ASSERT_TRUE(absl::HexStringToBytes(\"f1e3c2e5f23a6ba0ab90f4ff\", &encoded));\n absl::string_view decoded(\"www.example.com\");\n EXPECT_EQ(state(), State::RESET);\n buf_.OnStart( true, encoded.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_TRUE(buf_.OnEnd());\n EXPECT_EQ(state(), State::COMPLETE);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), decoded.size());\n EXPECT_EQ(decoded, buf_.str());\n EXPECT_TRUE(VerifyLogHasSubstrs(\n {\"{state=COMPLETE\", \"backing=BUFFERED\", \"buffer: www.example.com}\"}));\n std::string s = buf_.ReleaseString();\n EXPECT_EQ(s, decoded);\n EXPECT_EQ(state(), State::RESET);\n}\nTEST_F(HpackDecoderStringBufferTest, HuffmanSplit) {\n std::string encoded;\n ASSERT_TRUE(absl::HexStringToBytes(\"f1e3c2e5f23a6ba0ab90f4ff\", &encoded));\n std::string part1 = encoded.substr(0, 5);\n std::string part2 = encoded.substr(5);\n absl::string_view decoded(\"www.example.com\");\n EXPECT_EQ(state(), State::RESET);\n buf_.OnStart( true, encoded.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(0u, buf_.BufferedLength());\n QUICHE_LOG(INFO) << buf_;\n EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_GT(buf_.BufferedLength(), 0u);\n EXPECT_LT(buf_.BufferedLength(), decoded.size());\n QUICHE_LOG(INFO) << buf_;\n EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), decoded.size());\n QUICHE_LOG(INFO) << buf_;\n EXPECT_TRUE(buf_.OnEnd());\n EXPECT_EQ(state(), State::COMPLETE);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_EQ(buf_.BufferedLength(), decoded.size());\n EXPECT_EQ(decoded, buf_.str());\n QUICHE_LOG(INFO) << buf_;\n buf_.Reset();\n EXPECT_EQ(state(), State::RESET);\n QUICHE_LOG(INFO) << buf_;\n}\nTEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnData) {\n std::string encoded;\n ASSERT_TRUE(absl::HexStringToBytes(\"ffffffff\", &encoded));\n buf_.OnStart( true, encoded.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_FALSE(buf_.OnData(encoded.data(), encoded.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n QUICHE_LOG(INFO) << buf_;\n}\nTEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnEnd) {\n std::string encoded;\n ASSERT_TRUE(absl::HexStringToBytes(\"00\", &encoded));\n buf_.OnStart( true, encoded.size());\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));\n EXPECT_EQ(state(), State::COLLECTING);\n EXPECT_EQ(backing(), Backing::BUFFERED);\n EXPECT_FALSE(buf_.OnEnd());\n QUICHE_LOG(INFO) << buf_;\n}\n} \n} \n} "}}},{"rowIdx":437,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STATE_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STATE_H_\n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_listener.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_tables.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoding_error.h\"\n#include \"quiche/http2/hpack/decoder/hpack_whole_entry_listener.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass HpackDecoderStatePeer;\n} \nclass QUICHE_EXPORT HpackDecoderState : public HpackWholeEntryListener {\n public:\n explicit HpackDecoderState(HpackDecoderListener* listener);\n ~HpackDecoderState() override;\n HpackDecoderState(const HpackDecoderState&) = delete;\n HpackDecoderState& operator=(const HpackDecoderState&) = delete;\n HpackDecoderListener* listener() const { return listener_; }\n void ApplyHeaderTableSizeSetting(uint32_t max_header_table_size);\n size_t GetCurrentHeaderTableSizeSetting() const {\n return final_header_table_size_;\n }\n void OnHeaderBlockStart();\n void OnIndexedHeader(size_t index) override;\n void OnNameIndexAndLiteralValue(\n HpackEntryType entry_type, size_t name_index,\n HpackDecoderStringBuffer* value_buffer) override;\n void OnLiteralNameAndValue(HpackEntryType entry_type,\n HpackDecoderStringBuffer* name_buffer,\n HpackDecoderStringBuffer* value_buffer) override;\n void OnDynamicTableSizeUpdate(size_t size) override;\n void OnHpackDecodeError(HpackDecodingError error) override;\n void OnHeaderBlockEnd();\n HpackDecodingError error() const { return error_; }\n size_t GetDynamicTableSize() const {\n return decoder_tables_.current_header_table_size();\n }\n const HpackDecoderTables& decoder_tables_for_test() const {\n return decoder_tables_;\n }\n private:\n friend class test::HpackDecoderStatePeer;\n void ReportError(HpackDecodingError error);\n HpackDecoderTables decoder_tables_;\n HpackDecoderListener* listener_;\n uint32_t final_header_table_size_;\n uint32_t lowest_header_table_size_;\n bool require_dynamic_table_size_update_;\n bool allow_dynamic_table_size_update_;\n bool saw_dynamic_table_size_update_;\n HpackDecodingError error_;\n};\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_decoder_state.h\"\n#include \n#include \n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace {\nstd::string ExtractString(HpackDecoderStringBuffer* string_buffer) {\n if (string_buffer->IsBuffered()) {\n return string_buffer->ReleaseString();\n } else {\n auto result = std::string(string_buffer->str());\n string_buffer->Reset();\n return result;\n }\n}\n} \nHpackDecoderState::HpackDecoderState(HpackDecoderListener* listener)\n : listener_(listener),\n final_header_table_size_(Http2SettingsInfo::DefaultHeaderTableSize()),\n lowest_header_table_size_(final_header_table_size_),\n require_dynamic_table_size_update_(false),\n allow_dynamic_table_size_update_(true),\n saw_dynamic_table_size_update_(false),\n error_(HpackDecodingError::kOk) {\n QUICHE_CHECK(listener_);\n}\nHpackDecoderState::~HpackDecoderState() = default;\nvoid HpackDecoderState::ApplyHeaderTableSizeSetting(\n uint32_t header_table_size) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::ApplyHeaderTableSizeSetting(\"\n << header_table_size << \")\";\n QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);\n if (header_table_size < lowest_header_table_size_) {\n lowest_header_table_size_ = header_table_size;\n }\n final_header_table_size_ = header_table_size;\n QUICHE_DVLOG(2) << \"low water mark: \" << lowest_header_table_size_;\n QUICHE_DVLOG(2) << \"final limit: \" << final_header_table_size_;\n}\nvoid HpackDecoderState::OnHeaderBlockStart() {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnHeaderBlockStart\";\n QUICHE_DCHECK(error_ == HpackDecodingError::kOk)\n << HpackDecodingErrorToString(error_);\n QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);\n allow_dynamic_table_size_update_ = true;\n saw_dynamic_table_size_update_ = false;\n require_dynamic_table_size_update_ =\n (lowest_header_table_size_ <\n decoder_tables_.current_header_table_size() ||\n final_header_table_size_ < decoder_tables_.header_table_size_limit());\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnHeaderListStart \"\n << \"require_dynamic_table_size_update_=\"\n << require_dynamic_table_size_update_;\n listener_->OnHeaderListStart();\n}\nvoid HpackDecoderState::OnIndexedHeader(size_t index) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnIndexedHeader: \" << index;\n if (error_ != HpackDecodingError::kOk) {\n return;\n }\n if (require_dynamic_table_size_update_) {\n ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);\n return;\n }\n allow_dynamic_table_size_update_ = false;\n const HpackStringPair* entry = decoder_tables_.Lookup(index);\n if (entry != nullptr) {\n listener_->OnHeader(entry->name, entry->value);\n } else {\n ReportError(HpackDecodingError::kInvalidIndex);\n }\n}\nvoid HpackDecoderState::OnNameIndexAndLiteralValue(\n HpackEntryType entry_type, size_t name_index,\n HpackDecoderStringBuffer* value_buffer) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnNameIndexAndLiteralValue \"\n << entry_type << \", \" << name_index << \", \"\n << value_buffer->str();\n if (error_ != HpackDecodingError::kOk) {\n return;\n }\n if (require_dynamic_table_size_update_) {\n ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);\n return;\n }\n allow_dynamic_table_size_update_ = false;\n const HpackStringPair* entry = decoder_tables_.Lookup(name_index);\n if (entry != nullptr) {\n std::string value(ExtractString(value_buffer));\n listener_->OnHeader(entry->name, value);\n if (entry_type == HpackEntryType::kIndexedLiteralHeader) {\n decoder_tables_.Insert(entry->name, std::move(value));\n }\n } else {\n ReportError(HpackDecodingError::kInvalidNameIndex);\n }\n}\nvoid HpackDecoderState::OnLiteralNameAndValue(\n HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer,\n HpackDecoderStringBuffer* value_buffer) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnLiteralNameAndValue \" << entry_type\n << \", \" << name_buffer->str() << \", \" << value_buffer->str();\n if (error_ != HpackDecodingError::kOk) {\n return;\n }\n if (require_dynamic_table_size_update_) {\n ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);\n return;\n }\n allow_dynamic_table_size_update_ = false;\n std::string name(ExtractString(name_buffer));\n std::string value(ExtractString(value_buffer));\n listener_->OnHeader(name, value);\n if (entry_type == HpackEntryType::kIndexedLiteralHeader) {\n decoder_tables_.Insert(std::move(name), std::move(value));\n }\n}\nvoid HpackDecoderState::OnDynamicTableSizeUpdate(size_t size_limit) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnDynamicTableSizeUpdate \"\n << size_limit << \", required=\"\n << (require_dynamic_table_size_update_ ? \"true\" : \"false\")\n << \", allowed=\"\n << (allow_dynamic_table_size_update_ ? \"true\" : \"false\");\n if (error_ != HpackDecodingError::kOk) {\n return;\n }\n QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);\n if (!allow_dynamic_table_size_update_) {\n ReportError(HpackDecodingError::kDynamicTableSizeUpdateNotAllowed);\n return;\n }\n if (require_dynamic_table_size_update_) {\n if (size_limit > lowest_header_table_size_) {\n ReportError(HpackDecodingError::\n kInitialDynamicTableSizeUpdateIsAboveLowWaterMark);\n return;\n }\n require_dynamic_table_size_update_ = false;\n } else if (size_limit > final_header_table_size_) {\n ReportError(\n HpackDecodingError::kDynamicTableSizeUpdateIsAboveAcknowledgedSetting);\n return;\n }\n decoder_tables_.DynamicTableSizeUpdate(size_limit);\n if (saw_dynamic_table_size_update_) {\n allow_dynamic_table_size_update_ = false;\n } else {\n saw_dynamic_table_size_update_ = true;\n }\n lowest_header_table_size_ = final_header_table_size_;\n}\nvoid HpackDecoderState::OnHpackDecodeError(HpackDecodingError error) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnHpackDecodeError \"\n << HpackDecodingErrorToString(error);\n if (error_ == HpackDecodingError::kOk) {\n ReportError(error);\n }\n}\nvoid HpackDecoderState::OnHeaderBlockEnd() {\n QUICHE_DVLOG(2) << \"HpackDecoderState::OnHeaderBlockEnd\";\n if (error_ != HpackDecodingError::kOk) {\n return;\n }\n if (require_dynamic_table_size_update_) {\n ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);\n } else {\n listener_->OnHeaderListEnd();\n }\n}\nvoid HpackDecoderState::ReportError(HpackDecodingError error) {\n QUICHE_DVLOG(2) << \"HpackDecoderState::ReportError is new=\"\n << (error_ == HpackDecodingError::kOk ? \"true\" : \"false\")\n << \", error: \" << HpackDecodingErrorToString(error);\n if (error_ == HpackDecodingError::kOk) {\n listener_->OnHeaderErrorDetected(HpackDecodingErrorToString(error));\n error_ = error;\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_decoder_state.h\"\n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nusing ::testing::AssertionSuccess;\nusing ::testing::Eq;\nusing ::testing::Mock;\nusing ::testing::StrictMock;\nnamespace http2 {\nnamespace test {\nclass HpackDecoderStatePeer {\n public:\n static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) {\n return &state->decoder_tables_;\n }\n};\nnamespace {\nclass MockHpackDecoderListener : public HpackDecoderListener {\n public:\n MOCK_METHOD(void, OnHeaderListStart, (), (override));\n MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value),\n (override));\n MOCK_METHOD(void, OnHeaderListEnd, (), (override));\n MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message),\n (override));\n};\nenum StringBacking { UNBUFFERED, BUFFERED };\nclass HpackDecoderStateTest : public quiche::test::QuicheTest {\n protected:\n HpackDecoderStateTest() : decoder_state_(&listener_) {}\n HpackDecoderTables* GetDecoderTables() {\n return HpackDecoderStatePeer::GetDecoderTables(&decoder_state_);\n }\n const HpackStringPair* Lookup(size_t index) {\n return GetDecoderTables()->Lookup(index);\n }\n size_t current_header_table_size() {\n return GetDecoderTables()->current_header_table_size();\n }\n size_t header_table_size_limit() {\n return GetDecoderTables()->header_table_size_limit();\n }\n void set_header_table_size_limit(size_t size) {\n GetDecoderTables()->DynamicTableSizeUpdate(size);\n }\n void SetStringBuffer(absl::string_view s, StringBacking backing,\n HpackDecoderStringBuffer* string_buffer) {\n string_buffer->OnStart(false, s.size());\n EXPECT_TRUE(string_buffer->OnData(s.data(), s.size()));\n EXPECT_TRUE(string_buffer->OnEnd());\n if (backing == BUFFERED) {\n string_buffer->BufferStringIfUnbuffered();\n }\n }\n void SetName(absl::string_view s, StringBacking backing) {\n SetStringBuffer(s, backing, &name_buffer_);\n }\n void SetValue(absl::string_view s, StringBacking backing) {\n SetStringBuffer(s, backing, &value_buffer_);\n }\n void SendStartAndVerifyCallback() {\n EXPECT_CALL(listener_, OnHeaderListStart());\n decoder_state_.OnHeaderBlockStart();\n Mock::VerifyAndClearExpectations(&listener_);\n }\n void SendSizeUpdate(size_t size) {\n decoder_state_.OnDynamicTableSizeUpdate(size);\n Mock::VerifyAndClearExpectations(&listener_);\n }\n void SendIndexAndVerifyCallback(size_t index,\n HpackEntryType ,\n absl::string_view expected_name,\n absl::string_view expected_value) {\n EXPECT_CALL(listener_, OnHeader(Eq(expected_name), Eq(expected_value)));\n decoder_state_.OnIndexedHeader(index);\n Mock::VerifyAndClearExpectations(&listener_);\n }\n void SendValueAndVerifyCallback(size_t name_index, HpackEntryType entry_type,\n absl::string_view name,\n absl::string_view value,\n StringBacking value_backing) {\n SetValue(value, value_backing);\n EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value)));\n decoder_state_.OnNameIndexAndLiteralValue(entry_type, name_index,\n &value_buffer_);\n Mock::VerifyAndClearExpectations(&listener_);\n }\n void SendNameAndValueAndVerifyCallback(HpackEntryType entry_type,\n absl::string_view name,\n StringBacking name_backing,\n absl::string_view value,\n StringBacking value_backing) {\n SetName(name, name_backing);\n SetValue(value, value_backing);\n EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value)));\n decoder_state_.OnLiteralNameAndValue(entry_type, &name_buffer_,\n &value_buffer_);\n Mock::VerifyAndClearExpectations(&listener_);\n }\n void SendEndAndVerifyCallback() {\n EXPECT_CALL(listener_, OnHeaderListEnd());\n decoder_state_.OnHeaderBlockEnd();\n Mock::VerifyAndClearExpectations(&listener_);\n }\n AssertionResult VerifyEntry(size_t dynamic_index, absl::string_view name,\n absl::string_view value) {\n const HpackStringPair* entry =\n Lookup(dynamic_index + kFirstDynamicTableIndex - 1);\n HTTP2_VERIFY_NE(entry, nullptr);\n HTTP2_VERIFY_EQ(entry->name, name);\n HTTP2_VERIFY_EQ(entry->value, value);\n return AssertionSuccess();\n }\n AssertionResult VerifyNoEntry(size_t dynamic_index) {\n const HpackStringPair* entry =\n Lookup(dynamic_index + kFirstDynamicTableIndex - 1);\n HTTP2_VERIFY_EQ(entry, nullptr);\n return AssertionSuccess();\n }\n AssertionResult VerifyDynamicTableContents(\n const std::vector>&\n entries) {\n size_t index = 1;\n for (const auto& entry : entries) {\n HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second));\n ++index;\n }\n HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index));\n return AssertionSuccess();\n }\n StrictMock listener_;\n HpackDecoderState decoder_state_;\n HpackDecoderStringBuffer name_buffer_, value_buffer_;\n};\nTEST_F(HpackDecoderStateTest, C3_RequestExamples) {\n SendStartAndVerifyCallback();\n SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, \":method\",\n \"GET\");\n SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, \":scheme\",\n \"http\");\n SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, \":path\", \"/\");\n SendValueAndVerifyCallback(1, HpackEntryType::kIndexedLiteralHeader,\n \":authority\", \"www.example.com\", UNBUFFERED);\n SendEndAndVerifyCallback();\n ASSERT_TRUE(VerifyDynamicTableContents({{\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(57u, current_header_table_size());\n SendStartAndVerifyCallback();\n SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, \":method\",\n \"GET\");\n SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, \":scheme\",\n \"http\");\n SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, \":path\", \"/\");\n SendIndexAndVerifyCallback(62, HpackEntryType::kIndexedHeader, \":authority\",\n \"www.example.com\");\n SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader,\n \"cache-control\", \"no-cache\", UNBUFFERED);\n SendEndAndVerifyCallback();\n ASSERT_TRUE(VerifyDynamicTableContents(\n {{\"cache-control\", \"no-cache\"}, {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(110u, current_header_table_size());\n SendStartAndVerifyCallback();\n SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, \":method\",\n \"GET\");\n SendIndexAndVerifyCallback(7, HpackEntryType::kIndexedHeader, \":scheme\",\n \"https\");\n SendIndexAndVerifyCallback(5, HpackEntryType::kIndexedHeader, \":path\",\n \"/index.html\");\n SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, \":authority\",\n \"www.example.com\");\n SendNameAndValueAndVerifyCallback(HpackEntryType::kIndexedLiteralHeader,\n \"custom-key\", UNBUFFERED, \"custom-value\",\n UNBUFFERED);\n SendEndAndVerifyCallback();\n ASSERT_TRUE(VerifyDynamicTableContents({{\"custom-key\", \"custom-value\"},\n {\"cache-control\", \"no-cache\"},\n {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(164u, current_header_table_size());\n}\nTEST_F(HpackDecoderStateTest, C5_ResponseExamples) {\n set_header_table_size_limit(256);\n SendStartAndVerifyCallback();\n SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader,\n \":status\", \"302\", BUFFERED);\n SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader,\n \"cache-control\", \"private\", UNBUFFERED);\n SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, \"date\",\n \"Mon, 21 Oct 2013 20:13:21 GMT\", UNBUFFERED);\n SendValueAndVerifyCallback(46, HpackEntryType::kIndexedLiteralHeader,\n \"location\", \"https:\n SendEndAndVerifyCallback();\n ASSERT_TRUE(\n VerifyDynamicTableContents({{\"location\", \"https:\n {\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n {\"cache-control\", \"private\"},\n {\":status\", \"302\"}}));\n ASSERT_EQ(222u, current_header_table_size());\n SendStartAndVerifyCallback();\n SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader,\n \":status\", \"307\", BUFFERED);\n SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader,\n \"cache-control\", \"private\");\n SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, \"date\",\n \"Mon, 21 Oct 2013 20:13:21 GMT\");\n SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, \"location\",\n \"https:\n SendEndAndVerifyCallback();\n ASSERT_TRUE(\n VerifyDynamicTableContents({{\":status\", \"307\"},\n {\"location\", \"https:\n {\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n {\"cache-control\", \"private\"}}));\n ASSERT_EQ(222u, current_header_table_size());\n SendStartAndVerifyCallback();\n SendIndexAndVerifyCallback(8, HpackEntryType::kIndexedHeader, \":status\",\n \"200\");\n SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader,\n \"cache-control\", \"private\");\n SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, \"date\",\n \"Mon, 21 Oct 2013 20:13:22 GMT\", BUFFERED);\n SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, \"location\",\n \"https:\n SendValueAndVerifyCallback(26, HpackEntryType::kIndexedLiteralHeader,\n \"content-encoding\", \"gzip\", UNBUFFERED);\n SendValueAndVerifyCallback(\n 55, HpackEntryType::kIndexedLiteralHeader, \"set-cookie\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\", BUFFERED);\n SendEndAndVerifyCallback();\n ASSERT_TRUE(VerifyDynamicTableContents(\n {{\"set-cookie\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\"},\n {\"content-encoding\", \"gzip\"},\n {\"date\", \"Mon, 21 Oct 2013 20:13:22 GMT\"}}));\n ASSERT_EQ(215u, current_header_table_size());\n}\nTEST_F(HpackDecoderStateTest, OptionalTableSizeChanges) {\n SendStartAndVerifyCallback();\n EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),\n header_table_size_limit());\n SendSizeUpdate(1024);\n EXPECT_EQ(1024u, header_table_size_limit());\n SendSizeUpdate(0);\n EXPECT_EQ(0u, header_table_size_limit());\n EXPECT_CALL(listener_, OnHeaderErrorDetected(\n Eq(\"Dynamic table size update not allowed\")));\n SendSizeUpdate(0);\n}\nTEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeHeader) {\n EXPECT_EQ(4096u, decoder_state_.GetCurrentHeaderTableSizeSetting());\n decoder_state_.ApplyHeaderTableSizeSetting(1024);\n decoder_state_.ApplyHeaderTableSizeSetting(2048);\n EXPECT_EQ(2048u, decoder_state_.GetCurrentHeaderTableSizeSetting());\n SendStartAndVerifyCallback();\n EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),\n header_table_size_limit());\n SendSizeUpdate(1024);\n EXPECT_EQ(1024u, header_table_size_limit());\n SendSizeUpdate(1500);\n EXPECT_EQ(1500u, header_table_size_limit());\n SendEndAndVerifyCallback();\n decoder_state_.ApplyHeaderTableSizeSetting(1024);\n EXPECT_EQ(1024u, decoder_state_.GetCurrentHeaderTableSizeSetting());\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(Eq(\"Missing dynamic table size update\")));\n decoder_state_.OnIndexedHeader(1);\n decoder_state_.OnIndexedHeader(1);\n decoder_state_.OnDynamicTableSizeUpdate(1);\n SetValue(\"value\", UNBUFFERED);\n decoder_state_.OnNameIndexAndLiteralValue(\n HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_);\n SetName(\"name\", UNBUFFERED);\n decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,\n &name_buffer_, &value_buffer_);\n decoder_state_.OnHeaderBlockEnd();\n decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError);\n}\nTEST_F(HpackDecoderStateTest, InvalidRequiredSizeUpdate) {\n decoder_state_.ApplyHeaderTableSizeSetting(1024);\n SendStartAndVerifyCallback();\n EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),\n header_table_size_limit());\n EXPECT_CALL(\n listener_,\n OnHeaderErrorDetected(\n Eq(\"Initial dynamic table size update is above low water mark\")));\n SendSizeUpdate(2048);\n}\nTEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeEnd) {\n decoder_state_.ApplyHeaderTableSizeSetting(1024);\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(Eq(\"Missing dynamic table size update\")));\n decoder_state_.OnHeaderBlockEnd();\n}\nTEST_F(HpackDecoderStateTest, InvalidOptionalSizeUpdate) {\n SendStartAndVerifyCallback();\n EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),\n header_table_size_limit());\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(Eq(\n \"Dynamic table size update is above acknowledged setting\")));\n SendSizeUpdate(Http2SettingsInfo::DefaultHeaderTableSize() + 1);\n}\nTEST_F(HpackDecoderStateTest, InvalidStaticIndex) {\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(\n Eq(\"Invalid index in indexed header field representation\")));\n decoder_state_.OnIndexedHeader(0);\n}\nTEST_F(HpackDecoderStateTest, InvalidDynamicIndex) {\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(\n Eq(\"Invalid index in indexed header field representation\")));\n decoder_state_.OnIndexedHeader(kFirstDynamicTableIndex);\n}\nTEST_F(HpackDecoderStateTest, InvalidNameIndex) {\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(Eq(\"Invalid index in literal header field \"\n \"with indexed name representation\")));\n SetValue(\"value\", UNBUFFERED);\n decoder_state_.OnNameIndexAndLiteralValue(\n HpackEntryType::kIndexedLiteralHeader, kFirstDynamicTableIndex,\n &value_buffer_);\n}\nTEST_F(HpackDecoderStateTest, ErrorsSuppressCallbacks) {\n SendStartAndVerifyCallback();\n EXPECT_CALL(listener_,\n OnHeaderErrorDetected(Eq(\"Name Huffman encoding error\")));\n decoder_state_.OnHpackDecodeError(HpackDecodingError::kNameHuffmanError);\n decoder_state_.OnIndexedHeader(1);\n decoder_state_.OnDynamicTableSizeUpdate(1);\n SetValue(\"value\", UNBUFFERED);\n decoder_state_.OnNameIndexAndLiteralValue(\n HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_);\n SetName(\"name\", UNBUFFERED);\n decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,\n &name_buffer_, &value_buffer_);\n decoder_state_.OnHeaderBlockEnd();\n decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError);\n}\n} \n} \n} "}}},{"rowIdx":438,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_BLOCK_DECODER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_BLOCK_DECODER_H_\n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoding_error.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackBlockDecoder {\n public:\n explicit HpackBlockDecoder(HpackEntryDecoderListener* listener)\n : listener_(listener) {\n QUICHE_DCHECK_NE(listener_, nullptr);\n }\n ~HpackBlockDecoder() {}\n HpackBlockDecoder(const HpackBlockDecoder&) = delete;\n HpackBlockDecoder& operator=(const HpackBlockDecoder&) = delete;\n void Reset() {\n QUICHE_DVLOG(2) << \"HpackBlockDecoder::Reset\";\n before_entry_ = true;\n }\n DecodeStatus Decode(DecodeBuffer* db);\n bool before_entry() const { return before_entry_; }\n HpackDecodingError error() const { return entry_decoder_.error(); }\n std::string DebugString() const;\n private:\n HpackEntryDecoder entry_decoder_;\n HpackEntryDecoderListener* const listener_;\n bool before_entry_ = true;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackBlockDecoder& v);\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_block_decoder.h\"\n#include \n#include \n#include \n#include \"absl/strings/str_cat.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nDecodeStatus HpackBlockDecoder::Decode(DecodeBuffer* db) {\n if (!before_entry_) {\n QUICHE_DVLOG(2) << \"HpackBlockDecoder::Decode resume entry, db->Remaining=\"\n << db->Remaining();\n DecodeStatus status = entry_decoder_.Resume(db, listener_);\n switch (status) {\n case DecodeStatus::kDecodeDone:\n before_entry_ = true;\n break;\n case DecodeStatus::kDecodeInProgress:\n QUICHE_DCHECK_EQ(0u, db->Remaining());\n return DecodeStatus::kDecodeInProgress;\n case DecodeStatus::kDecodeError:\n QUICHE_CODE_COUNT_N(decompress_failure_3, 1, 23);\n return DecodeStatus::kDecodeError;\n }\n }\n QUICHE_DCHECK(before_entry_);\n while (db->HasData()) {\n QUICHE_DVLOG(2) << \"HpackBlockDecoder::Decode start entry, db->Remaining=\"\n << db->Remaining();\n DecodeStatus status = entry_decoder_.Start(db, listener_);\n switch (status) {\n case DecodeStatus::kDecodeDone:\n continue;\n case DecodeStatus::kDecodeInProgress:\n QUICHE_DCHECK_EQ(0u, db->Remaining());\n before_entry_ = false;\n return DecodeStatus::kDecodeInProgress;\n case DecodeStatus::kDecodeError:\n QUICHE_CODE_COUNT_N(decompress_failure_3, 2, 23);\n return DecodeStatus::kDecodeError;\n }\n QUICHE_DCHECK(false);\n }\n QUICHE_DCHECK(before_entry_);\n return DecodeStatus::kDecodeDone;\n}\nstd::string HpackBlockDecoder::DebugString() const {\n return absl::StrCat(\n \"HpackBlockDecoder(\", entry_decoder_.DebugString(), \", listener@\",\n absl::Hex(reinterpret_cast(listener_)),\n (before_entry_ ? \", between entries)\" : \", in an entry)\"));\n}\nstd::ostream& operator<<(std::ostream& out, const HpackBlockDecoder& v) {\n return out << v.DebugString();\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_block_decoder.h\"\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_block_collector.h\"\n#include \"quiche/http2/test_tools/hpack_example.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nclass HpackBlockDecoderTest : public RandomDecoderTest {\n protected:\n HpackBlockDecoderTest() : listener_(&collector_), decoder_(&listener_) {\n stop_decode_on_done_ = false;\n decoder_.Reset();\n std::ostringstream strm;\n strm << decoder_;\n }\n DecodeStatus StartDecoding(DecodeBuffer* db) override {\n collector_.Clear();\n decoder_.Reset();\n return ResumeDecoding(db);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* db) override {\n DecodeStatus status = decoder_.Decode(db);\n std::ostringstream strm;\n strm << decoder_;\n return status;\n }\n AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db,\n const Validator& validator) {\n bool return_non_zero_on_first = false;\n return RandomDecoderTest::DecodeAndValidateSeveralWays(\n db, return_non_zero_on_first, validator);\n }\n AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb,\n const Validator& validator) {\n DecodeBuffer db(hbb.buffer());\n return DecodeAndValidateSeveralWays(&db, validator);\n }\n AssertionResult DecodeHpackExampleAndValidateSeveralWays(\n absl::string_view hpack_example, Validator validator) {\n std::string input = HpackExampleToStringOrDie(hpack_example);\n DecodeBuffer db(input);\n return DecodeAndValidateSeveralWays(&db, validator);\n }\n uint8_t Rand8() { return Random().Rand8(); }\n std::string Rand8String() { return Random().RandString(Rand8()); }\n HpackBlockCollector collector_;\n HpackEntryDecoderVLoggingListener listener_;\n HpackBlockDecoder decoder_;\n};\nTEST_F(HpackBlockDecoderTest, SpecExample_C_2_1) {\n auto do_check = [this]() {\n return collector_.ValidateSoleLiteralNameValueHeader(\n HpackEntryType::kIndexedLiteralHeader, false, \"custom-key\", false,\n \"custom-header\");\n };\n const char hpack_example[] = R\"(\n 40 | == Literal indexed ==\n 0a | Literal name (len = 10)\n 6375 7374 6f6d 2d6b 6579 | custom-key\n 0d | Literal value (len = 13)\n 6375 7374 6f6d 2d68 6561 6465 72 | custom-header\n | -> custom-key:\n | custom-header\n )\";\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n hpack_example, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackBlockDecoderTest, SpecExample_C_2_2) {\n auto do_check = [this]() {\n return collector_.ValidateSoleLiteralValueHeader(\n HpackEntryType::kUnindexedLiteralHeader, 4, false, \"/sample/path\");\n };\n const char hpack_example[] = R\"(\n 04 | == Literal not indexed ==\n | Indexed name (idx = 4)\n | :path\n 0c | Literal value (len = 12)\n 2f73 616d 706c 652f 7061 7468 | /sample/path\n | -> :path: /sample/path\n )\";\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n hpack_example, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackBlockDecoderTest, SpecExample_C_2_3) {\n auto do_check = [this]() {\n return collector_.ValidateSoleLiteralNameValueHeader(\n HpackEntryType::kNeverIndexedLiteralHeader, false, \"password\", false,\n \"secret\");\n };\n const char hpack_example[] = R\"(\n 10 | == Literal never indexed ==\n 08 | Literal name (len = 8)\n 7061 7373 776f 7264 | password\n 06 | Literal value (len = 6)\n 7365 6372 6574 | secret\n | -> password: secret\n )\";\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n hpack_example, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackBlockDecoderTest, SpecExample_C_2_4) {\n auto do_check = [this]() { return collector_.ValidateSoleIndexedHeader(2); };\n const char hpack_example[] = R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n )\";\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n hpack_example, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackBlockDecoderTest, SpecExample_C_3_1) {\n std::string example = R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 86 | == Indexed - Add ==\n | idx = 6\n | -> :scheme: http\n 84 | == Indexed - Add ==\n | idx = 4\n | -> :path: /\n 41 | == Literal indexed ==\n | Indexed name (idx = 1)\n | :authority\n 0f | Literal value (len = 15)\n 7777 772e 6578 616d 706c 652e 636f 6d | www.example.com\n | -> :authority:\n | www.example.com\n )\";\n HpackBlockCollector expected;\n expected.ExpectIndexedHeader(2);\n expected.ExpectIndexedHeader(6);\n expected.ExpectIndexedHeader(4);\n expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,\n 1, false, \"www.example.com\");\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n example,\n ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));\n EXPECT_TRUE(collector_.VerifyEq(expected));\n}\nTEST_F(HpackBlockDecoderTest, SpecExample_C_5_1) {\n std::string example = R\"(\n 48 | == Literal indexed ==\n | Indexed name (idx = 8)\n | :status\n 03 | Literal value (len = 3)\n 3330 32 | 302\n | -> :status: 302\n 58 | == Literal indexed ==\n | Indexed name (idx = 24)\n | cache-control\n 07 | Literal value (len = 7)\n 7072 6976 6174 65 | private\n | -> cache-control: private\n 61 | == Literal indexed ==\n | Indexed name (idx = 33)\n | date\n 1d | Literal value (len = 29)\n 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013\n 2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT\n | -> date: Mon, 21 Oct 2013\n | 20:13:21 GMT\n 6e | == Literal indexed ==\n | Indexed name (idx = 46)\n | location\n 17 | Literal value (len = 23)\n 6874 7470 733a 2f2f 7777 772e 6578 616d | https:\n 706c 652e 636f 6d | ple.com\n | -> location:\n | https:\n )\";\n HpackBlockCollector expected;\n expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,\n 8, false, \"302\");\n expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,\n 24, false, \"private\");\n expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,\n 33, false,\n \"Mon, 21 Oct 2013 20:13:21 GMT\");\n expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,\n 46, false, \"https:\n EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(\n example,\n ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));\n EXPECT_TRUE(collector_.VerifyEq(expected));\n}\nTEST_F(HpackBlockDecoderTest, Computed) {\n HpackBlockCollector expected;\n expected.ExpectIndexedHeader(0);\n expected.ExpectIndexedHeader(1);\n expected.ExpectIndexedHeader(126);\n expected.ExpectIndexedHeader(127);\n expected.ExpectIndexedHeader(128);\n expected.ExpectDynamicTableSizeUpdate(0);\n expected.ExpectDynamicTableSizeUpdate(1);\n expected.ExpectDynamicTableSizeUpdate(14);\n expected.ExpectDynamicTableSizeUpdate(15);\n expected.ExpectDynamicTableSizeUpdate(30);\n expected.ExpectDynamicTableSizeUpdate(31);\n expected.ExpectDynamicTableSizeUpdate(4095);\n expected.ExpectDynamicTableSizeUpdate(4096);\n expected.ExpectDynamicTableSizeUpdate(8192);\n for (auto type : {HpackEntryType::kIndexedLiteralHeader,\n HpackEntryType::kUnindexedLiteralHeader,\n HpackEntryType::kNeverIndexedLiteralHeader}) {\n for (bool value_huffman : {false, true}) {\n expected.ExpectNameIndexAndLiteralValue(type, Rand8() + 1, value_huffman,\n Rand8String());\n expected.ExpectLiteralNameAndValue(type, false, Rand8String(),\n value_huffman, Rand8String());\n expected.ExpectLiteralNameAndValue(type, true, Rand8String(),\n value_huffman, Rand8String());\n }\n }\n expected.ShuffleEntries(RandomPtr());\n HpackBlockBuilder hbb;\n expected.AppendToHpackBlockBuilder(&hbb);\n EXPECT_TRUE(DecodeAndValidateSeveralWays(\n hbb,\n ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));\n EXPECT_TRUE(collector_.VerifyEq(expected));\n}\n} \n} \n} "}}},{"rowIdx":439,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_H_\n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/hpack/decoder/hpack_block_decoder.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_listener.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_state.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_tables.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoding_error.h\"\n#include \"quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass HpackDecoderPeer;\n} \nclass QUICHE_EXPORT HpackDecoder {\n public:\n HpackDecoder(HpackDecoderListener* listener, size_t max_string_size);\n virtual ~HpackDecoder();\n HpackDecoder(const HpackDecoder&) = delete;\n HpackDecoder& operator=(const HpackDecoder&) = delete;\n void set_max_string_size_bytes(size_t max_string_size_bytes);\n void ApplyHeaderTableSizeSetting(uint32_t max_header_table_size);\n size_t GetCurrentHeaderTableSizeSetting() const {\n return decoder_state_.GetCurrentHeaderTableSizeSetting();\n }\n bool StartDecodingBlock();\n bool DecodeFragment(DecodeBuffer* db);\n bool EndDecodingBlock();\n bool DetectError();\n size_t GetDynamicTableSize() const {\n return decoder_state_.GetDynamicTableSize();\n }\n HpackDecodingError error() const { return error_; }\n private:\n friend class test::HpackDecoderPeer;\n void ReportError(HpackDecodingError error);\n HpackDecoderState decoder_state_;\n HpackWholeEntryBuffer entry_buffer_;\n HpackBlockDecoder block_decoder_;\n HpackDecodingError error_;\n};\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_decoder.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nHpackDecoder::HpackDecoder(HpackDecoderListener* listener,\n size_t max_string_size)\n : decoder_state_(listener),\n entry_buffer_(&decoder_state_, max_string_size),\n block_decoder_(&entry_buffer_),\n error_(HpackDecodingError::kOk) {}\nHpackDecoder::~HpackDecoder() = default;\nvoid HpackDecoder::set_max_string_size_bytes(size_t max_string_size_bytes) {\n entry_buffer_.set_max_string_size_bytes(max_string_size_bytes);\n}\nvoid HpackDecoder::ApplyHeaderTableSizeSetting(uint32_t max_header_table_size) {\n decoder_state_.ApplyHeaderTableSizeSetting(max_header_table_size);\n}\nbool HpackDecoder::StartDecodingBlock() {\n QUICHE_DVLOG(3) << \"HpackDecoder::StartDecodingBlock, error_detected=\"\n << (DetectError() ? \"true\" : \"false\");\n if (DetectError()) {\n return false;\n }\n block_decoder_.Reset();\n decoder_state_.OnHeaderBlockStart();\n return true;\n}\nbool HpackDecoder::DecodeFragment(DecodeBuffer* db) {\n QUICHE_DVLOG(3) << \"HpackDecoder::DecodeFragment, error_detected=\"\n << (DetectError() ? \"true\" : \"false\")\n << \", size=\" << db->Remaining();\n if (DetectError()) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 3, 23);\n return false;\n }\n DecodeStatus status = block_decoder_.Decode(db);\n if (status == DecodeStatus::kDecodeError) {\n ReportError(block_decoder_.error());\n QUICHE_CODE_COUNT_N(decompress_failure_3, 4, 23);\n return false;\n } else if (DetectError()) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 5, 23);\n return false;\n }\n QUICHE_DCHECK_EQ(block_decoder_.before_entry(),\n status == DecodeStatus::kDecodeDone)\n << status;\n if (!block_decoder_.before_entry()) {\n entry_buffer_.BufferStringsIfUnbuffered();\n }\n return true;\n}\nbool HpackDecoder::EndDecodingBlock() {\n QUICHE_DVLOG(3) << \"HpackDecoder::EndDecodingBlock, error_detected=\"\n << (DetectError() ? \"true\" : \"false\");\n if (DetectError()) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 6, 23);\n return false;\n }\n if (!block_decoder_.before_entry()) {\n ReportError(HpackDecodingError::kTruncatedBlock);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 7, 23);\n return false;\n }\n decoder_state_.OnHeaderBlockEnd();\n if (DetectError()) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 8, 23);\n return false;\n }\n return true;\n}\nbool HpackDecoder::DetectError() {\n if (error_ != HpackDecodingError::kOk) {\n return true;\n }\n if (decoder_state_.error() != HpackDecodingError::kOk) {\n QUICHE_DVLOG(2) << \"Error detected in decoder_state_\";\n QUICHE_CODE_COUNT_N(decompress_failure_3, 10, 23);\n error_ = decoder_state_.error();\n }\n return error_ != HpackDecodingError::kOk;\n}\nvoid HpackDecoder::ReportError(HpackDecodingError error) {\n QUICHE_DVLOG(3) << \"HpackDecoder::ReportError is new=\"\n << (error_ == HpackDecodingError::kOk ? \"true\" : \"false\")\n << \", error: \" << HpackDecodingErrorToString(error);\n if (error_ == HpackDecodingError::kOk) {\n error_ = error;\n decoder_state_.listener()->OnHeaderErrorDetected(\n HpackDecodingErrorToString(error));\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_decoder.h\"\n#include \n#include \n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_listener.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_state.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_tables.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_example.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_util.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nusing ::testing::AssertionSuccess;\nusing ::testing::ElementsAreArray;\nusing ::testing::Eq;\nnamespace http2 {\nnamespace test {\nclass HpackDecoderStatePeer {\n public:\n static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) {\n return &state->decoder_tables_;\n }\n static void set_listener(HpackDecoderState* state,\n HpackDecoderListener* listener) {\n state->listener_ = listener;\n }\n};\nclass HpackDecoderPeer {\n public:\n static HpackDecoderState* GetDecoderState(HpackDecoder* decoder) {\n return &decoder->decoder_state_;\n }\n static HpackDecoderTables* GetDecoderTables(HpackDecoder* decoder) {\n return HpackDecoderStatePeer::GetDecoderTables(GetDecoderState(decoder));\n }\n};\nnamespace {\ntypedef std::pair HpackHeaderEntry;\ntypedef std::vector HpackHeaderEntries;\nclass MockHpackDecoderListener : public HpackDecoderListener {\n public:\n MOCK_METHOD(void, OnHeaderListStart, (), (override));\n MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value),\n (override));\n MOCK_METHOD(void, OnHeaderListEnd, (), (override));\n MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message),\n (override));\n};\nclass HpackDecoderTest : public quiche::test::QuicheTestWithParam,\n public HpackDecoderListener {\n protected:\n HpackDecoderTest() : decoder_(this, 4096) {\n fragment_the_hpack_block_ = GetParam();\n }\n ~HpackDecoderTest() override = default;\n void OnHeaderListStart() override {\n ASSERT_FALSE(saw_start_);\n ASSERT_FALSE(saw_end_);\n saw_start_ = true;\n header_entries_.clear();\n }\n void OnHeader(absl::string_view name, absl::string_view value) override {\n ASSERT_TRUE(saw_start_);\n ASSERT_FALSE(saw_end_);\n header_entries_.emplace_back(name, value);\n }\n void OnHeaderListEnd() override {\n ASSERT_TRUE(saw_start_);\n ASSERT_FALSE(saw_end_);\n ASSERT_TRUE(error_messages_.empty());\n saw_end_ = true;\n }\n void OnHeaderErrorDetected(absl::string_view error_message) override {\n ASSERT_TRUE(saw_start_);\n error_messages_.push_back(std::string(error_message));\n HpackDecoderStatePeer::set_listener(\n HpackDecoderPeer::GetDecoderState(&decoder_), &mock_listener_);\n }\n AssertionResult DecodeBlock(absl::string_view block) {\n QUICHE_VLOG(1) << \"HpackDecoderTest::DecodeBlock\";\n HTTP2_VERIFY_FALSE(decoder_.DetectError());\n HTTP2_VERIFY_TRUE(error_messages_.empty());\n HTTP2_VERIFY_FALSE(saw_start_);\n HTTP2_VERIFY_FALSE(saw_end_);\n header_entries_.clear();\n HTTP2_VERIFY_FALSE(decoder_.DetectError());\n HTTP2_VERIFY_TRUE(decoder_.StartDecodingBlock());\n HTTP2_VERIFY_FALSE(decoder_.DetectError());\n if (fragment_the_hpack_block_) {\n while (!block.empty()) {\n size_t fragment_size = random_.RandomSizeSkewedLow(block.size());\n DecodeBuffer db(block.substr(0, fragment_size));\n HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db));\n HTTP2_VERIFY_EQ(0u, db.Remaining());\n block.remove_prefix(fragment_size);\n }\n } else {\n DecodeBuffer db(block);\n HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db));\n HTTP2_VERIFY_EQ(0u, db.Remaining());\n }\n HTTP2_VERIFY_FALSE(decoder_.DetectError());\n HTTP2_VERIFY_TRUE(decoder_.EndDecodingBlock());\n if (saw_end_) {\n HTTP2_VERIFY_FALSE(decoder_.DetectError());\n HTTP2_VERIFY_TRUE(error_messages_.empty());\n } else {\n HTTP2_VERIFY_TRUE(decoder_.DetectError());\n HTTP2_VERIFY_FALSE(error_messages_.empty());\n }\n saw_start_ = saw_end_ = false;\n return AssertionSuccess();\n }\n const HpackDecoderTables& GetDecoderTables() {\n return *HpackDecoderPeer::GetDecoderTables(&decoder_);\n }\n const HpackStringPair* Lookup(size_t index) {\n return GetDecoderTables().Lookup(index);\n }\n size_t current_header_table_size() {\n return GetDecoderTables().current_header_table_size();\n }\n size_t header_table_size_limit() {\n return GetDecoderTables().header_table_size_limit();\n }\n void set_header_table_size_limit(size_t size) {\n HpackDecoderPeer::GetDecoderTables(&decoder_)->DynamicTableSizeUpdate(size);\n }\n AssertionResult VerifyEntry(size_t dynamic_index, const char* name,\n const char* value) {\n const HpackStringPair* entry =\n Lookup(dynamic_index + kFirstDynamicTableIndex - 1);\n HTTP2_VERIFY_NE(entry, nullptr);\n HTTP2_VERIFY_EQ(entry->name, name);\n HTTP2_VERIFY_EQ(entry->value, value);\n return AssertionSuccess();\n }\n AssertionResult VerifyNoEntry(size_t dynamic_index) {\n const HpackStringPair* entry =\n Lookup(dynamic_index + kFirstDynamicTableIndex - 1);\n HTTP2_VERIFY_EQ(entry, nullptr);\n return AssertionSuccess();\n }\n AssertionResult VerifyDynamicTableContents(\n const std::vector>& entries) {\n size_t index = 1;\n for (const auto& entry : entries) {\n HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second));\n ++index;\n }\n HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index));\n return AssertionSuccess();\n }\n Http2Random random_;\n HpackDecoder decoder_;\n testing::StrictMock mock_listener_;\n HpackHeaderEntries header_entries_;\n std::vector error_messages_;\n bool fragment_the_hpack_block_;\n bool saw_start_ = false;\n bool saw_end_ = false;\n};\nINSTANTIATE_TEST_SUITE_P(AllWays, HpackDecoderTest, ::testing::Bool());\nTEST_P(HpackDecoderTest, C3_RequestExamples) {\n std::string hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 86 | == Indexed - Add ==\n | idx = 6\n | -> :scheme: http\n 84 | == Indexed - Add ==\n | idx = 4\n | -> :path: /\n 41 | == Literal indexed ==\n | Indexed name (idx = 1)\n | :authority\n 0f | Literal value (len = 15)\n 7777 772e 6578 616d 706c 652e 636f 6d | www.example.com\n | -> :authority:\n | www.example.com\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"http\"},\n HpackHeaderEntry{\":path\", \"/\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents({{\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(57u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 86 | == Indexed - Add ==\n | idx = 6\n | -> :scheme: http\n 84 | == Indexed - Add ==\n | idx = 4\n | -> :path: /\n be | == Indexed - Add ==\n | idx = 62\n | -> :authority:\n | www.example.com\n 58 | == Literal indexed ==\n | Indexed name (idx = 24)\n | cache-control\n 08 | Literal value (len = 8)\n 6e6f 2d63 6163 6865 | no-cache\n | -> cache-control: no-cache\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"http\"},\n HpackHeaderEntry{\":path\", \"/\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n HpackHeaderEntry{\"cache-control\", \"no-cache\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents(\n {{\"cache-control\", \"no-cache\"}, {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(110u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 87 | == Indexed - Add ==\n | idx = 7\n | -> :scheme: https\n 85 | == Indexed - Add ==\n | idx = 5\n | -> :path: /index.html\n bf | == Indexed - Add ==\n | idx = 63\n | -> :authority:\n | www.example.com\n 40 | == Literal indexed ==\n 0a | Literal name (len = 10)\n 6375 7374 6f6d 2d6b 6579 | custom-key\n 0c | Literal value (len = 12)\n 6375 7374 6f6d 2d76 616c 7565 | custom-value\n | -> custom-key:\n | custom-value\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"https\"},\n HpackHeaderEntry{\":path\", \"/index.html\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n HpackHeaderEntry{\"custom-key\", \"custom-value\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents({{\"custom-key\", \"custom-value\"},\n {\"cache-control\", \"no-cache\"},\n {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(164u, current_header_table_size());\n}\nTEST_P(HpackDecoderTest, C4_RequestExamplesWithHuffmanEncoding) {\n std::string hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 86 | == Indexed - Add ==\n | idx = 6\n | -> :scheme: http\n 84 | == Indexed - Add ==\n | idx = 4\n | -> :path: /\n 41 | == Literal indexed ==\n | Indexed name (idx = 1)\n | :authority\n 8c | Literal value (len = 12)\n | Huffman encoded:\n f1e3 c2e5 f23a 6ba0 ab90 f4ff | .....:k.....\n | Decoded:\n | www.example.com\n | -> :authority:\n | www.example.com\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"http\"},\n HpackHeaderEntry{\":path\", \"/\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents({{\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(57u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 86 | == Indexed - Add ==\n | idx = 6\n | -> :scheme: http\n 84 | == Indexed - Add ==\n | idx = 4\n | -> :path: /\n be | == Indexed - Add ==\n | idx = 62\n | -> :authority:\n | www.example.com\n 58 | == Literal indexed ==\n | Indexed name (idx = 24)\n | cache-control\n 86 | Literal value (len = 6)\n | Huffman encoded:\n a8eb 1064 9cbf | ...d..\n | Decoded:\n | no-cache\n | -> cache-control: no-cache\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"http\"},\n HpackHeaderEntry{\":path\", \"/\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n HpackHeaderEntry{\"cache-control\", \"no-cache\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents(\n {{\"cache-control\", \"no-cache\"}, {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(110u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 82 | == Indexed - Add ==\n | idx = 2\n | -> :method: GET\n 87 | == Indexed - Add ==\n | idx = 7\n | -> :scheme: https\n 85 | == Indexed - Add ==\n | idx = 5\n | -> :path: /index.html\n bf | == Indexed - Add ==\n | idx = 63\n | -> :authority:\n | www.example.com\n 40 | == Literal indexed ==\n 88 | Literal name (len = 8)\n | Huffman encoded:\n 25a8 49e9 5ba9 7d7f | %.I.[.}.\n | Decoded:\n | custom-key\n 89 | Literal value (len = 9)\n | Huffman encoded:\n 25a8 49e9 5bb8 e8b4 bf | %.I.[....\n | Decoded:\n | custom-value\n | -> custom-key:\n | custom-value\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":method\", \"GET\"},\n HpackHeaderEntry{\":scheme\", \"https\"},\n HpackHeaderEntry{\":path\", \"/index.html\"},\n HpackHeaderEntry{\":authority\", \"www.example.com\"},\n HpackHeaderEntry{\"custom-key\", \"custom-value\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents({{\"custom-key\", \"custom-value\"},\n {\"cache-control\", \"no-cache\"},\n {\":authority\", \"www.example.com\"}}));\n ASSERT_EQ(164u, current_header_table_size());\n}\nTEST_P(HpackDecoderTest, C5_ResponseExamples) {\n set_header_table_size_limit(256);\n std::string hpack_block = HpackExampleToStringOrDie(R\"(\n 48 | == Literal indexed ==\n | Indexed name (idx = 8)\n | :status\n 03 | Literal value (len = 3)\n 3330 32 | 302\n | -> :status: 302\n 58 | == Literal indexed ==\n | Indexed name (idx = 24)\n | cache-control\n 07 | Literal value (len = 7)\n 7072 6976 6174 65 | private\n | -> cache-control: private\n 61 | == Literal indexed ==\n | Indexed name (idx = 33)\n | date\n 1d | Literal value (len = 29)\n 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013\n 2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT\n | -> date: Mon, 21 Oct 2013\n | 20:13:21 GMT\n 6e | == Literal indexed ==\n | Indexed name (idx = 46)\n | location\n 17 | Literal value (len = 23)\n 6874 7470 733a 2f2f 7777 772e 6578 616d | https:\n 706c 652e 636f 6d | ple.com\n | -> location:\n | https:\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":status\", \"302\"},\n HpackHeaderEntry{\"cache-control\", \"private\"},\n HpackHeaderEntry{\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n HpackHeaderEntry{\"location\", \"https:\n }));\n ASSERT_TRUE(\n VerifyDynamicTableContents({{\"location\", \"https:\n {\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n {\"cache-control\", \"private\"},\n {\":status\", \"302\"}}));\n ASSERT_EQ(222u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 48 | == Literal indexed ==\n | Indexed name (idx = 8)\n | :status\n 03 | Literal value (len = 3)\n 3330 37 | 307\n | - evict: :status: 302\n | -> :status: 307\n c1 | == Indexed - Add ==\n | idx = 65\n | -> cache-control: private\n c0 | == Indexed - Add ==\n | idx = 64\n | -> date: Mon, 21 Oct 2013\n | 20:13:21 GMT\n bf | == Indexed - Add ==\n | idx = 63\n | -> location:\n | https:\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":status\", \"307\"},\n HpackHeaderEntry{\"cache-control\", \"private\"},\n HpackHeaderEntry{\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n HpackHeaderEntry{\"location\", \"https:\n }));\n ASSERT_TRUE(\n VerifyDynamicTableContents({{\":status\", \"307\"},\n {\"location\", \"https:\n {\"date\", \"Mon, 21 Oct 2013 20:13:21 GMT\"},\n {\"cache-control\", \"private\"}}));\n ASSERT_EQ(222u, current_header_table_size());\n hpack_block = HpackExampleToStringOrDie(R\"(\n 88 | == Indexed - Add ==\n | idx = 8\n | -> :status: 200\n c1 | == Indexed - Add ==\n | idx = 65\n | -> cache-control: private\n 61 | == Literal indexed ==\n | Indexed name (idx = 33)\n | date\n 1d | Literal value (len = 29)\n 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013\n 2032 303a 3133 3a32 3220 474d 54 | 20:13:22 GMT\n | - evict: cache-control:\n | private\n | -> date: Mon, 21 Oct 2013\n | 20:13:22 GMT\n c0 | == Indexed - Add ==\n | idx = 64\n | -> location:\n | https:\n 5a | == Literal indexed ==\n | Indexed name (idx = 26)\n | content-encoding\n 04 | Literal value (len = 4)\n 677a 6970 | gzip\n | - evict: date: Mon, 21 Oct\n | 2013 20:13:21 GMT\n | -> content-encoding: gzip\n 77 | == Literal indexed ==\n | Indexed name (idx = 55)\n | set-cookie\n 38 | Literal value (len = 56)\n 666f 6f3d 4153 444a 4b48 514b 425a 584f | foo=ASDJKHQKBZXO\n 5157 454f 5049 5541 5851 5745 4f49 553b | QWEOPIUAXQWEOIU;\n 206d 6178 2d61 6765 3d33 3630 303b 2076 | max-age=3600; v\n 6572 7369 6f6e 3d31 | ersion=1\n | - evict: location:\n | https:\n | - evict: :status: 307\n | -> set-cookie: foo=ASDJKHQ\n | KBZXOQWEOPIUAXQWEOIU; ma\n | x-age=3600; version=1\n )\");\n EXPECT_TRUE(DecodeBlock(hpack_block));\n ASSERT_THAT(\n header_entries_,\n ElementsAreArray({\n HpackHeaderEntry{\":status\", \"200\"},\n HpackHeaderEntry{\"cache-control\", \"private\"},\n HpackHeaderEntry{\"date\", \"Mon, 21 Oct 2013 20:13:22 GMT\"},\n HpackHeaderEntry{\"location\", \"https:\n HpackHeaderEntry{\"content-encoding\", \"gzip\"},\n HpackHeaderEntry{\n \"set-cookie\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\"},\n }));\n ASSERT_TRUE(VerifyDynamicTableContents(\n {{\"set-cookie\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\"},\n {\"content-encoding\", \"gzip\"},\n {\"date\", \"Mon, 21 Oct 2013 20:13:22 GMT\"}}));\n ASSERT_EQ(215u, current_header_table_size());\n}\nTEST_P(HpackDecoderTest, C6_ResponseExamplesWithHuffmanEncoding) {\n set_header_table_size_limit(256);"}}},{"rowIdx":440,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_TABLES_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_TABLES_H_\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/quiche_circular_deque.h\"\nnamespace http2 {\nnamespace test {\nclass HpackDecoderTablesPeer;\n} \nstruct QUICHE_EXPORT HpackStringPair {\n HpackStringPair(std::string name, std::string value);\n ~HpackStringPair();\n size_t size() const { return 32 + name.size() + value.size(); }\n std::string DebugString() const;\n const std::string name;\n const std::string value;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& os,\n const HpackStringPair& p);\nclass QUICHE_EXPORT HpackDecoderStaticTable {\n public:\n explicit HpackDecoderStaticTable(const std::vector* table);\n HpackDecoderStaticTable();\n const HpackStringPair* Lookup(size_t index) const;\n private:\n friend class test::HpackDecoderTablesPeer;\n const std::vector* const table_;\n};\nclass QUICHE_EXPORT HpackDecoderDynamicTable {\n public:\n HpackDecoderDynamicTable();\n ~HpackDecoderDynamicTable();\n HpackDecoderDynamicTable(const HpackDecoderDynamicTable&) = delete;\n HpackDecoderDynamicTable& operator=(const HpackDecoderDynamicTable&) = delete;\n void DynamicTableSizeUpdate(size_t size_limit);\n void Insert(std::string name, std::string value);\n const HpackStringPair* Lookup(size_t index) const;\n size_t size_limit() const { return size_limit_; }\n size_t current_size() const { return current_size_; }\n private:\n friend class test::HpackDecoderTablesPeer;\n void EnsureSizeNoMoreThan(size_t limit);\n void RemoveLastEntry();\n quiche::QuicheCircularDeque table_;\n size_t size_limit_ = Http2SettingsInfo::DefaultHeaderTableSize();\n size_t current_size_ = 0;\n size_t insert_count_;\n};\nclass QUICHE_EXPORT HpackDecoderTables {\n public:\n HpackDecoderTables();\n ~HpackDecoderTables();\n HpackDecoderTables(const HpackDecoderTables&) = delete;\n HpackDecoderTables& operator=(const HpackDecoderTables&) = delete;\n void DynamicTableSizeUpdate(size_t size_limit) {\n dynamic_table_.DynamicTableSizeUpdate(size_limit);\n }\n void Insert(std::string name, std::string value) {\n dynamic_table_.Insert(std::move(name), std::move(value));\n }\n const HpackStringPair* Lookup(size_t index) const;\n size_t header_table_size_limit() const { return dynamic_table_.size_limit(); }\n size_t current_header_table_size() const {\n return dynamic_table_.current_size();\n }\n private:\n friend class test::HpackDecoderTablesPeer;\n HpackDecoderStaticTable static_table_;\n HpackDecoderDynamicTable dynamic_table_;\n};\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_decoder_tables.h\"\n#include \n#include \n#include \n#include \n#include \"absl/strings/str_cat.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace {\nstd::vector* MakeStaticTable() {\n auto* ptr = new std::vector();\n ptr->reserve(kFirstDynamicTableIndex);\n ptr->emplace_back(\"\", \"\");\n#define STATIC_TABLE_ENTRY(name, value, index) \\\n QUICHE_DCHECK_EQ(ptr->size(), static_cast(index)); \\\n ptr->emplace_back(name, value)\n#include \"quiche/http2/hpack/hpack_static_table_entries.inc\"\n#undef STATIC_TABLE_ENTRY\n return ptr;\n}\nconst std::vector* GetStaticTable() {\n static const std::vector* const g_static_table =\n MakeStaticTable();\n return g_static_table;\n}\n} \nHpackStringPair::HpackStringPair(std::string name, std::string value)\n : name(std::move(name)), value(std::move(value)) {\n QUICHE_DVLOG(3) << DebugString() << \" ctor\";\n}\nHpackStringPair::~HpackStringPair() {\n QUICHE_DVLOG(3) << DebugString() << \" dtor\";\n}\nstd::string HpackStringPair::DebugString() const {\n return absl::StrCat(\"HpackStringPair(name=\", name, \", value=\", value, \")\");\n}\nstd::ostream& operator<<(std::ostream& os, const HpackStringPair& p) {\n os << p.DebugString();\n return os;\n}\nHpackDecoderStaticTable::HpackDecoderStaticTable(\n const std::vector* table)\n : table_(table) {}\nHpackDecoderStaticTable::HpackDecoderStaticTable() : table_(GetStaticTable()) {}\nconst HpackStringPair* HpackDecoderStaticTable::Lookup(size_t index) const {\n if (0 < index && index < kFirstDynamicTableIndex) {\n return &((*table_)[index]);\n }\n return nullptr;\n}\nHpackDecoderDynamicTable::HpackDecoderDynamicTable()\n : insert_count_(kFirstDynamicTableIndex - 1) {}\nHpackDecoderDynamicTable::~HpackDecoderDynamicTable() = default;\nvoid HpackDecoderDynamicTable::DynamicTableSizeUpdate(size_t size_limit) {\n QUICHE_DVLOG(3) << \"HpackDecoderDynamicTable::DynamicTableSizeUpdate \"\n << size_limit;\n EnsureSizeNoMoreThan(size_limit);\n QUICHE_DCHECK_LE(current_size_, size_limit);\n size_limit_ = size_limit;\n}\nvoid HpackDecoderDynamicTable::Insert(std::string name, std::string value) {\n HpackStringPair entry(std::move(name), std::move(value));\n size_t entry_size = entry.size();\n QUICHE_DVLOG(2) << \"InsertEntry of size=\" << entry_size\n << \"\\n name: \" << entry.name\n << \"\\n value: \" << entry.value;\n if (entry_size > size_limit_) {\n QUICHE_DVLOG(2) << \"InsertEntry: entry larger than table, removing \"\n << table_.size() << \" entries, of total size \"\n << current_size_ << \" bytes.\";\n table_.clear();\n current_size_ = 0;\n return;\n }\n ++insert_count_;\n size_t insert_limit = size_limit_ - entry_size;\n EnsureSizeNoMoreThan(insert_limit);\n table_.push_front(std::move(entry));\n current_size_ += entry_size;\n QUICHE_DVLOG(2) << \"InsertEntry: current_size_=\" << current_size_;\n QUICHE_DCHECK_GE(current_size_, entry_size);\n QUICHE_DCHECK_LE(current_size_, size_limit_);\n}\nconst HpackStringPair* HpackDecoderDynamicTable::Lookup(size_t index) const {\n if (index < table_.size()) {\n return &table_[index];\n }\n return nullptr;\n}\nvoid HpackDecoderDynamicTable::EnsureSizeNoMoreThan(size_t limit) {\n QUICHE_DVLOG(2) << \"EnsureSizeNoMoreThan limit=\" << limit\n << \", current_size_=\" << current_size_;\n while (current_size_ > limit) {\n RemoveLastEntry();\n }\n QUICHE_DCHECK_LE(current_size_, limit);\n}\nvoid HpackDecoderDynamicTable::RemoveLastEntry() {\n QUICHE_DCHECK(!table_.empty());\n if (!table_.empty()) {\n QUICHE_DVLOG(2) << \"RemoveLastEntry current_size_=\" << current_size_\n << \", last entry size=\" << table_.back().size();\n QUICHE_DCHECK_GE(current_size_, table_.back().size());\n current_size_ -= table_.back().size();\n table_.pop_back();\n QUICHE_DCHECK_EQ(table_.empty(), current_size_ == 0);\n }\n}\nHpackDecoderTables::HpackDecoderTables() = default;\nHpackDecoderTables::~HpackDecoderTables() = default;\nconst HpackStringPair* HpackDecoderTables::Lookup(size_t index) const {\n if (index < kFirstDynamicTableIndex) {\n return static_table_.Lookup(index);\n } else {\n return dynamic_table_.Lookup(index - kFirstDynamicTableIndex);\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_decoder_tables.h\"\n#include \n#include \n#include \n#include \n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_util.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nclass HpackDecoderTablesPeer {\n public:\n static size_t num_dynamic_entries(const HpackDecoderTables& tables) {\n return tables.dynamic_table_.table_.size();\n }\n};\nnamespace {\nstruct StaticEntry {\n const char* name;\n const char* value;\n size_t index;\n};\nstd::vector MakeSpecStaticEntries() {\n std::vector static_entries;\n#define STATIC_TABLE_ENTRY(name, value, index) \\\n QUICHE_DCHECK_EQ(static_entries.size() + 1, static_cast(index)); \\\n static_entries.push_back({name, value, index});\n#include \"quiche/http2/hpack/hpack_static_table_entries.inc\"\n#undef STATIC_TABLE_ENTRY\n return static_entries;\n}\ntemplate \nvoid ShuffleCollection(C* collection, Http2Random* r) {\n std::shuffle(collection->begin(), collection->end(), *r);\n}\nclass HpackDecoderStaticTableTest : public quiche::test::QuicheTest {\n protected:\n HpackDecoderStaticTableTest() = default;\n std::vector shuffled_static_entries() {\n std::vector entries = MakeSpecStaticEntries();\n ShuffleCollection(&entries, &random_);\n return entries;\n }\n AssertionResult VerifyStaticTableContents() {\n for (const auto& expected : shuffled_static_entries()) {\n const HpackStringPair* found = Lookup(expected.index);\n HTTP2_VERIFY_NE(found, nullptr);\n HTTP2_VERIFY_EQ(expected.name, found->name) << expected.index;\n HTTP2_VERIFY_EQ(expected.value, found->value) << expected.index;\n }\n HTTP2_VERIFY_EQ(nullptr, Lookup(0));\n return AssertionSuccess();\n }\n virtual const HpackStringPair* Lookup(size_t index) {\n return static_table_.Lookup(index);\n }\n Http2Random* RandomPtr() { return &random_; }\n Http2Random random_;\n private:\n HpackDecoderStaticTable static_table_;\n};\nTEST_F(HpackDecoderStaticTableTest, StaticTableContents) {\n EXPECT_TRUE(VerifyStaticTableContents());\n}\nsize_t Size(const std::string& name, const std::string& value) {\n return name.size() + value.size() + 32;\n}\ntypedef std::tuple FakeHpackEntry;\nconst std::string& Name(const FakeHpackEntry& entry) {\n return std::get<0>(entry);\n}\nconst std::string& Value(const FakeHpackEntry& entry) {\n return std::get<1>(entry);\n}\nsize_t Size(const FakeHpackEntry& entry) { return std::get<2>(entry); }\nclass HpackDecoderTablesTest : public HpackDecoderStaticTableTest {\n protected:\n const HpackStringPair* Lookup(size_t index) override {\n return tables_.Lookup(index);\n }\n size_t dynamic_size_limit() const {\n return tables_.header_table_size_limit();\n }\n size_t current_dynamic_size() const {\n return tables_.current_header_table_size();\n }\n size_t num_dynamic_entries() const {\n return HpackDecoderTablesPeer::num_dynamic_entries(tables_);\n }\n void FakeInsert(const std::string& name, const std::string& value) {\n FakeHpackEntry entry(name, value, Size(name, value));\n fake_dynamic_table_.insert(fake_dynamic_table_.begin(), entry);\n }\n size_t FakeSize() {\n size_t sz = 0;\n for (const auto& entry : fake_dynamic_table_) {\n sz += Size(entry);\n }\n return sz;\n }\n size_t FakeTrim(size_t limit) {\n size_t original_size = FakeSize();\n size_t total_size = 0;\n for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) {\n total_size += Size(fake_dynamic_table_[ndx]);\n if (total_size > limit) {\n fake_dynamic_table_.erase(fake_dynamic_table_.begin() + ndx,\n fake_dynamic_table_.end());\n return original_size - FakeSize();\n }\n }\n return 0;\n }\n AssertionResult VerifyDynamicTableContents() {\n HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());\n HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size());\n for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) {\n const HpackStringPair* found = Lookup(ndx + kFirstDynamicTableIndex);\n HTTP2_VERIFY_NE(found, nullptr);\n const auto& expected = fake_dynamic_table_[ndx];\n HTTP2_VERIFY_EQ(Name(expected), found->name);\n HTTP2_VERIFY_EQ(Value(expected), found->value);\n }\n HTTP2_VERIFY_EQ(\n nullptr, Lookup(fake_dynamic_table_.size() + kFirstDynamicTableIndex));\n return AssertionSuccess();\n }\n AssertionResult DynamicTableSizeUpdate(size_t size_limit) {\n HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());\n if (size_limit < current_dynamic_size()) {\n tables_.DynamicTableSizeUpdate(size_limit);\n FakeTrim(size_limit);\n return VerifyDynamicTableContents();\n }\n tables_.DynamicTableSizeUpdate(size_limit);\n return VerifyDynamicTableContents();\n }\n AssertionResult Insert(const std::string& name, const std::string& value) {\n size_t old_count = num_dynamic_entries();\n tables_.Insert(name, value);\n FakeInsert(name, value);\n HTTP2_VERIFY_EQ(old_count + 1, fake_dynamic_table_.size());\n FakeTrim(dynamic_size_limit());\n HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());\n HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size());\n return VerifyDynamicTableContents();\n }\n private:\n HpackDecoderTables tables_;\n std::vector fake_dynamic_table_;\n};\nTEST_F(HpackDecoderTablesTest, StaticTableContents) {\n EXPECT_TRUE(VerifyStaticTableContents());\n}\nTEST_F(HpackDecoderTablesTest, RandomDynamicTable) {\n EXPECT_EQ(0u, current_dynamic_size());\n EXPECT_TRUE(VerifyStaticTableContents());\n EXPECT_TRUE(VerifyDynamicTableContents());\n std::vector table_sizes;\n table_sizes.push_back(dynamic_size_limit());\n table_sizes.push_back(0);\n table_sizes.push_back(dynamic_size_limit() / 2);\n table_sizes.push_back(dynamic_size_limit());\n table_sizes.push_back(dynamic_size_limit() / 2);\n table_sizes.push_back(0);\n table_sizes.push_back(dynamic_size_limit());\n for (size_t limit : table_sizes) {\n ASSERT_TRUE(DynamicTableSizeUpdate(limit));\n for (int insert_count = 0; insert_count < 100; ++insert_count) {\n std::string name =\n GenerateHttp2HeaderName(random_.UniformInRange(2, 40), RandomPtr());\n std::string value =\n GenerateWebSafeString(random_.UniformInRange(2, 600), RandomPtr());\n ASSERT_TRUE(Insert(name, value));\n }\n EXPECT_TRUE(VerifyStaticTableContents());\n }\n}\n} \n} \n} "}}},{"rowIdx":441,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_DECODER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_DECODER_H_\n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoding_error.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_type_decoder.h\"\n#include \"quiche/http2/hpack/decoder/hpack_string_decoder.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackEntryDecoder {\n public:\n enum class EntryDecoderState {\n kResumeDecodingType,\n kDecodedType,\n kStartDecodingName,\n kResumeDecodingName,\n kStartDecodingValue,\n kResumeDecodingValue,\n };\n DecodeStatus Start(DecodeBuffer* db, HpackEntryDecoderListener* listener);\n DecodeStatus Resume(DecodeBuffer* db, HpackEntryDecoderListener* listener);\n HpackDecodingError error() const { return error_; }\n std::string DebugString() const;\n void OutputDebugString(std::ostream& out) const;\n private:\n bool DispatchOnType(HpackEntryDecoderListener* listener);\n HpackEntryTypeDecoder entry_type_decoder_;\n HpackStringDecoder string_decoder_;\n EntryDecoderState state_ = EntryDecoderState();\n HpackDecodingError error_ = HpackDecodingError::kOk;\n};\nQUICHE_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackEntryDecoder& v);\nQUICHE_EXPORT std::ostream& operator<<(\n std::ostream& out, HpackEntryDecoder::EntryDecoderState state);\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace {\nclass NameDecoderListener {\n public:\n explicit NameDecoderListener(HpackEntryDecoderListener* listener)\n : listener_(listener) {}\n bool OnStringStart(bool huffman_encoded, size_t len) {\n listener_->OnNameStart(huffman_encoded, len);\n return true;\n }\n void OnStringData(const char* data, size_t len) {\n listener_->OnNameData(data, len);\n }\n void OnStringEnd() { listener_->OnNameEnd(); }\n private:\n HpackEntryDecoderListener* listener_;\n};\nclass ValueDecoderListener {\n public:\n explicit ValueDecoderListener(HpackEntryDecoderListener* listener)\n : listener_(listener) {}\n bool OnStringStart(bool huffman_encoded, size_t len) {\n listener_->OnValueStart(huffman_encoded, len);\n return true;\n }\n void OnStringData(const char* data, size_t len) {\n listener_->OnValueData(data, len);\n }\n void OnStringEnd() { listener_->OnValueEnd(); }\n private:\n HpackEntryDecoderListener* listener_;\n};\n} \nDecodeStatus HpackEntryDecoder::Start(DecodeBuffer* db,\n HpackEntryDecoderListener* listener) {\n QUICHE_DCHECK(db != nullptr);\n QUICHE_DCHECK(listener != nullptr);\n QUICHE_DCHECK(db->HasData());\n DecodeStatus status = entry_type_decoder_.Start(db);\n switch (status) {\n case DecodeStatus::kDecodeDone:\n if (entry_type_decoder_.entry_type() == HpackEntryType::kIndexedHeader) {\n listener->OnIndexedHeader(entry_type_decoder_.varint());\n return DecodeStatus::kDecodeDone;\n }\n state_ = EntryDecoderState::kDecodedType;\n return Resume(db, listener);\n case DecodeStatus::kDecodeInProgress:\n QUICHE_DCHECK_EQ(0u, db->Remaining());\n state_ = EntryDecoderState::kResumeDecodingType;\n return status;\n case DecodeStatus::kDecodeError:\n QUICHE_CODE_COUNT_N(decompress_failure_3, 11, 23);\n error_ = HpackDecodingError::kIndexVarintError;\n return status;\n }\n QUICHE_BUG(http2_bug_63_1) << \"Unreachable\";\n return DecodeStatus::kDecodeError;\n}\nDecodeStatus HpackEntryDecoder::Resume(DecodeBuffer* db,\n HpackEntryDecoderListener* listener) {\n QUICHE_DCHECK(db != nullptr);\n QUICHE_DCHECK(listener != nullptr);\n DecodeStatus status;\n do {\n switch (state_) {\n case EntryDecoderState::kResumeDecodingType:\n QUICHE_DVLOG(1) << \"kResumeDecodingType: db->Remaining=\"\n << db->Remaining();\n status = entry_type_decoder_.Resume(db);\n if (status == DecodeStatus::kDecodeError) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 12, 23);\n error_ = HpackDecodingError::kIndexVarintError;\n }\n if (status != DecodeStatus::kDecodeDone) {\n return status;\n }\n state_ = EntryDecoderState::kDecodedType;\n ABSL_FALLTHROUGH_INTENDED;\n case EntryDecoderState::kDecodedType:\n QUICHE_DVLOG(1) << \"kDecodedType: db->Remaining=\" << db->Remaining();\n if (DispatchOnType(listener)) {\n return DecodeStatus::kDecodeDone;\n }\n continue;\n case EntryDecoderState::kStartDecodingName:\n QUICHE_DVLOG(1) << \"kStartDecodingName: db->Remaining=\"\n << db->Remaining();\n {\n NameDecoderListener ncb(listener);\n status = string_decoder_.Start(db, &ncb);\n }\n if (status != DecodeStatus::kDecodeDone) {\n state_ = EntryDecoderState::kResumeDecodingName;\n if (status == DecodeStatus::kDecodeError) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 13, 23);\n error_ = HpackDecodingError::kNameLengthVarintError;\n }\n return status;\n }\n state_ = EntryDecoderState::kStartDecodingValue;\n ABSL_FALLTHROUGH_INTENDED;\n case EntryDecoderState::kStartDecodingValue:\n QUICHE_DVLOG(1) << \"kStartDecodingValue: db->Remaining=\"\n << db->Remaining();\n {\n ValueDecoderListener vcb(listener);\n status = string_decoder_.Start(db, &vcb);\n }\n if (status == DecodeStatus::kDecodeError) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 14, 23);\n error_ = HpackDecodingError::kValueLengthVarintError;\n }\n if (status == DecodeStatus::kDecodeDone) {\n return status;\n }\n state_ = EntryDecoderState::kResumeDecodingValue;\n return status;\n case EntryDecoderState::kResumeDecodingName:\n QUICHE_DVLOG(1) << \"kResumeDecodingName: db->Remaining=\"\n << db->Remaining();\n {\n NameDecoderListener ncb(listener);\n status = string_decoder_.Resume(db, &ncb);\n }\n if (status != DecodeStatus::kDecodeDone) {\n state_ = EntryDecoderState::kResumeDecodingName;\n if (status == DecodeStatus::kDecodeError) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 15, 23);\n error_ = HpackDecodingError::kNameLengthVarintError;\n }\n return status;\n }\n state_ = EntryDecoderState::kStartDecodingValue;\n break;\n case EntryDecoderState::kResumeDecodingValue:\n QUICHE_DVLOG(1) << \"kResumeDecodingValue: db->Remaining=\"\n << db->Remaining();\n {\n ValueDecoderListener vcb(listener);\n status = string_decoder_.Resume(db, &vcb);\n }\n if (status == DecodeStatus::kDecodeError) {\n QUICHE_CODE_COUNT_N(decompress_failure_3, 16, 23);\n error_ = HpackDecodingError::kValueLengthVarintError;\n }\n if (status == DecodeStatus::kDecodeDone) {\n return status;\n }\n state_ = EntryDecoderState::kResumeDecodingValue;\n return status;\n }\n } while (true);\n}\nbool HpackEntryDecoder::DispatchOnType(HpackEntryDecoderListener* listener) {\n const HpackEntryType entry_type = entry_type_decoder_.entry_type();\n const uint32_t varint = static_cast(entry_type_decoder_.varint());\n switch (entry_type) {\n case HpackEntryType::kIndexedHeader:\n listener->OnIndexedHeader(varint);\n return true;\n case HpackEntryType::kIndexedLiteralHeader:\n case HpackEntryType::kUnindexedLiteralHeader:\n case HpackEntryType::kNeverIndexedLiteralHeader:\n listener->OnStartLiteralHeader(entry_type, varint);\n if (varint == 0) {\n state_ = EntryDecoderState::kStartDecodingName;\n } else {\n state_ = EntryDecoderState::kStartDecodingValue;\n }\n return false;\n case HpackEntryType::kDynamicTableSizeUpdate:\n listener->OnDynamicTableSizeUpdate(varint);\n return true;\n }\n QUICHE_BUG(http2_bug_63_2) << \"Unreachable, entry_type=\" << entry_type;\n return true;\n}\nvoid HpackEntryDecoder::OutputDebugString(std::ostream& out) const {\n out << \"HpackEntryDecoder(state=\" << state_ << \", \" << entry_type_decoder_\n << \", \" << string_decoder_ << \")\";\n}\nstd::string HpackEntryDecoder::DebugString() const {\n std::stringstream s;\n s << *this;\n return s.str();\n}\nstd::ostream& operator<<(std::ostream& out, const HpackEntryDecoder& v) {\n v.OutputDebugString(out);\n return out;\n}\nstd::ostream& operator<<(std::ostream& out,\n HpackEntryDecoder::EntryDecoderState state) {\n typedef HpackEntryDecoder::EntryDecoderState EntryDecoderState;\n switch (state) {\n case EntryDecoderState::kResumeDecodingType:\n return out << \"kResumeDecodingType\";\n case EntryDecoderState::kDecodedType:\n return out << \"kDecodedType\";\n case EntryDecoderState::kStartDecodingName:\n return out << \"kStartDecodingName\";\n case EntryDecoderState::kResumeDecodingName:\n return out << \"kResumeDecodingName\";\n case EntryDecoderState::kStartDecodingValue:\n return out << \"kStartDecodingValue\";\n case EntryDecoderState::kResumeDecodingValue:\n return out << \"kResumeDecodingValue\";\n }\n return out << static_cast(state);\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_entry_decoder.h\"\n#include \n#include \n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_entry_collector.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nclass HpackEntryDecoderTest : public RandomDecoderTest {\n protected:\n HpackEntryDecoderTest() : listener_(&collector_) {}\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n collector_.Clear();\n return decoder_.Start(b, &listener_);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n return decoder_.Resume(b, &listener_);\n }\n AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db,\n const Validator& validator) {\n bool return_non_zero_on_first = true;\n return RandomDecoderTest::DecodeAndValidateSeveralWays(\n db, return_non_zero_on_first, validator);\n }\n AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb,\n const Validator& validator) {\n DecodeBuffer db(hbb.buffer());\n return DecodeAndValidateSeveralWays(&db, validator);\n }\n HpackEntryDecoder decoder_;\n HpackEntryCollector collector_;\n HpackEntryDecoderVLoggingListener listener_;\n};\nTEST_F(HpackEntryDecoderTest, IndexedHeader_Literals) {\n {\n const char input[] = {'\\x82'}; \n DecodeBuffer b(input);\n auto do_check = [this]() { return collector_.ValidateIndexedHeader(2); };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n collector_.Clear();\n {\n const char input[] = {'\\xfe'}; \n DecodeBuffer b(input);\n auto do_check = [this]() { return collector_.ValidateIndexedHeader(126); };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n collector_.Clear();\n {\n const char input[] = {'\\xff', '\\x00'}; \n DecodeBuffer b(input);\n auto do_check = [this]() { return collector_.ValidateIndexedHeader(127); };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n}\nTEST_F(HpackEntryDecoderTest, IndexedHeader_Various) {\n for (const uint32_t ndx : {1, 2, 61, 62, 63, 126, 127, 254, 255, 256}) {\n HpackBlockBuilder hbb;\n hbb.AppendIndexedHeader(ndx);\n auto do_check = [this, ndx]() {\n return collector_.ValidateIndexedHeader(ndx);\n };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n}\nTEST_F(HpackEntryDecoderTest, IndexedLiteralValue_Literal) {\n const char input[] =\n \"\\x7f\" \n \"\\x01\" \n \"\\x0d\" \n \"custom-header\"; \n DecodeBuffer b(input, sizeof input - 1);\n auto do_check = [this]() {\n return collector_.ValidateLiteralValueHeader(\n HpackEntryType::kIndexedLiteralHeader, 0x40, false, \"custom-header\");\n };\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackEntryDecoderTest, IndexedLiteralNameValue_Literal) {\n const char input[] =\n \"\\x40\" \n \"\\x0a\" \n \"custom-key\" \n \"\\x0d\" \n \"custom-header\"; \n DecodeBuffer b(input, sizeof input - 1);\n auto do_check = [this]() {\n return collector_.ValidateLiteralNameValueHeader(\n HpackEntryType::kIndexedLiteralHeader, false, \"custom-key\", false,\n \"custom-header\");\n };\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nTEST_F(HpackEntryDecoderTest, DynamicTableSizeUpdate_Literal) {\n const char input[] = \"\\x3f\\x00\";\n DecodeBuffer b(input, 2);\n auto do_check = [this]() {\n return collector_.ValidateDynamicTableSizeUpdate(31);\n };\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n}\nclass HpackLiteralEntryDecoderTest\n : public HpackEntryDecoderTest,\n public ::testing::WithParamInterface {\n protected:\n HpackLiteralEntryDecoderTest() : entry_type_(GetParam()) {}\n const HpackEntryType entry_type_;\n};\nINSTANTIATE_TEST_SUITE_P(\n AllLiteralTypes, HpackLiteralEntryDecoderTest,\n testing::Values(HpackEntryType::kIndexedLiteralHeader,\n HpackEntryType::kUnindexedLiteralHeader,\n HpackEntryType::kNeverIndexedLiteralHeader));\nTEST_P(HpackLiteralEntryDecoderTest, RandNameIndexAndLiteralValue) {\n for (int n = 0; n < 10; n++) {\n const uint32_t ndx = 1 + Random().Rand8();\n const bool value_is_huffman_encoded = (n % 2) == 0;\n const std::string value = Random().RandString(Random().Rand8());\n HpackBlockBuilder hbb;\n hbb.AppendNameIndexAndLiteralValue(entry_type_, ndx,\n value_is_huffman_encoded, value);\n auto do_check = [this, ndx, value_is_huffman_encoded,\n value]() -> AssertionResult {\n return collector_.ValidateLiteralValueHeader(\n entry_type_, ndx, value_is_huffman_encoded, value);\n };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n}\nTEST_P(HpackLiteralEntryDecoderTest, RandLiteralNameAndValue) {\n for (int n = 0; n < 10; n++) {\n const bool name_is_huffman_encoded = (n & 1) == 0;\n const int name_len = 1 + Random().Rand8();\n const std::string name = Random().RandString(name_len);\n const bool value_is_huffman_encoded = (n & 2) == 0;\n const int value_len = Random().Skewed(10);\n const std::string value = Random().RandString(value_len);\n HpackBlockBuilder hbb;\n hbb.AppendLiteralNameAndValue(entry_type_, name_is_huffman_encoded, name,\n value_is_huffman_encoded, value);\n auto do_check = [this, name_is_huffman_encoded, name,\n value_is_huffman_encoded, value]() -> AssertionResult {\n return collector_.ValidateLiteralNameValueHeader(\n entry_type_, name_is_huffman_encoded, name, value_is_huffman_encoded,\n value);\n };\n EXPECT_TRUE(\n DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));\n EXPECT_TRUE(do_check());\n }\n}\n} \n} \n} "}}},{"rowIdx":442,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_WHOLE_ENTRY_BUFFER_H_\n#define QUICHE_HTTP2_HPACK_DECODER_HPACK_WHOLE_ENTRY_BUFFER_H_\n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h\"\n#include \"quiche/http2/hpack/decoder/hpack_decoding_error.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h\"\n#include \"quiche/http2/hpack/decoder/hpack_whole_entry_listener.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackWholeEntryBuffer : public HpackEntryDecoderListener {\n public:\n HpackWholeEntryBuffer(HpackWholeEntryListener* listener,\n size_t max_string_size);\n ~HpackWholeEntryBuffer() override;\n HpackWholeEntryBuffer(const HpackWholeEntryBuffer&) = delete;\n HpackWholeEntryBuffer& operator=(const HpackWholeEntryBuffer&) = delete;\n void set_listener(HpackWholeEntryListener* listener);\n void set_max_string_size_bytes(size_t max_string_size_bytes);\n void BufferStringsIfUnbuffered();\n bool error_detected() const { return error_detected_; }\n void OnIndexedHeader(size_t index) override;\n void OnStartLiteralHeader(HpackEntryType entry_type,\n size_t maybe_name_index) override;\n void OnNameStart(bool huffman_encoded, size_t len) override;\n void OnNameData(const char* data, size_t len) override;\n void OnNameEnd() override;\n void OnValueStart(bool huffman_encoded, size_t len) override;\n void OnValueData(const char* data, size_t len) override;\n void OnValueEnd() override;\n void OnDynamicTableSizeUpdate(size_t size) override;\n private:\n void ReportError(HpackDecodingError error);\n HpackWholeEntryListener* listener_;\n HpackDecoderStringBuffer name_, value_;\n size_t max_string_size_bytes_;\n size_t maybe_name_index_;\n HpackEntryType entry_type_;\n bool error_detected_ = false;\n};\n} \n#endif \n#include \"quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/quiche_text_utils.h\"\nnamespace http2 {\nHpackWholeEntryBuffer::HpackWholeEntryBuffer(HpackWholeEntryListener* listener,\n size_t max_string_size_bytes)\n : max_string_size_bytes_(max_string_size_bytes) {\n set_listener(listener);\n}\nHpackWholeEntryBuffer::~HpackWholeEntryBuffer() = default;\nvoid HpackWholeEntryBuffer::set_listener(HpackWholeEntryListener* listener) {\n QUICHE_CHECK(listener);\n listener_ = listener;\n}\nvoid HpackWholeEntryBuffer::set_max_string_size_bytes(\n size_t max_string_size_bytes) {\n max_string_size_bytes_ = max_string_size_bytes;\n}\nvoid HpackWholeEntryBuffer::BufferStringsIfUnbuffered() {\n name_.BufferStringIfUnbuffered();\n value_.BufferStringIfUnbuffered();\n}\nvoid HpackWholeEntryBuffer::OnIndexedHeader(size_t index) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnIndexedHeader: index=\" << index;\n listener_->OnIndexedHeader(index);\n}\nvoid HpackWholeEntryBuffer::OnStartLiteralHeader(HpackEntryType entry_type,\n size_t maybe_name_index) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnStartLiteralHeader: entry_type=\"\n << entry_type << \", maybe_name_index=\" << maybe_name_index;\n entry_type_ = entry_type;\n maybe_name_index_ = maybe_name_index;\n}\nvoid HpackWholeEntryBuffer::OnNameStart(bool huffman_encoded, size_t len) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnNameStart: huffman_encoded=\"\n << (huffman_encoded ? \"true\" : \"false\") << \", len=\" << len;\n QUICHE_DCHECK_EQ(maybe_name_index_, 0u);\n if (!error_detected_) {\n if (len > max_string_size_bytes_) {\n QUICHE_DVLOG(1) << \"Name length (\" << len\n << \") is longer than permitted (\"\n << max_string_size_bytes_ << \")\";\n ReportError(HpackDecodingError::kNameTooLong);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 18, 23);\n return;\n }\n name_.OnStart(huffman_encoded, len);\n }\n}\nvoid HpackWholeEntryBuffer::OnNameData(const char* data, size_t len) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnNameData: len=\" << len\n << \" data:\\n\"\n << quiche::QuicheTextUtils::HexDump(\n absl::string_view(data, len));\n QUICHE_DCHECK_EQ(maybe_name_index_, 0u);\n if (!error_detected_ && !name_.OnData(data, len)) {\n ReportError(HpackDecodingError::kNameHuffmanError);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 19, 23);\n }\n}\nvoid HpackWholeEntryBuffer::OnNameEnd() {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnNameEnd\";\n QUICHE_DCHECK_EQ(maybe_name_index_, 0u);\n if (!error_detected_ && !name_.OnEnd()) {\n ReportError(HpackDecodingError::kNameHuffmanError);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 20, 23);\n }\n}\nvoid HpackWholeEntryBuffer::OnValueStart(bool huffman_encoded, size_t len) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnValueStart: huffman_encoded=\"\n << (huffman_encoded ? \"true\" : \"false\") << \", len=\" << len;\n if (!error_detected_) {\n if (len > max_string_size_bytes_) {\n QUICHE_DVLOG(1) << \"Value length (\" << len << \") of [\"\n << name_.GetStringIfComplete()\n << \"] is longer than permitted (\"\n << max_string_size_bytes_ << \")\";\n ReportError(HpackDecodingError::kValueTooLong);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 21, 23);\n return;\n }\n value_.OnStart(huffman_encoded, len);\n }\n}\nvoid HpackWholeEntryBuffer::OnValueData(const char* data, size_t len) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnValueData: len=\" << len\n << \" data:\\n\"\n << quiche::QuicheTextUtils::HexDump(\n absl::string_view(data, len));\n if (!error_detected_ && !value_.OnData(data, len)) {\n ReportError(HpackDecodingError::kValueHuffmanError);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 22, 23);\n }\n}\nvoid HpackWholeEntryBuffer::OnValueEnd() {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnValueEnd\";\n if (error_detected_) {\n return;\n }\n if (!value_.OnEnd()) {\n ReportError(HpackDecodingError::kValueHuffmanError);\n QUICHE_CODE_COUNT_N(decompress_failure_3, 23, 23);\n return;\n }\n if (maybe_name_index_ == 0) {\n listener_->OnLiteralNameAndValue(entry_type_, &name_, &value_);\n name_.Reset();\n } else {\n listener_->OnNameIndexAndLiteralValue(entry_type_, maybe_name_index_,\n &value_);\n }\n value_.Reset();\n}\nvoid HpackWholeEntryBuffer::OnDynamicTableSizeUpdate(size_t size) {\n QUICHE_DVLOG(2) << \"HpackWholeEntryBuffer::OnDynamicTableSizeUpdate: size=\"\n << size;\n listener_->OnDynamicTableSizeUpdate(size);\n}\nvoid HpackWholeEntryBuffer::ReportError(HpackDecodingError error) {\n if (!error_detected_) {\n QUICHE_DVLOG(1) << \"HpackWholeEntryBuffer::ReportError: \"\n << HpackDecodingErrorToString(error);\n error_detected_ = true;\n listener_->OnHpackDecodeError(error);\n listener_ = HpackWholeEntryNoOpListener::NoOpListener();\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::_;\nusing ::testing::AllOf;\nusing ::testing::InSequence;\nusing ::testing::Property;\nusing ::testing::StrictMock;\nnamespace http2 {\nnamespace test {\nnamespace {\nconstexpr size_t kMaxStringSize = 20;\nclass MockHpackWholeEntryListener : public HpackWholeEntryListener {\n public:\n ~MockHpackWholeEntryListener() override = default;\n MOCK_METHOD(void, OnIndexedHeader, (size_t index), (override));\n MOCK_METHOD(void, OnNameIndexAndLiteralValue,\n (HpackEntryType entry_type, size_t name_index,\n HpackDecoderStringBuffer* value_buffer),\n (override));\n MOCK_METHOD(void, OnLiteralNameAndValue,\n (HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer,\n HpackDecoderStringBuffer* value_buffer),\n (override));\n MOCK_METHOD(void, OnDynamicTableSizeUpdate, (size_t size), (override));\n MOCK_METHOD(void, OnHpackDecodeError, (HpackDecodingError error), (override));\n};\nclass HpackWholeEntryBufferTest : public quiche::test::QuicheTest {\n protected:\n HpackWholeEntryBufferTest() : entry_buffer_(&listener_, kMaxStringSize) {}\n ~HpackWholeEntryBufferTest() override = default;\n StrictMock listener_;\n HpackWholeEntryBuffer entry_buffer_;\n};\nTEST_F(HpackWholeEntryBufferTest, OnIndexedHeader) {\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnIndexedHeader(17));\n entry_buffer_.OnIndexedHeader(17);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnIndexedHeader(62));\n entry_buffer_.OnIndexedHeader(62);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnIndexedHeader(62));\n entry_buffer_.OnIndexedHeader(62);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnIndexedHeader(128));\n entry_buffer_.OnIndexedHeader(128);\n }\n StrictMock listener2;\n entry_buffer_.set_listener(&listener2);\n {\n InSequence seq;\n EXPECT_CALL(listener2, OnIndexedHeader(100));\n entry_buffer_.OnIndexedHeader(100);\n }\n}\nTEST_F(HpackWholeEntryBufferTest, OnDynamicTableSizeUpdate) {\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(4096));\n entry_buffer_.OnDynamicTableSizeUpdate(4096);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(0));\n entry_buffer_.OnDynamicTableSizeUpdate(0);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024));\n entry_buffer_.OnDynamicTableSizeUpdate(1024);\n }\n {\n InSequence seq;\n EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024));\n entry_buffer_.OnDynamicTableSizeUpdate(1024);\n }\n StrictMock listener2;\n entry_buffer_.set_listener(&listener2);\n {\n InSequence seq;\n EXPECT_CALL(listener2, OnDynamicTableSizeUpdate(0));\n entry_buffer_.OnDynamicTableSizeUpdate(0);\n }\n}\nTEST_F(HpackWholeEntryBufferTest, OnNameIndexAndLiteralValue) {\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader,\n 123);\n entry_buffer_.OnValueStart(false, 10);\n entry_buffer_.OnValueData(\"some data.\", 10);\n entry_buffer_.BufferStringsIfUnbuffered();\n EXPECT_CALL(\n listener_,\n OnNameIndexAndLiteralValue(\n HpackEntryType::kNeverIndexedLiteralHeader, 123,\n AllOf(Property(&HpackDecoderStringBuffer::str, \"some data.\"),\n Property(&HpackDecoderStringBuffer::BufferedLength, 10))));\n entry_buffer_.OnValueEnd();\n}\nTEST_F(HpackWholeEntryBufferTest, OnLiteralNameAndValue) {\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);\n entry_buffer_.OnNameStart(false, 9);\n entry_buffer_.OnNameData(\"some-\", 5);\n entry_buffer_.OnNameData(\"name\", 4);\n entry_buffer_.OnNameEnd();\n entry_buffer_.OnValueStart(false, 12);\n entry_buffer_.OnValueData(\"Header Value\", 12);\n EXPECT_CALL(\n listener_,\n OnLiteralNameAndValue(\n HpackEntryType::kIndexedLiteralHeader,\n AllOf(Property(&HpackDecoderStringBuffer::str, \"some-name\"),\n Property(&HpackDecoderStringBuffer::BufferedLength, 9)),\n AllOf(Property(&HpackDecoderStringBuffer::str, \"Header Value\"),\n Property(&HpackDecoderStringBuffer::BufferedLength, 0))));\n entry_buffer_.OnValueEnd();\n}\nTEST_F(HpackWholeEntryBufferTest, NameTooLong) {\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);\n EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kNameTooLong));\n entry_buffer_.OnNameStart(false, kMaxStringSize + 1);\n}\nTEST_F(HpackWholeEntryBufferTest, ValueTooLong) {\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);\n EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong));\n entry_buffer_.OnNameStart(false, 4);\n entry_buffer_.OnNameData(\"path\", 4);\n entry_buffer_.OnNameEnd();\n entry_buffer_.OnValueStart(false, kMaxStringSize + 1);\n}\nTEST_F(HpackWholeEntryBufferTest, ValueTooLongWithoutName) {\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);\n EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong));\n entry_buffer_.OnValueStart(false, kMaxStringSize + 1);\n}\nTEST_F(HpackWholeEntryBufferTest, NameHuffmanError) {\n const char data[] = \"\\xff\\xff\\xff\";\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader,\n 0);\n entry_buffer_.OnNameStart(true, 4);\n entry_buffer_.OnNameData(data, 3);\n EXPECT_CALL(listener_,\n OnHpackDecodeError(HpackDecodingError::kNameHuffmanError));\n entry_buffer_.OnNameData(data, 1);\n EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(8096)).Times(0);\n entry_buffer_.OnDynamicTableSizeUpdate(8096);\n}\nTEST_F(HpackWholeEntryBufferTest, ValueHuffmanError) {\n const char data[] = \"\\x00\\x00\\x00\";\n entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader,\n 61);\n entry_buffer_.OnValueStart(true, 3);\n entry_buffer_.OnValueData(data, 3);\n EXPECT_CALL(listener_,\n OnHpackDecodeError(HpackDecodingError::kValueHuffmanError));\n entry_buffer_.OnValueEnd();\n EXPECT_CALL(listener_, OnIndexedHeader(17)).Times(0);\n entry_buffer_.OnIndexedHeader(17);\n}\n} \n} \n} "}}},{"rowIdx":443,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_\n#define QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_\n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nQUICHE_EXPORT size_t HuffmanSize(absl::string_view plain);\nQUICHE_EXPORT void HuffmanEncode(absl::string_view plain, size_t encoded_size,\n std::string* huffman);\nQUICHE_EXPORT void HuffmanEncodeFast(absl::string_view input,\n size_t encoded_size, std::string* output);\n} \n#endif \n#include \"quiche/http2/hpack/huffman/hpack_huffman_encoder.h\"\n#include \n#include \"quiche/http2/hpack/huffman/huffman_spec_tables.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nsize_t HuffmanSize(absl::string_view plain) {\n size_t bits = 0;\n for (const uint8_t c : plain) {\n bits += HuffmanSpecTables::kCodeLengths[c];\n }\n return (bits + 7) / 8;\n}\nvoid HuffmanEncode(absl::string_view plain, size_t encoded_size,\n std::string* huffman) {\n QUICHE_DCHECK(huffman != nullptr);\n huffman->reserve(huffman->size() + encoded_size);\n uint64_t bit_buffer = 0; \n size_t bits_unused = 64; \n for (uint8_t c : plain) {\n size_t code_length = HuffmanSpecTables::kCodeLengths[c];\n if (bits_unused < code_length) {\n do {\n char h = static_cast(bit_buffer >> 56);\n bit_buffer <<= 8;\n bits_unused += 8;\n huffman->push_back(h);\n } while (bits_unused <= 56);\n }\n uint64_t code = HuffmanSpecTables::kRightCodes[c];\n size_t shift_by = bits_unused - code_length;\n bit_buffer |= (code << shift_by);\n bits_unused -= code_length;\n }\n size_t bits_used = 64 - bits_unused;\n while (bits_used >= 8) {\n char h = static_cast(bit_buffer >> 56);\n bit_buffer <<= 8;\n bits_used -= 8;\n huffman->push_back(h);\n }\n if (bits_used > 0) {\n constexpr uint64_t leading_eos_bits = 0b11111111;\n bit_buffer |= (leading_eos_bits << (56 - bits_used));\n char h = static_cast(bit_buffer >> 56);\n huffman->push_back(h);\n }\n}\nvoid HuffmanEncodeFast(absl::string_view input, size_t encoded_size,\n std::string* output) {\n const size_t original_size = output->size();\n const size_t final_size = original_size + encoded_size;\n output->resize(final_size + 4, 0);\n char* const first = &*output->begin() + original_size;\n size_t bit_counter = 0;\n for (uint8_t c : input) {\n uint64_t code = static_cast(HuffmanSpecTables::kLeftCodes[c])\n << (8 - (bit_counter % 8));\n char* const current = first + (bit_counter / 8);\n bit_counter += HuffmanSpecTables::kCodeLengths[c];\n *current |= code >> 32;\n *(current + 1) |= (code >> 24) & 0xff;\n if ((code & 0xff0000) == 0) {\n continue;\n }\n *(current + 2) |= (code >> 16) & 0xff;\n if ((code & 0xff00) == 0) {\n continue;\n }\n *(current + 3) |= (code >> 8) & 0xff;\n *(current + 4) |= code & 0xff;\n }\n QUICHE_DCHECK_EQ(encoded_size, (bit_counter + 7) / 8);\n if (bit_counter % 8 != 0) {\n *(first + encoded_size - 1) |= 0xff >> (bit_counter & 7);\n }\n output->resize(final_size);\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/huffman/hpack_huffman_encoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"absl/strings/escaping.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace {\nclass HuffmanEncoderTest : public quiche::test::QuicheTestWithParam {\n protected:\n HuffmanEncoderTest() : use_fast_encoder_(GetParam()) {}\n virtual ~HuffmanEncoderTest() = default;\n void Encode(absl::string_view input, size_t encoded_size,\n std::string* output) {\n use_fast_encoder_ ? HuffmanEncodeFast(input, encoded_size, output)\n : HuffmanEncode(input, encoded_size, output);\n }\n const bool use_fast_encoder_;\n};\nINSTANTIATE_TEST_SUITE_P(TwoEncoders, HuffmanEncoderTest, ::testing::Bool());\nTEST_P(HuffmanEncoderTest, Empty) {\n std::string empty(\"\");\n size_t encoded_size = HuffmanSize(empty);\n EXPECT_EQ(0u, encoded_size);\n std::string buffer;\n Encode(empty, encoded_size, &buffer);\n EXPECT_EQ(\"\", buffer);\n}\nTEST_P(HuffmanEncoderTest, SpecRequestExamples) {\n std::string test_table[] = {\n \"f1e3c2e5f23a6ba0ab90f4ff\",\n \"www.example.com\",\n \"a8eb10649cbf\",\n \"no-cache\",\n \"25a849e95ba97d7f\",\n \"custom-key\",\n \"25a849e95bb8e8b4bf\",\n \"custom-value\",\n };\n for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {\n std::string huffman_encoded;\n ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));\n const std::string& plain_string(test_table[i + 1]);\n size_t encoded_size = HuffmanSize(plain_string);\n EXPECT_EQ(huffman_encoded.size(), encoded_size);\n std::string buffer;\n buffer.reserve(huffman_encoded.size());\n Encode(plain_string, encoded_size, &buffer);\n EXPECT_EQ(buffer, huffman_encoded) << \"Error encoding \" << plain_string;\n }\n}\nTEST_P(HuffmanEncoderTest, SpecResponseExamples) {\n std::string test_table[] = {\n \"6402\",\n \"302\",\n \"aec3771a4b\",\n \"private\",\n \"d07abe941054d444a8200595040b8166e082a62d1bff\",\n \"Mon, 21 Oct 2013 20:13:21 GMT\",\n \"9d29ad171863c78f0b97c8e9ae82ae43d3\",\n \"https:\n \"94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0\"\n \"03ed4ee5b1063d5007\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\",\n };\n for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {\n std::string huffman_encoded;\n ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));\n const std::string& plain_string(test_table[i + 1]);\n size_t encoded_size = HuffmanSize(plain_string);\n EXPECT_EQ(huffman_encoded.size(), encoded_size);\n std::string buffer;\n Encode(plain_string, encoded_size, &buffer);\n EXPECT_EQ(buffer, huffman_encoded) << \"Error encoding \" << plain_string;\n }\n}\nTEST_P(HuffmanEncoderTest, EncodedSizeAgreesWithEncodeString) {\n std::string test_table[] = {\n \"\",\n \"Mon, 21 Oct 2013 20:13:21 GMT\",\n \"https:\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\",\n std::string(1, '\\0'),\n std::string(\"foo\\0bar\", 7),\n std::string(256, '\\0'),\n };\n for (size_t i = 0; i != 256; ++i) {\n test_table[ABSL_ARRAYSIZE(test_table) - 1][i] = static_cast(i);\n }\n for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); ++i) {\n const std::string& plain_string = test_table[i];\n size_t encoded_size = HuffmanSize(plain_string);\n std::string huffman_encoded;\n Encode(plain_string, encoded_size, &huffman_encoded);\n EXPECT_EQ(encoded_size, huffman_encoded.size());\n }\n}\nTEST_P(HuffmanEncoderTest, AppendToOutput) {\n size_t encoded_size = HuffmanSize(\"foo\");\n std::string buffer;\n Encode(\"foo\", encoded_size, &buffer);\n std::string expected_encoding;\n ASSERT_TRUE(absl::HexStringToBytes(\"94e7\", &expected_encoding));\n EXPECT_EQ(expected_encoding, buffer);\n encoded_size = HuffmanSize(\"bar\");\n Encode(\"bar\", encoded_size, &buffer);\n ASSERT_TRUE(absl::HexStringToBytes(\"94e78c767f\", &expected_encoding));\n EXPECT_EQ(expected_encoding, buffer);\n}\n} \n} "}}},{"rowIdx":444,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_DECODER_H_\n#define QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_DECODER_H_\n#include \n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\ntypedef uint64_t HuffmanAccumulator;\ntypedef size_t HuffmanAccumulatorBitCount;\nclass QUICHE_EXPORT HuffmanBitBuffer {\n public:\n HuffmanBitBuffer();\n void Reset();\n size_t AppendBytes(absl::string_view input);\n HuffmanAccumulator value() const { return accumulator_; }\n HuffmanAccumulatorBitCount count() const { return count_; }\n bool IsEmpty() const { return count_ == 0; }\n HuffmanAccumulatorBitCount free_count() const;\n void ConsumeBits(HuffmanAccumulatorBitCount code_length);\n bool InputProperlyTerminated() const;\n std::string DebugString() const;\n private:\n HuffmanAccumulator accumulator_;\n HuffmanAccumulatorBitCount count_;\n};\ninline std::ostream& operator<<(std::ostream& out, const HuffmanBitBuffer& v) {\n return out << v.DebugString();\n}\nclass QUICHE_EXPORT HpackHuffmanDecoder {\n public:\n HpackHuffmanDecoder();\n ~HpackHuffmanDecoder();\n void Reset() { bit_buffer_.Reset(); }\n bool Decode(absl::string_view input, std::string* output);\n bool InputProperlyTerminated() const {\n return bit_buffer_.InputProperlyTerminated();\n }\n std::string DebugString() const;\n private:\n HuffmanBitBuffer bit_buffer_;\n};\ninline std::ostream& operator<<(std::ostream& out,\n const HpackHuffmanDecoder& v) {\n return out << v.DebugString();\n}\n} \n#endif \n#include \"quiche/http2/hpack/huffman/hpack_huffman_decoder.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace {\ntypedef uint32_t HuffmanCode;\ntypedef uint16_t HuffmanCodeBitCount;\ntypedef std::bitset<32> HuffmanCodeBitSet;\ntypedef std::bitset<64> HuffmanAccumulatorBitSet;\nstatic constexpr HuffmanCodeBitCount kMinCodeBitCount = 5;\nstatic constexpr HuffmanCodeBitCount kMaxCodeBitCount = 30;\nstatic constexpr HuffmanCodeBitCount kHuffmanCodeBitCount =\n std::numeric_limits::digits;\nstatic_assert(std::numeric_limits::digits >= kMaxCodeBitCount,\n \"HuffmanCode isn't big enough.\");\nstatic_assert(std::numeric_limits::digits >=\n kMaxCodeBitCount,\n \"HuffmanAccumulator isn't big enough.\");\nstatic constexpr HuffmanAccumulatorBitCount kHuffmanAccumulatorBitCount =\n std::numeric_limits::digits;\nstatic constexpr HuffmanAccumulatorBitCount kExtraAccumulatorBitCount =\n kHuffmanAccumulatorBitCount - kHuffmanCodeBitCount;\nstruct PrefixInfo {\n uint32_t DecodeToCanonical(HuffmanCode bits) const {\n HuffmanCode ordinal_in_length =\n ((bits - first_code) >> (kHuffmanCodeBitCount - code_length));\n return first_canonical + ordinal_in_length;\n }\n const HuffmanCode first_code; \n const uint16_t code_length; \n const uint16_t first_canonical; \n};\ninline std::ostream& operator<<(std::ostream& out, const PrefixInfo& v) {\n return out << \"{first_code: \" << HuffmanCodeBitSet(v.first_code)\n << \", code_length: \" << v.code_length\n << \", first_canonical: \" << v.first_canonical << \"}\";\n}\nPrefixInfo PrefixToInfo(HuffmanCode value) {\n if (value < 0b10111000000000000000000000000000) {\n if (value < 0b01010000000000000000000000000000) {\n return {0b00000000000000000000000000000000, 5, 0};\n } else {\n return {0b01010000000000000000000000000000, 6, 10};\n }\n } else {\n if (value < 0b11111110000000000000000000000000) {\n if (value < 0b11111000000000000000000000000000) {\n return {0b10111000000000000000000000000000, 7, 36};\n } else {\n return {0b11111000000000000000000000000000, 8, 68};\n }\n } else {\n if (value < 0b11111111110000000000000000000000) {\n if (value < 0b11111111101000000000000000000000) {\n if (value < 0b11111111010000000000000000000000) {\n return {0b11111110000000000000000000000000, 10, 74};\n } else {\n return {0b11111111010000000000000000000000, 11, 79};\n }\n } else {\n return {0b11111111101000000000000000000000, 12, 82};\n }\n } else {\n if (value < 0b11111111111111100000000000000000) {\n if (value < 0b11111111111110000000000000000000) {\n if (value < 0b11111111111100000000000000000000) {\n return {0b11111111110000000000000000000000, 13, 84};\n } else {\n return {0b11111111111100000000000000000000, 14, 90};\n }\n } else {\n return {0b11111111111110000000000000000000, 15, 92};\n }\n } else {\n if (value < 0b11111111111111110100100000000000) {\n if (value < 0b11111111111111101110000000000000) {\n if (value < 0b11111111111111100110000000000000) {\n return {0b11111111111111100000000000000000, 19, 95};\n } else {\n return {0b11111111111111100110000000000000, 20, 98};\n }\n } else {\n return {0b11111111111111101110000000000000, 21, 106};\n }\n } else {\n if (value < 0b11111111111111111110101000000000) {\n if (value < 0b11111111111111111011000000000000) {\n return {0b11111111111111110100100000000000, 22, 119};\n } else {\n return {0b11111111111111111011000000000000, 23, 145};\n }\n } else {\n if (value < 0b11111111111111111111101111000000) {\n if (value < 0b11111111111111111111100000000000) {\n if (value < 0b11111111111111111111011000000000) {\n return {0b11111111111111111110101000000000, 24, 174};\n } else {\n return {0b11111111111111111111011000000000, 25, 186};\n }\n } else {\n return {0b11111111111111111111100000000000, 26, 190};\n }\n } else {\n if (value < 0b11111111111111111111111111110000) {\n if (value < 0b11111111111111111111111000100000) {\n return {0b11111111111111111111101111000000, 27, 205};\n } else {\n return {0b11111111111111111111111000100000, 28, 224};\n }\n } else {\n return {0b11111111111111111111111111110000, 30, 253};\n }\n }\n }\n }\n }\n }\n }\n }\n}\nconstexpr unsigned char kCanonicalToSymbol[] = {\n '0', '1', '2', 'a', 'c', 'e', 'i', 'o',\n 's', 't', 0x20, '%', '-', '.', '/', '3',\n '4', '5', '6', '7', '8', '9', '=', 'A',\n '_', 'b', 'd', 'f', 'g', 'h', 'l', 'm',\n 'n', 'p', 'r', 'u', ':', 'B', 'C', 'D',\n 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',\n 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',\n 'U', 'V', 'W', 'Y', 'j', 'k', 'q', 'v',\n 'w', 'x', 'y', 'z', '&', '*', ',', ';',\n 'X', 'Z', '!', '\\\"', '(', ')', '?', '\\'',\n '+', '|', '#', '>', 0x00, '$', '@', '[',\n ']', '~', '^', '}', '<', '`', '{', '\\\\',\n 0xc3, 0xd0, 0x80, 0x82, 0x83, 0xa2, 0xb8, 0xc2,\n 0xe0, 0xe2, 0x99, 0xa1, 0xa7, 0xac, 0xb0, 0xb1,\n 0xb3, 0xd1, 0xd8, 0xd9, 0xe3, 0xe5, 0xe6, 0x81,\n 0x84, 0x85, 0x86, 0x88, 0x92, 0x9a, 0x9c, 0xa0,\n 0xa3, 0xa4, 0xa9, 0xaa, 0xad, 0xb2, 0xb5, 0xb9,\n 0xba, 0xbb, 0xbd, 0xbe, 0xc4, 0xc6, 0xe4, 0xe8,\n 0xe9, 0x01, 0x87, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,\n 0x8f, 0x93, 0x95, 0x96, 0x97, 0x98, 0x9b, 0x9d,\n 0x9e, 0xa5, 0xa6, 0xa8, 0xae, 0xaf, 0xb4, 0xb6,\n 0xb7, 0xbc, 0xbf, 0xc5, 0xe7, 0xef, 0x09, 0x8e,\n 0x90, 0x91, 0x94, 0x9f, 0xab, 0xce, 0xd7, 0xe1,\n 0xec, 0xed, 0xc7, 0xcf, 0xea, 0xeb, 0xc0, 0xc1,\n 0xc8, 0xc9, 0xca, 0xcd, 0xd2, 0xd5, 0xda, 0xdb,\n 0xee, 0xf0, 0xf2, 0xf3, 0xff, 0xcb, 0xcc, 0xd3,\n 0xd4, 0xd6, 0xdd, 0xde, 0xdf, 0xf1, 0xf4, 0xf5,\n 0xf6, 0xf7, 0xf8, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,\n 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0b,\n 0x0c, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,\n 0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,\n 0x1e, 0x1f, 0x7f, 0xdc, 0xf9, 0x0a, 0x0d, 0x16,\n};\nconstexpr size_t kShortCodeTableSize = 124;\nstruct ShortCodeInfo {\n uint8_t symbol;\n uint8_t length;\n} kShortCodeTable[kShortCodeTableSize] = {\n {0x30, 5}, \n {0x30, 5}, \n {0x30, 5}, \n {0x30, 5}, \n {0x31, 5}, \n {0x31, 5}, \n {0x31, 5}, \n {0x31, 5}, \n {0x32, 5}, \n {0x32, 5}, \n {0x32, 5}, \n {0x32, 5}, \n {0x61, 5}, \n {0x61, 5}, \n {0x61, 5}, \n {0x61, 5}, \n {0x63, 5}, \n {0x63, 5}, \n {0x63, 5}, \n {0x63, 5}, \n {0x65, 5}, \n {0x65, 5}, \n {0x65, 5}, \n {0x65, 5}, \n {0x69, 5}, \n {0x69, 5}, \n {0x69, 5}, \n {0x69, 5}, \n {0x6f, 5}, \n {0x6f, 5}, \n {0x6f, 5}, \n {0x6f, 5}, \n {0x73, 5}, \n {0x73, 5}, \n {0x73, 5}, \n {0x73, 5}, \n {0x74, 5}, \n {0x74, 5}, \n {0x74, 5}, \n {0x74, 5}, \n {0x20, 6}, \n {0x20, 6}, \n {0x25, 6}, \n {0x25, 6}, \n {0x2d, 6}, \n {0x2d, 6}, \n {0x2e, 6}, \n {0x2e, 6}, \n {0x2f, 6}, \n {0x2f, 6}, \n {0x33, 6}, \n {0x33, 6}, \n {0x34, 6}, \n {0x34, 6}, \n {0x35, 6}, \n {0x35, 6}, \n {0x36, 6}, \n {0x36, 6}, \n {0x37, 6}, \n {0x37, 6}, \n {0x38, 6}, \n {0x38, 6}, \n {0x39, 6}, \n {0x39, 6}, \n {0x3d, 6}, \n {0x3d, 6}, \n {0x41, 6}, \n {0x41, 6}, \n {0x5f, 6}, \n {0x5f, 6}, \n {0x62, 6}, \n {0x62, 6}, \n {0x64, 6}, \n {0x64, 6}, \n {0x66, 6}, \n {0x66, 6}, \n {0x67, 6}, \n {0x67, 6}, \n {0x68, 6}, \n {0x68, 6}, \n {0x6c, 6}, \n {0x6c, 6}, \n {0x6d, 6}, \n {0x6d, 6}, \n {0x6e, 6}, \n {0x6e, 6}, \n {0x70, 6}, \n {0x70, 6}, \n {0x72, 6}, \n {0x72, 6}, \n {0x75, 6}, \n {0x75, 6}, \n {0x3a, 7}, \n {0x42, 7}, \n {0x43, 7}, \n {0x44, 7}, \n {0x45, 7}, \n {0x46, 7}, \n {0x47, 7}, \n {0x48, 7}, \n {0x49, 7}, \n {0x4a, 7}, \n {0x4b, 7}, \n {0x4c, 7}, \n {0x4d, 7}, \n {0x4e, 7}, \n {0x4f, 7}, \n {0x50, 7}, \n {0x51, 7}, \n {0x52, 7}, \n {0x53, 7}, \n {0x54, 7}, \n {0x55, 7}, \n {0x56, 7}, \n {0x57, 7}, \n {0x59, 7}, \n {0x6a, 7}, \n {0x6b, 7}, \n {0x71, 7}, \n {0x76, 7}, \n {0x77, 7}, \n {0x78, 7}, \n {0x79, 7}, \n {0x7a, 7}, \n};\n} \nHuffmanBitBuffer::HuffmanBitBuffer() { Reset(); }\nvoid HuffmanBitBuffer::Reset() {\n accumulator_ = 0;\n count_ = 0;\n}\nsize_t HuffmanBitBuffer::AppendBytes(absl::string_view input) {\n HuffmanAccumulatorBitCount free_cnt = free_count();\n size_t bytes_available = input.size();\n if (free_cnt < 8 || bytes_available == 0) {\n return 0;\n }\n size_t bytes_used = 0;\n auto* ptr = reinterpret_cast(input.data());\n do {\n auto b = static_cast(*ptr++);\n free_cnt -= 8;\n accumulator_ |= (b << free_cnt);\n ++bytes_used;\n } while (free_cnt >= 8 && bytes_used < bytes_available);\n count_ += (bytes_used * 8);\n return bytes_used;\n}\nHuffmanAccumulatorBitCount HuffmanBitBuffer::free_count() const {\n return kHuffmanAccumulatorBitCount - count_;\n}\nvoid HuffmanBitBuffer::ConsumeBits(HuffmanAccumulatorBitCount code_length) {\n QUICHE_DCHECK_LE(code_length, count_);\n accumulator_ <<= code_length;\n count_ -= code_length;\n}\nbool HuffmanBitBuffer::InputProperlyTerminated() const {\n auto cnt = count();\n if (cnt < 8) {\n if (cnt == 0) {\n return true;\n }\n HuffmanAccumulator expected = ~(~HuffmanAccumulator() >> cnt);\n QUICHE_DCHECK_EQ(accumulator_ & ~expected, 0u)\n << \"\\n expected: \" << HuffmanAccumulatorBitSet(expected) << \"\\n \"\n << *this;\n return accumulator_ == expected;\n }\n return false;\n}\nstd::string HuffmanBitBuffer::DebugString() const {\n std::stringstream ss;\n ss << \"{accumulator: \" << HuffmanAccumulatorBitSet(accumulator_)\n << \"; count: \" << count_ << \"}\";\n return ss.str();\n}\nHpackHuffmanDecoder::HpackHuffmanDecoder() = default;\nHpackHuffmanDecoder::~HpackHuffmanDecoder() = default;\nbool HpackHuffmanDecoder::Decode(absl::string_view input, std::string* output) {\n QUICHE_DVLOG(1) << \"HpackHuffmanDecoder::Decode\";\n input.remove_prefix(bit_buffer_.AppendBytes(input));\n while (true) {\n QUICHE_DVLOG(3) << \"Enter Decode Loop, bit_buffer_: \" << bit_buffer_;\n if (bit_buffer_.count() >= 7) {\n uint8_t short_code =\n bit_buffer_.value() >> (kHuffmanAccumulatorBitCount - 7);\n QUICHE_DCHECK_LT(short_code, 128);\n if (short_code < kShortCodeTableSize) {\n ShortCodeInfo info = kShortCodeTable[short_code];\n bit_buffer_.ConsumeBits(info.length);\n output->push_back(static_cast(info.symbol));\n continue;\n }\n } else {\n size_t byte_count = bit_buffer_.AppendBytes(input);\n if (byte_count > 0) {\n input.remove_prefix(byte_count);\n continue;\n }\n }\n HuffmanCode code_prefix = bit_buffer_.value() >> kExtraAccumulatorBitCount;\n QUICHE_DVLOG(3) << \"code_prefix: \" << HuffmanCodeBitSet(code_prefix);\n PrefixInfo prefix_info = PrefixToInfo(code_prefix);\n QUICHE_DVLOG(3) << \"prefix_info: \" << prefix_info;\n QUICHE_DCHECK_LE(kMinCodeBitCount, prefix_info.code_length);\n QUICHE_DCHECK_LE(prefix_info.code_length, kMaxCodeBitCount);\n if (prefix_info.code_length <= bit_buffer_.count()) {\n uint32_t canonical = prefix_info.DecodeToCanonical(code_prefix);\n if (canonical < 256) {\n char c = kCanonicalToSymbol[canonical];\n output->push_back(c);\n bit_buffer_.ConsumeBits(prefix_info.code_length);\n continue;\n }\n QUICHE_DLOG(ERROR) << \"EOS explicitly encoded!\\n \" << bit_buffer_ << \"\\n \"\n << prefix_info;\n return false;\n }\n size_t byte_count = bit_buffer_.AppendBytes(input);\n if (byte_count == 0) {\n QUICHE_DCHECK_EQ(input.size(), 0u);\n return true;\n }\n input.remove_prefix(byte_count);\n }\n}\nstd::string HpackHuffmanDecoder::DebugString() const {\n return bit_buffer_.DebugString();\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/huffman/hpack_huffman_decoder.h\"\n#include \n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"absl/strings/escaping.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(HuffmanBitBufferTest, Reset) {\n HuffmanBitBuffer bb;\n EXPECT_TRUE(bb.IsEmpty());\n EXPECT_TRUE(bb.InputProperlyTerminated());\n EXPECT_EQ(bb.count(), 0u);\n EXPECT_EQ(bb.free_count(), 64u);\n EXPECT_EQ(bb.value(), 0u);\n}\nTEST(HuffmanBitBufferTest, AppendBytesAligned) {\n std::string s;\n s.push_back('\\x11');\n s.push_back('\\x22');\n s.push_back('\\x33');\n absl::string_view sp(s);\n HuffmanBitBuffer bb;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_TRUE(sp.empty());\n EXPECT_FALSE(bb.IsEmpty()) << bb;\n EXPECT_FALSE(bb.InputProperlyTerminated());\n EXPECT_EQ(bb.count(), 24u) << bb;\n EXPECT_EQ(bb.free_count(), 40u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 40) << bb;\n s.clear();\n s.push_back('\\x44');\n sp = s;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_TRUE(sp.empty());\n EXPECT_EQ(bb.count(), 32u) << bb;\n EXPECT_EQ(bb.free_count(), 32u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x11223344) << 32) << bb;\n s.clear();\n s.push_back('\\x55');\n s.push_back('\\x66');\n s.push_back('\\x77');\n s.push_back('\\x88');\n s.push_back('\\x99');\n sp = s;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_EQ(sp.size(), 1u);\n EXPECT_EQ('\\x99', sp[0]);\n EXPECT_EQ(bb.count(), 64u) << bb;\n EXPECT_EQ(bb.free_count(), 0u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_EQ(sp.size(), 1u);\n EXPECT_EQ('\\x99', sp[0]);\n EXPECT_EQ(bb.count(), 64u) << bb;\n EXPECT_EQ(bb.free_count(), 0u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb;\n}\nTEST(HuffmanBitBufferTest, ConsumeBits) {\n std::string s;\n s.push_back('\\x11');\n s.push_back('\\x22');\n s.push_back('\\x33');\n absl::string_view sp(s);\n HuffmanBitBuffer bb;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_TRUE(sp.empty());\n bb.ConsumeBits(1);\n EXPECT_EQ(bb.count(), 23u) << bb;\n EXPECT_EQ(bb.free_count(), 41u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 41) << bb;\n bb.ConsumeBits(20);\n EXPECT_EQ(bb.count(), 3u) << bb;\n EXPECT_EQ(bb.free_count(), 61u) << bb;\n EXPECT_EQ(bb.value(), HuffmanAccumulator(0x3) << 61) << bb;\n}\nTEST(HuffmanBitBufferTest, AppendBytesUnaligned) {\n std::string s;\n s.push_back('\\x11');\n s.push_back('\\x22');\n s.push_back('\\x33');\n s.push_back('\\x44');\n s.push_back('\\x55');\n s.push_back('\\x66');\n s.push_back('\\x77');\n s.push_back('\\x88');\n s.push_back('\\x99');\n s.push_back('\\xaa');\n s.push_back('\\xbb');\n s.push_back('\\xcc');\n s.push_back('\\xdd');\n absl::string_view sp(s);\n HuffmanBitBuffer bb;\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_EQ(sp.size(), 5u);\n EXPECT_FALSE(bb.InputProperlyTerminated());\n bb.ConsumeBits(15);\n EXPECT_EQ(bb.count(), 49u) << bb;\n EXPECT_EQ(bb.free_count(), 15u) << bb;\n HuffmanAccumulator expected(0x1122334455667788);\n expected <<= 15;\n EXPECT_EQ(bb.value(), expected);\n sp.remove_prefix(bb.AppendBytes(sp));\n EXPECT_EQ(sp.size(), 4u);\n EXPECT_EQ(bb.count(), 57u) << bb;\n EXPECT_EQ(bb.free_count(), 7u) << bb;\n expected |= (HuffmanAccumulator(0x99) << 7);\n EXPECT_EQ(bb.value(), expected)\n << bb << std::hex << \"\\n actual: \" << bb.value()\n << \"\\n expected: \" << expected;\n}\nclass HpackHuffmanDecoderTest : public RandomDecoderTest {\n protected:\n HpackHuffmanDecoderTest() {\n stop_decode_on_done_ = false;\n }\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n input_bytes_seen_ = 0;\n output_buffer_.clear();\n decoder_.Reset();\n return ResumeDecoding(b);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n input_bytes_seen_ += b->Remaining();\n absl::string_view sp(b->cursor(), b->Remaining());\n if (decoder_.Decode(sp, &output_buffer_)) {\n b->AdvanceCursor(b->Remaining());\n EXPECT_LE(input_bytes_seen_, input_bytes_expected_);\n if (input_bytes_expected_ == input_bytes_seen_) {\n if (decoder_.InputProperlyTerminated()) {\n return DecodeStatus::kDecodeDone;\n } else {\n return DecodeStatus::kDecodeError;\n }\n }\n return DecodeStatus::kDecodeInProgress;\n }\n return DecodeStatus::kDecodeError;\n }\n HpackHuffmanDecoder decoder_;\n std::string output_buffer_;\n size_t input_bytes_seen_;\n size_t input_bytes_expected_;\n};\nTEST_F(HpackHuffmanDecoderTest, SpecRequestExamples) {\n HpackHuffmanDecoder decoder;\n std::string test_table[] = {\n \"f1e3c2e5f23a6ba0ab90f4ff\",\n \"www.example.com\",\n \"a8eb10649cbf\",\n \"no-cache\",\n \"25a849e95ba97d7f\",\n \"custom-key\",\n \"25a849e95bb8e8b4bf\",\n \"custom-value\",\n };\n for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {\n std::string huffman_encoded;\n ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));\n const std::string& plain_string(test_table[i + 1]);\n std::string buffer;\n decoder.Reset();\n EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder;\n EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder;\n EXPECT_EQ(buffer, plain_string);\n }\n}\nTEST_F(HpackHuffmanDecoderTest, SpecResponseExamples) {\n HpackHuffmanDecoder decoder;\n std::string test_table[] = {\n \"6402\",\n \"302\",\n \"aec3771a4b\",\n \"private\",\n \"d07abe941054d444a8200595040b8166e082a62d1bff\",\n \"Mon, 21 Oct 2013 20:13:21 GMT\",\n \"9d29ad171863c78f0b97c8e9ae82ae43d3\",\n \"https:\n \"94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0\"\n \"03ed4ee5b1063d5007\",\n \"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1\",\n };\n for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {\n std::string huffman_encoded;\n ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));\n const std::string& plain_string(test_table[i + 1]);\n std::string buffer;\n decoder.Reset();\n EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder;\n EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder;\n EXPECT_EQ(buffer, plain_string);\n }\n}\n} \n} \n} "}}},{"rowIdx":445,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_DECODER_H_\n#define QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_DECODER_H_\n#include \n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\n#ifndef NDEBUG\nconst uint8_t kHpackVarintDecoderOffsetDone =\n std::numeric_limits::max();\n#endif\nclass QUICHE_EXPORT HpackVarintDecoder {\n public:\n DecodeStatus Start(uint8_t prefix_value, uint8_t prefix_length,\n DecodeBuffer* db);\n DecodeStatus StartExtended(uint8_t prefix_length, DecodeBuffer* db);\n DecodeStatus Resume(DecodeBuffer* db);\n uint64_t value() const;\n void set_value(uint64_t v);\n std::string DebugString() const;\n DecodeStatus StartForTest(uint8_t prefix_value, uint8_t prefix_length,\n DecodeBuffer* db);\n DecodeStatus StartExtendedForTest(uint8_t prefix_length, DecodeBuffer* db);\n DecodeStatus ResumeForTest(DecodeBuffer* db);\n private:\n void MarkDone() {\n#ifndef NDEBUG\n offset_ = kHpackVarintDecoderOffsetDone;\n#endif\n }\n void CheckNotDone() const {\n#ifndef NDEBUG\n QUICHE_DCHECK_NE(kHpackVarintDecoderOffsetDone, offset_);\n#endif\n }\n void CheckDone() const {\n#ifndef NDEBUG\n QUICHE_DCHECK_EQ(kHpackVarintDecoderOffsetDone, offset_);\n#endif\n }\n uint64_t value_ = 0;\n uint8_t offset_ = 0;\n};\n} \n#endif \n#include \"quiche/http2/hpack/varint/hpack_varint_decoder.h\"\n#include \n#include \n#include \"absl/strings/str_cat.h\"\nnamespace http2 {\nDecodeStatus HpackVarintDecoder::Start(uint8_t prefix_value,\n uint8_t prefix_length,\n DecodeBuffer* db) {\n QUICHE_DCHECK_LE(3u, prefix_length);\n QUICHE_DCHECK_LE(prefix_length, 8u);\n const uint8_t prefix_mask = (1 << prefix_length) - 1;\n value_ = prefix_value & prefix_mask;\n if (value_ < prefix_mask) {\n MarkDone();\n return DecodeStatus::kDecodeDone;\n }\n offset_ = 0;\n return Resume(db);\n}\nDecodeStatus HpackVarintDecoder::StartExtended(uint8_t prefix_length,\n DecodeBuffer* db) {\n QUICHE_DCHECK_LE(3u, prefix_length);\n QUICHE_DCHECK_LE(prefix_length, 8u);\n value_ = (1 << prefix_length) - 1;\n offset_ = 0;\n return Resume(db);\n}\nDecodeStatus HpackVarintDecoder::Resume(DecodeBuffer* db) {\n const uint8_t kMaxOffset = 63;\n CheckNotDone();\n while (offset_ < kMaxOffset) {\n if (db->Empty()) {\n return DecodeStatus::kDecodeInProgress;\n }\n uint8_t byte = db->DecodeUInt8();\n uint64_t summand = byte & 0x7f;\n QUICHE_DCHECK_LE(offset_, 56);\n QUICHE_DCHECK_LE(summand, std::numeric_limits::max() >> offset_);\n summand <<= offset_;\n QUICHE_DCHECK_LE(value_, std::numeric_limits::max() - summand);\n value_ += summand;\n if ((byte & 0x80) == 0) {\n MarkDone();\n return DecodeStatus::kDecodeDone;\n }\n offset_ += 7;\n }\n if (db->Empty()) {\n return DecodeStatus::kDecodeInProgress;\n }\n QUICHE_DCHECK_EQ(kMaxOffset, offset_);\n uint8_t byte = db->DecodeUInt8();\n if ((byte & 0x80) == 0) {\n uint64_t summand = byte & 0x7f;\n if (summand <= std::numeric_limits::max() >> offset_) {\n summand <<= offset_;\n if (value_ <= std::numeric_limits::max() - summand) {\n value_ += summand;\n MarkDone();\n return DecodeStatus::kDecodeDone;\n }\n }\n }\n QUICHE_DLOG(WARNING)\n << \"Variable length int encoding is too large or too long. \"\n << DebugString();\n MarkDone();\n return DecodeStatus::kDecodeError;\n}\nuint64_t HpackVarintDecoder::value() const {\n CheckDone();\n return value_;\n}\nvoid HpackVarintDecoder::set_value(uint64_t v) {\n MarkDone();\n value_ = v;\n}\nstd::string HpackVarintDecoder::DebugString() const {\n return absl::StrCat(\"HpackVarintDecoder(value=\", value_, \", offset=\", offset_,\n \")\");\n}\nDecodeStatus HpackVarintDecoder::StartForTest(uint8_t prefix_value,\n uint8_t prefix_length,\n DecodeBuffer* db) {\n return Start(prefix_value, prefix_length, db);\n}\nDecodeStatus HpackVarintDecoder::StartExtendedForTest(uint8_t prefix_length,\n DecodeBuffer* db) {\n return StartExtended(prefix_length, db);\n}\nDecodeStatus HpackVarintDecoder::ResumeForTest(DecodeBuffer* db) {\n return Resume(db);\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/varint/hpack_varint_decoder.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nnamespace {\nclass HpackVarintDecoderTest\n : public RandomDecoderTest,\n public ::testing::WithParamInterface> {\n protected:\n HpackVarintDecoderTest()\n : high_bits_(std::get<0>(GetParam())), prefix_length_(0) {\n QUICHE_CHECK(absl::HexStringToBytes(std::get<1>(GetParam()), &suffix_));\n }\n void DecodeExpectSuccess(absl::string_view data, uint32_t prefix_length,\n uint64_t expected_value) {\n Validator validator = [expected_value, this](\n const DecodeBuffer& ,\n DecodeStatus ) -> AssertionResult {\n HTTP2_VERIFY_EQ(expected_value, decoder_.value())\n << \"Value doesn't match expected: \" << decoder_.value()\n << \" != \" << expected_value;\n return AssertionSuccess();\n };\n validator =\n ValidateDoneAndOffset( data.size(), std::move(validator));\n EXPECT_TRUE(Decode(data, prefix_length, std::move(validator)));\n EXPECT_EQ(expected_value, decoder_.value());\n }\n void DecodeExpectError(absl::string_view data, uint32_t prefix_length) {\n Validator validator = [](const DecodeBuffer& ,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(DecodeStatus::kDecodeError, status);\n return AssertionSuccess();\n };\n EXPECT_TRUE(Decode(data, prefix_length, std::move(validator)));\n }\n private:\n AssertionResult Decode(absl::string_view data, uint32_t prefix_length,\n const Validator validator) {\n prefix_length_ = prefix_length;\n std::string data_copy(data);\n uint8_t high_bits_mask = 0b11111111 << prefix_length_;\n data_copy[0] |= (high_bits_mask & high_bits_);\n data_copy.append(suffix_);\n DecodeBuffer b(data_copy);\n bool return_non_zero_on_first = true;\n return DecodeAndValidateSeveralWays(&b, return_non_zero_on_first,\n validator);\n }\n DecodeStatus StartDecoding(DecodeBuffer* b) override {\n QUICHE_CHECK_LT(0u, b->Remaining());\n uint8_t prefix = b->DecodeUInt8();\n return decoder_.Start(prefix, prefix_length_, b);\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* b) override {\n return decoder_.Resume(b);\n }\n const uint8_t high_bits_;\n std::string suffix_;\n HpackVarintDecoder decoder_;\n uint8_t prefix_length_;\n};\nINSTANTIATE_TEST_SUITE_P(\n HpackVarintDecoderTest, HpackVarintDecoderTest,\n ::testing::Combine(\n ::testing::Values(0b00000000, 0b11111111, 0b10101010),\n ::testing::Values(\"\", \"00\", \"666f6f\")));\nstruct {\n const char* data;\n uint32_t prefix_length;\n uint64_t expected_value;\n} kSuccessTestData[] = {\n {\"00\", 3, 0},\n {\"00\", 4, 0},\n {\"00\", 5, 0},\n {\"00\", 6, 0},\n {\"00\", 7, 0},\n {\"00\", 8, 0},\n {\"06\", 3, 6},\n {\"0d\", 4, 13},\n {\"10\", 5, 16},\n {\"29\", 6, 41},\n {\"56\", 7, 86},\n {\"bf\", 8, 191},\n {\"0700\", 3, 7},\n {\"0f00\", 4, 15},\n {\"1f00\", 5, 31},\n {\"3f00\", 6, 63},\n {\"7f00\", 7, 127},\n {\"ff00\", 8, 255},\n {\"078000\", 3, 7},\n {\"0f8000\", 4, 15},\n {\"1f8000\", 5, 31},\n {\"3f8000\", 6, 63},\n {\"7f8000\", 7, 127},\n {\"ff8000\", 8, 255},\n {\"0760\", 3, 103},\n {\"0f2a\", 4, 57},\n {\"1f7f\", 5, 158},\n {\"3f02\", 6, 65},\n {\"7f49\", 7, 200},\n {\"ff6f\", 8, 366},\n {\"07e000\", 3, 103},\n {\"0faa00\", 4, 57},\n {\"1fff00\", 5, 158},\n {\"3f8200\", 6, 65},\n {\"7fc900\", 7, 200},\n {\"ffef00\", 8, 366},\n {\"07e08000\", 3, 103},\n {\"0faa8000\", 4, 57},\n {\"1fff8000\", 5, 158},\n {\"3f828000\", 6, 65},\n {\"7fc98000\", 7, 200},\n {\"ffef8000\", 8, 366},\n {\"07e0808080808080808000\", 3, 103},\n {\"0faa808080808080808000\", 4, 57},\n {\"1fff808080808080808000\", 5, 158},\n {\"3f82808080808080808000\", 6, 65},\n {\"7fc9808080808080808000\", 7, 200},\n {\"ffef808080808080808000\", 8, 366},\n {\"07b260\", 3, 12345},\n {\"0f8a2a\", 4, 5401},\n {\"1fa87f\", 5, 16327},\n {\"3fd002\", 6, 399},\n {\"7fff49\", 7, 9598},\n {\"ffe32f\", 8, 6370},\n {\"07b2e000\", 3, 12345},\n {\"0f8aaa00\", 4, 5401},\n {\"1fa8ff00\", 5, 16327},\n {\"3fd08200\", 6, 399},\n {\"7fffc900\", 7, 9598},\n {\"ffe3af00\", 8, 6370},\n {\"07b2e080808080808000\", 3, 12345},\n {\"0f8aaa80808080808000\", 4, 5401},\n {\"1fa8ff80808080808000\", 5, 16327},\n {\"3fd08280808080808000\", 6, 399},\n {\"7fffc980808080808000\", 7, 9598},\n {\"ffe3af80808080808000\", 8, 6370},\n {\"078ab260\", 3, 1579281},\n {\"0fc18a2a\", 4, 689488},\n {\"1fada87f\", 5, 2085964},\n {\"3fa0d002\", 6, 43103},\n {\"7ffeff49\", 7, 1212541},\n {\"ff93de23\", 8, 585746},\n {\"078ab2e000\", 3, 1579281},\n {\"0fc18aaa00\", 4, 689488},\n {\"1fada8ff00\", 5, 2085964},\n {\"3fa0d08200\", 6, 43103},\n {\"7ffeffc900\", 7, 1212541},\n {\"ff93dea300\", 8, 585746},\n {\"079f8ab260\", 3, 202147110},\n {\"0fa2c18a2a\", 4, 88252593},\n {\"1fd0ada87f\", 5, 266999535},\n {\"3ff9a0d002\", 6, 5509304},\n {\"7f9efeff49\", 7, 155189149},\n {\"ffaa82f404\", 8, 10289705},\n {\"079f8ab2e000\", 3, 202147110},\n {\"0fa2c18aaa00\", 4, 88252593},\n {\"1fd0ada8ff00\", 5, 266999535},\n {\"3ff9a0d08200\", 6, 5509304},\n {\"7f9efeffc900\", 7, 155189149},\n {\"ffaa82f48400\", 8, 10289705},\n {\"0783aa9f8ab260\", 3, 3311978140938},\n {\"0ff0b0a2c18a2a\", 4, 1445930244223},\n {\"1fda84d0ada87f\", 5, 4374519874169},\n {\"3fb5fbf9a0d002\", 6, 90263420404},\n {\"7fcff19efeff49\", 7, 2542616951118},\n {\"ff9fa486bbc327\", 8, 1358138807070},\n {\"07f19883aa9f8ab260\", 3, 54263449861016696},\n {\"0f84fdf0b0a2c18a2a\", 4, 23690121121119891},\n {\"1fa0dfda84d0ada87f\", 5, 71672133617889215},\n {\"3f9ff0b5fbf9a0d002\", 6, 1478875878881374},\n {\"7ffbc1cff19efeff49\", 7, 41658236125045114},\n {\"ff91b6fb85af99c342\", 8, 37450237664484368},\n {\"0794f1f19883aa9f8ab201\", 3, 12832019021693745307u},\n {\"0fa08f84fdf0b0a2c18a01\", 4, 9980690937382242223u},\n {\"1fbfdda0dfda84d0ada801\", 5, 12131360551794650846u},\n {\"3f9dc79ff0b5fbf9a0d001\", 6, 15006530362736632796u},\n {\"7f8790fbc1cff19efeff01\", 7, 18445754019193211014u},\n {\"fffba8c5b8d3fe9f8c8401\", 8, 9518498503615141242u},\n {\"07f8ffffffffffffffff01\", 3, 18446744073709551615u},\n {\"0ff0ffffffffffffffff01\", 4, 18446744073709551615u},\n {\"1fe0ffffffffffffffff01\", 5, 18446744073709551615u},\n {\"3fc0ffffffffffffffff01\", 6, 18446744073709551615u},\n {\"7f80ffffffffffffffff01\", 7, 18446744073709551615u},\n {\"ff80feffffffffffffff01\", 8, 18446744073709551615u},\n {\"0a\", 5, 10},\n {\"1f9a0a\", 5, 1337},\n};\nTEST_P(HpackVarintDecoderTest, Success) {\n for (size_t i = 0; i < ABSL_ARRAYSIZE(kSuccessTestData); ++i) {\n std::string data_bytes;\n ASSERT_TRUE(absl::HexStringToBytes(kSuccessTestData[i].data, &data_bytes));\n DecodeExpectSuccess(data_bytes, kSuccessTestData[i].prefix_length,\n kSuccessTestData[i].expected_value);\n }\n}\nstruct {\n const char* data;\n uint32_t prefix_length;\n} kErrorTestData[] = {\n {\"0780808080808080808080\", 3},\n {\"0f80808080808080808080\", 4},\n {\"1f80808080808080808080\", 5},\n {\"3f80808080808080808080\", 6},\n {\"7f80808080808080808080\", 7},\n {\"ff80808080808080808080\", 8},\n {\"07ffffffffffffffffffff\", 3},\n {\"0fffffffffffffffffffff\", 4},\n {\"1fffffffffffffffffffff\", 5},\n {\"3fffffffffffffffffffff\", 6},\n {\"7fffffffffffffffffffff\", 7},\n {\"ffffffffffffffffffffff\", 8},\n {\"07f9ffffffffffffffff01\", 3},\n {\"0ff1ffffffffffffffff01\", 4},\n {\"1fe1ffffffffffffffff01\", 5},\n {\"3fc1ffffffffffffffff01\", 6},\n {\"7f81ffffffffffffffff01\", 7},\n {\"ff81feffffffffffffff01\", 8},\n {\"07f8ffffffffffffffff8100\", 3},\n {\"0ff0ffffffffffffffff8100\", 4},\n {\"1fe0ffffffffffffffff8100\", 5},\n {\"3fc0ffffffffffffffff8100\", 6},\n {\"7f80ffffffffffffffff8100\", 7},\n {\"ff80feffffffffffffff8100\", 8}};\nTEST_P(HpackVarintDecoderTest, Error) {\n for (size_t i = 0; i < ABSL_ARRAYSIZE(kErrorTestData); ++i) {\n std::string data_bytes;\n ASSERT_TRUE(absl::HexStringToBytes(kErrorTestData[i].data, &data_bytes));\n DecodeExpectError(data_bytes, kErrorTestData[i].prefix_length);\n }\n}\n} \n} \n} "}}},{"rowIdx":446,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_ENCODER_H_\n#define QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_ENCODER_H_\n#include \n#include \n#include \n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nclass QUICHE_EXPORT HpackVarintEncoder {\n public:\n static void Encode(uint8_t high_bits, uint8_t prefix_length, uint64_t varint,\n std::string* output);\n};\n} \n#endif \n#include \"quiche/http2/hpack/varint/hpack_varint_encoder.h\"\n#include \n#include \n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nvoid HpackVarintEncoder::Encode(uint8_t high_bits, uint8_t prefix_length,\n uint64_t varint, std::string* output) {\n QUICHE_DCHECK_LE(1u, prefix_length);\n QUICHE_DCHECK_LE(prefix_length, 8u);\n const uint8_t prefix_mask = (1 << prefix_length) - 1;\n QUICHE_DCHECK_EQ(0, high_bits & prefix_mask);\n if (varint < prefix_mask) {\n unsigned char first_byte = high_bits | static_cast(varint);\n output->push_back(first_byte);\n return;\n }\n unsigned char first_byte = high_bits | prefix_mask;\n output->push_back(first_byte);\n varint -= prefix_mask;\n while (varint >= 128) {\n output->push_back(0b10000000 | (varint % 128));\n varint >>= 7;\n }\n output->push_back(varint);\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/hpack/varint/hpack_varint_encoder.h\"\n#include \n#include \n#include \"absl/base/macros.h\"\n#include \"absl/strings/escaping.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nstruct {\n uint8_t high_bits;\n uint8_t prefix_length;\n uint64_t value;\n uint8_t expected_encoding;\n} kShortTestData[] = {{0b10110010, 1, 0, 0b10110010},\n {0b10101100, 2, 2, 0b10101110},\n {0b10100000, 3, 6, 0b10100110},\n {0b10110000, 4, 13, 0b10111101},\n {0b10100000, 5, 8, 0b10101000},\n {0b11000000, 6, 48, 0b11110000},\n {0b10000000, 7, 99, 0b11100011},\n {0b00000000, 5, 10, 0b00001010}};\nTEST(HpackVarintEncoderTest, Short) {\n for (size_t i = 0; i < ABSL_ARRAYSIZE(kShortTestData); ++i) {\n std::string output;\n HpackVarintEncoder::Encode(kShortTestData[i].high_bits,\n kShortTestData[i].prefix_length,\n kShortTestData[i].value, &output);\n ASSERT_EQ(1u, output.size());\n EXPECT_EQ(kShortTestData[i].expected_encoding,\n static_cast(output[0]));\n }\n}\nstruct {\n uint8_t high_bits;\n uint8_t prefix_length;\n uint64_t value;\n const char* expected_encoding;\n} kLongTestData[] = {\n {0b10011000, 3, 103, \"9f60\"},\n {0b10010000, 4, 57, \"9f2a\"},\n {0b11000000, 5, 158, \"df7f\"},\n {0b01000000, 6, 65, \"7f02\"},\n {0b00000000, 7, 200, \"7f49\"},\n {0b10011000, 3, 12345, \"9fb260\"},\n {0b10010000, 4, 5401, \"9f8a2a\"},\n {0b11000000, 5, 16327, \"dfa87f\"},\n {0b01000000, 6, 399, \"7fd002\"},\n {0b00000000, 7, 9598, \"7fff49\"},\n {0b10011000, 3, 1579281, \"9f8ab260\"},\n {0b10010000, 4, 689488, \"9fc18a2a\"},\n {0b11000000, 5, 2085964, \"dfada87f\"},\n {0b01000000, 6, 43103, \"7fa0d002\"},\n {0b00000000, 7, 1212541, \"7ffeff49\"},\n {0b10011000, 3, 202147110, \"9f9f8ab260\"},\n {0b10010000, 4, 88252593, \"9fa2c18a2a\"},\n {0b11000000, 5, 266999535, \"dfd0ada87f\"},\n {0b01000000, 6, 5509304, \"7ff9a0d002\"},\n {0b00000000, 7, 155189149, \"7f9efeff49\"},\n {0b10011000, 3, 3311978140938, \"9f83aa9f8ab260\"},\n {0b10010000, 4, 1445930244223, \"9ff0b0a2c18a2a\"},\n {0b11000000, 5, 4374519874169, \"dfda84d0ada87f\"},\n {0b01000000, 6, 90263420404, \"7fb5fbf9a0d002\"},\n {0b00000000, 7, 2542616951118, \"7fcff19efeff49\"},\n {0b10011000, 3, 54263449861016696, \"9ff19883aa9f8ab260\"},\n {0b10010000, 4, 23690121121119891, \"9f84fdf0b0a2c18a2a\"},\n {0b11000000, 5, 71672133617889215, \"dfa0dfda84d0ada87f\"},\n {0b01000000, 6, 1478875878881374, \"7f9ff0b5fbf9a0d002\"},\n {0b00000000, 7, 41658236125045114, \"7ffbc1cff19efeff49\"},\n {0b10011000, 3, 12832019021693745307u, \"9f94f1f19883aa9f8ab201\"},\n {0b10010000, 4, 9980690937382242223u, \"9fa08f84fdf0b0a2c18a01\"},\n {0b11000000, 5, 12131360551794650846u, \"dfbfdda0dfda84d0ada801\"},\n {0b01000000, 6, 15006530362736632796u, \"7f9dc79ff0b5fbf9a0d001\"},\n {0b00000000, 7, 18445754019193211014u, \"7f8790fbc1cff19efeff01\"},\n {0b10011000, 3, 18446744073709551615u, \"9ff8ffffffffffffffff01\"},\n {0b10010000, 4, 18446744073709551615u, \"9ff0ffffffffffffffff01\"},\n {0b11000000, 5, 18446744073709551615u, \"dfe0ffffffffffffffff01\"},\n {0b01000000, 6, 18446744073709551615u, \"7fc0ffffffffffffffff01\"},\n {0b00000000, 7, 18446744073709551615u, \"7f80ffffffffffffffff01\"},\n {0b00000000, 5, 1337, \"1f9a0a\"},\n};\nTEST(HpackVarintEncoderTest, Long) {\n for (size_t i = 0; i < ABSL_ARRAYSIZE(kLongTestData); ++i) {\n std::string expected_encoding;\n ASSERT_TRUE(absl::HexStringToBytes(kLongTestData[i].expected_encoding,\n &expected_encoding));\n std::string output;\n HpackVarintEncoder::Encode(kLongTestData[i].high_bits,\n kLongTestData[i].prefix_length,\n kLongTestData[i].value, &output);\n EXPECT_EQ(expected_encoding, output);\n }\n}\nstruct {\n uint8_t high_bits;\n uint8_t prefix_length;\n uint64_t value;\n uint8_t expected_encoding_first_byte;\n} kLastByteIsZeroTestData[] = {\n {0b10110010, 1, 1, 0b10110011}, {0b10101100, 2, 3, 0b10101111},\n {0b10101000, 3, 7, 0b10101111}, {0b10110000, 4, 15, 0b10111111},\n {0b10100000, 5, 31, 0b10111111}, {0b11000000, 6, 63, 0b11111111},\n {0b10000000, 7, 127, 0b11111111}, {0b00000000, 8, 255, 0b11111111}};\nTEST(HpackVarintEncoderTest, LastByteIsZero) {\n for (size_t i = 0; i < ABSL_ARRAYSIZE(kLastByteIsZeroTestData); ++i) {\n std::string output;\n HpackVarintEncoder::Encode(kLastByteIsZeroTestData[i].high_bits,\n kLastByteIsZeroTestData[i].prefix_length,\n kLastByteIsZeroTestData[i].value, &output);\n ASSERT_EQ(2u, output.size());\n EXPECT_EQ(kLastByteIsZeroTestData[i].expected_encoding_first_byte,\n static_cast(output[0]));\n EXPECT_EQ(0b00000000, output[1]);\n }\n}\nTEST(HpackVarintEncoderTest, Append) {\n std::string output(\"foo\");\n std::string expected_encoding;\n ASSERT_TRUE(absl::HexStringToBytes(\"666f6f\", &expected_encoding));\n EXPECT_EQ(expected_encoding, output);\n HpackVarintEncoder::Encode(0b10011000, 3, 103, &output);\n ASSERT_TRUE(absl::HexStringToBytes(\"666f6f9f60\", &expected_encoding));\n EXPECT_EQ(expected_encoding, output);\n HpackVarintEncoder::Encode(0b10100000, 5, 8, &output);\n ASSERT_TRUE(absl::HexStringToBytes(\"666f6f9f60a8\", &expected_encoding));\n EXPECT_EQ(expected_encoding, output);\n HpackVarintEncoder::Encode(0b10011000, 3, 202147110, &output);\n ASSERT_TRUE(\n absl::HexStringToBytes(\"666f6f9f60a89f9f8ab260\", &expected_encoding));\n EXPECT_EQ(expected_encoding, output);\n}\n} \n} \n} "}}},{"rowIdx":447,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_EXAMPLE_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HPACK_EXAMPLE_H_\n#include \n#include \"absl/strings/string_view.h\"\nnamespace http2 {\nnamespace test {\nstd::string HpackExampleToStringOrDie(absl::string_view example);\n} \n} \n#endif \n#include \"quiche/http2/test_tools/hpack_example.h\"\n#include \n#include \n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nvoid HpackExampleToStringOrDie(absl::string_view example, std::string* output) {\n while (!example.empty()) {\n const char c0 = example[0];\n if (isxdigit(c0)) {\n QUICHE_CHECK_GT(example.size(), 1u) << \"Truncated hex byte?\";\n const char c1 = example[1];\n QUICHE_CHECK(isxdigit(c1)) << \"Found half a byte?\";\n std::string byte;\n QUICHE_CHECK(absl::HexStringToBytes(example.substr(0, 2), &byte))\n << \"Can't parse hex byte\";\n absl::StrAppend(output, byte);\n example.remove_prefix(2);\n continue;\n }\n if (isspace(c0)) {\n example.remove_prefix(1);\n continue;\n }\n if (!example.empty() && example[0] == '|') {\n auto pos = example.find('\\n');\n if (pos == absl::string_view::npos) {\n break;\n }\n example.remove_prefix(pos + 1);\n continue;\n }\n QUICHE_BUG(http2_bug_107_1)\n << \"Can't parse byte \" << static_cast(c0)\n << absl::StrCat(\" (0x\", absl::Hex(c0), \")\") << \"\\nExample: \" << example;\n }\n QUICHE_CHECK_LT(0u, output->size()) << \"Example is empty.\";\n}\n} \nstd::string HpackExampleToStringOrDie(absl::string_view example) {\n std::string output;\n HpackExampleToStringOrDie(example, &output);\n return output;\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/hpack_example.h\"\n#include \n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(HpackExampleToStringOrDie, GoodInput) {\n std::string bytes = HpackExampleToStringOrDie(R\"(\n 40 | == Literal never indexed ==\n | Blank lines are OK in example:\n 08 | Literal name (len = 8)\n 7061 7373 776f 7264 | password\n 06 | Literal value (len = 6)\n 7365 6372 6574 | secret\n | -> password: secret\n )\");\n const char kExpected[] = {\n 0x40, \n 0x08, \n 0x70, 0x61, 0x73, 0x73, \n 0x77, 0x6f, 0x72, 0x64, \n 0x06, \n 0x73, 0x65, 0x63, 0x72, \n 0x65, 0x74, \n };\n EXPECT_EQ(absl::string_view(kExpected, sizeof kExpected), bytes);\n}\n#ifdef GTEST_HAS_DEATH_TEST\nTEST(HpackExampleToStringOrDie, InvalidInput) {\n EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie(\"4\"), \"Truncated\");\n EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie(\"4x\"), \"half\");\n EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie(\"\"), \"empty\");\n}\n#endif\n} \n} \n} "}}},{"rowIdx":448,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_COLLECTOR_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_COLLECTOR_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_entry_collector.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass QUICHE_NO_EXPORT HpackBlockCollector : public HpackEntryDecoderListener {\n public:\n HpackBlockCollector();\n HpackBlockCollector(const HpackBlockCollector& other);\n ~HpackBlockCollector() override;\n void OnIndexedHeader(size_t index) override;\n void OnDynamicTableSizeUpdate(size_t size) override;\n void OnStartLiteralHeader(HpackEntryType header_type,\n size_t maybe_name_index) override;\n void OnNameStart(bool huffman_encoded, size_t len) override;\n void OnNameData(const char* data, size_t len) override;\n void OnNameEnd() override;\n void OnValueStart(bool huffman_encoded, size_t len) override;\n void OnValueData(const char* data, size_t len) override;\n void OnValueEnd() override;\n void ExpectIndexedHeader(size_t index);\n void ExpectDynamicTableSizeUpdate(size_t size);\n void ExpectNameIndexAndLiteralValue(HpackEntryType type, size_t index,\n bool value_huffman,\n const std::string& value);\n void ExpectLiteralNameAndValue(HpackEntryType type, bool name_huffman,\n const std::string& name, bool value_huffman,\n const std::string& value);\n void ShuffleEntries(Http2Random* rng);\n void AppendToHpackBlockBuilder(HpackBlockBuilder* hbb) const;\n ::testing::AssertionResult ValidateSoleIndexedHeader(size_t ndx) const;\n ::testing::AssertionResult ValidateSoleDynamicTableSizeUpdate(\n size_t size) const;\n ::testing::AssertionResult ValidateSoleLiteralValueHeader(\n HpackEntryType expected_type, size_t expected_index,\n bool expected_value_huffman, absl::string_view expected_value) const;\n ::testing::AssertionResult ValidateSoleLiteralNameValueHeader(\n HpackEntryType expected_type, bool expected_name_huffman,\n absl::string_view expected_name, bool expected_value_huffman,\n absl::string_view expected_value) const;\n bool IsNotPending() const { return pending_entry_.IsClear(); }\n bool IsClear() const { return IsNotPending() && entries_.empty(); }\n void Clear();\n ::testing::AssertionResult VerifyEq(const HpackBlockCollector& that) const;\n private:\n void PushPendingEntry();\n HpackEntryCollector pending_entry_;\n std::vector entries_;\n};\n} \n} \n#endif \n#include \"quiche/http2/test_tools/hpack_block_collector.h\"\n#include \n#include \n#include \n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nusing ::testing::AssertionResult;\nusing ::testing::AssertionSuccess;\nnamespace http2 {\nnamespace test {\nHpackBlockCollector::HpackBlockCollector() = default;\nHpackBlockCollector::HpackBlockCollector(const HpackBlockCollector& other)\n : pending_entry_(other.pending_entry_), entries_(other.entries_) {}\nHpackBlockCollector::~HpackBlockCollector() = default;\nvoid HpackBlockCollector::OnIndexedHeader(size_t index) {\n pending_entry_.OnIndexedHeader(index);\n PushPendingEntry();\n}\nvoid HpackBlockCollector::OnDynamicTableSizeUpdate(size_t size) {\n pending_entry_.OnDynamicTableSizeUpdate(size);\n PushPendingEntry();\n}\nvoid HpackBlockCollector::OnStartLiteralHeader(HpackEntryType header_type,\n size_t maybe_name_index) {\n pending_entry_.OnStartLiteralHeader(header_type, maybe_name_index);\n}\nvoid HpackBlockCollector::OnNameStart(bool huffman_encoded, size_t len) {\n pending_entry_.OnNameStart(huffman_encoded, len);\n}\nvoid HpackBlockCollector::OnNameData(const char* data, size_t len) {\n pending_entry_.OnNameData(data, len);\n}\nvoid HpackBlockCollector::OnNameEnd() { pending_entry_.OnNameEnd(); }\nvoid HpackBlockCollector::OnValueStart(bool huffman_encoded, size_t len) {\n pending_entry_.OnValueStart(huffman_encoded, len);\n}\nvoid HpackBlockCollector::OnValueData(const char* data, size_t len) {\n pending_entry_.OnValueData(data, len);\n}\nvoid HpackBlockCollector::OnValueEnd() {\n pending_entry_.OnValueEnd();\n PushPendingEntry();\n}\nvoid HpackBlockCollector::PushPendingEntry() {\n EXPECT_TRUE(pending_entry_.IsComplete());\n QUICHE_DVLOG(2) << \"PushPendingEntry: \" << pending_entry_;\n entries_.push_back(pending_entry_);\n EXPECT_TRUE(entries_.back().IsComplete());\n pending_entry_.Clear();\n}\nvoid HpackBlockCollector::Clear() {\n pending_entry_.Clear();\n entries_.clear();\n}\nvoid HpackBlockCollector::ExpectIndexedHeader(size_t index) {\n entries_.push_back(\n HpackEntryCollector(HpackEntryType::kIndexedHeader, index));\n}\nvoid HpackBlockCollector::ExpectDynamicTableSizeUpdate(size_t size) {\n entries_.push_back(\n HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, size));\n}\nvoid HpackBlockCollector::ExpectNameIndexAndLiteralValue(\n HpackEntryType type, size_t index, bool value_huffman,\n const std::string& value) {\n entries_.push_back(HpackEntryCollector(type, index, value_huffman, value));\n}\nvoid HpackBlockCollector::ExpectLiteralNameAndValue(HpackEntryType type,\n bool name_huffman,\n const std::string& name,\n bool value_huffman,\n const std::string& value) {\n entries_.push_back(\n HpackEntryCollector(type, name_huffman, name, value_huffman, value));\n}\nvoid HpackBlockCollector::ShuffleEntries(Http2Random* rng) {\n std::shuffle(entries_.begin(), entries_.end(), *rng);\n}\nvoid HpackBlockCollector::AppendToHpackBlockBuilder(\n HpackBlockBuilder* hbb) const {\n QUICHE_CHECK(IsNotPending());\n for (const auto& entry : entries_) {\n entry.AppendToHpackBlockBuilder(hbb);\n }\n}\nAssertionResult HpackBlockCollector::ValidateSoleIndexedHeader(\n size_t ndx) const {\n HTTP2_VERIFY_TRUE(pending_entry_.IsClear());\n HTTP2_VERIFY_EQ(1u, entries_.size());\n HTTP2_VERIFY_TRUE(entries_.front().ValidateIndexedHeader(ndx));\n return AssertionSuccess();\n}\nAssertionResult HpackBlockCollector::ValidateSoleLiteralValueHeader(\n HpackEntryType expected_type, size_t expected_index,\n bool expected_value_huffman, absl::string_view expected_value) const {\n HTTP2_VERIFY_TRUE(pending_entry_.IsClear());\n HTTP2_VERIFY_EQ(1u, entries_.size());\n HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralValueHeader(\n expected_type, expected_index, expected_value_huffman, expected_value));\n return AssertionSuccess();\n}\nAssertionResult HpackBlockCollector::ValidateSoleLiteralNameValueHeader(\n HpackEntryType expected_type, bool expected_name_huffman,\n absl::string_view expected_name, bool expected_value_huffman,\n absl::string_view expected_value) const {\n HTTP2_VERIFY_TRUE(pending_entry_.IsClear());\n HTTP2_VERIFY_EQ(1u, entries_.size());\n HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralNameValueHeader(\n expected_type, expected_name_huffman, expected_name,\n expected_value_huffman, expected_value));\n return AssertionSuccess();\n}\nAssertionResult HpackBlockCollector::ValidateSoleDynamicTableSizeUpdate(\n size_t size) const {\n HTTP2_VERIFY_TRUE(pending_entry_.IsClear());\n HTTP2_VERIFY_EQ(1u, entries_.size());\n HTTP2_VERIFY_TRUE(entries_.front().ValidateDynamicTableSizeUpdate(size));\n return AssertionSuccess();\n}\nAssertionResult HpackBlockCollector::VerifyEq(\n const HpackBlockCollector& that) const {\n HTTP2_VERIFY_EQ(pending_entry_, that.pending_entry_);\n HTTP2_VERIFY_EQ(entries_, that.entries_);\n return AssertionSuccess();\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/hpack_block_collector.h\"\n#include \n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(HpackBlockCollectorTest, Clear) {\n HpackBlockCollector collector;\n EXPECT_TRUE(collector.IsClear());\n EXPECT_TRUE(collector.IsNotPending());\n collector.OnIndexedHeader(234);\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsNotPending());\n collector.Clear();\n EXPECT_TRUE(collector.IsClear());\n EXPECT_TRUE(collector.IsNotPending());\n collector.OnDynamicTableSizeUpdate(0);\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsNotPending());\n collector.Clear();\n collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);\n EXPECT_FALSE(collector.IsClear());\n EXPECT_FALSE(collector.IsNotPending());\n}\nTEST(HpackBlockCollectorTest, IndexedHeader) {\n HpackBlockCollector a;\n a.OnIndexedHeader(123);\n EXPECT_TRUE(a.ValidateSoleIndexedHeader(123));\n HpackBlockCollector b;\n EXPECT_FALSE(a.VerifyEq(b));\n b.OnIndexedHeader(1);\n EXPECT_TRUE(b.ValidateSoleIndexedHeader(1));\n EXPECT_FALSE(a.VerifyEq(b));\n b.Clear();\n b.OnIndexedHeader(123);\n EXPECT_TRUE(a.VerifyEq(b));\n b.OnIndexedHeader(234);\n EXPECT_FALSE(b.VerifyEq(a));\n a.OnIndexedHeader(234);\n EXPECT_TRUE(b.VerifyEq(a));\n std::string expected;\n {\n HpackBlockBuilder hbb;\n hbb.AppendIndexedHeader(123);\n hbb.AppendIndexedHeader(234);\n EXPECT_EQ(3u, hbb.size());\n expected = hbb.buffer();\n }\n std::string actual;\n {\n HpackBlockBuilder hbb;\n a.AppendToHpackBlockBuilder(&hbb);\n EXPECT_EQ(3u, hbb.size());\n actual = hbb.buffer();\n }\n EXPECT_EQ(expected, actual);\n}\nTEST(HpackBlockCollectorTest, DynamicTableSizeUpdate) {\n HpackBlockCollector a;\n a.OnDynamicTableSizeUpdate(0);\n EXPECT_TRUE(a.ValidateSoleDynamicTableSizeUpdate(0));\n HpackBlockCollector b;\n EXPECT_FALSE(a.VerifyEq(b));\n b.OnDynamicTableSizeUpdate(1);\n EXPECT_TRUE(b.ValidateSoleDynamicTableSizeUpdate(1));\n EXPECT_FALSE(a.VerifyEq(b));\n b.Clear();\n b.OnDynamicTableSizeUpdate(0);\n EXPECT_TRUE(a.VerifyEq(b));\n b.OnDynamicTableSizeUpdate(4096);\n EXPECT_FALSE(b.VerifyEq(a));\n a.OnDynamicTableSizeUpdate(4096);\n EXPECT_TRUE(b.VerifyEq(a));\n std::string expected;\n {\n HpackBlockBuilder hbb;\n hbb.AppendDynamicTableSizeUpdate(0);\n hbb.AppendDynamicTableSizeUpdate(4096);\n EXPECT_EQ(4u, hbb.size());\n expected = hbb.buffer();\n }\n std::string actual;\n {\n HpackBlockBuilder hbb;\n a.AppendToHpackBlockBuilder(&hbb);\n EXPECT_EQ(4u, hbb.size());\n actual = hbb.buffer();\n }\n EXPECT_EQ(expected, actual);\n}\n} \n} \n} "}}},{"rowIdx":449,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HTTP2_RANDOM_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HTTP2_RANDOM_H_\n#include \n#include \n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass QUICHE_NO_EXPORT Http2Random {\n public:\n Http2Random();\n Http2Random(const Http2Random&) = delete;\n Http2Random& operator=(const Http2Random&) = delete;\n explicit Http2Random(absl::string_view key);\n std::string Key() const;\n void FillRandom(void* buffer, size_t buffer_size);\n std::string RandString(int length);\n uint64_t Rand64();\n uint32_t Uniform(uint32_t n) { return Rand64() % n; }\n uint64_t UniformInRange(uint64_t lo, uint64_t hi) {\n return lo + Rand64() % (hi - lo);\n }\n uint32_t Skewed(uint32_t max_log) {\n const uint32_t base = Rand32() % (max_log + 1);\n const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u;\n return Rand32() & mask;\n }\n uint64_t RandomSizeSkewedLow(uint64_t max) {\n return std::round(max * std::pow(RandDouble(), 2));\n }\n double RandDouble();\n float RandFloat() { return RandDouble(); }\n bool OneIn(int n) { return Uniform(n) == 0; }\n uint8_t Rand8() { return Rand64(); }\n uint16_t Rand16() { return Rand64(); }\n uint32_t Rand32() { return Rand64(); }\n std::string RandStringWithAlphabet(int length, absl::string_view alphabet);\n using result_type = uint64_t;\n static constexpr result_type min() { return 0; }\n static constexpr result_type max() {\n return std::numeric_limits::max();\n }\n result_type operator()() { return Rand64(); }\n private:\n uint8_t key_[32];\n uint32_t counter_ = 0;\n};\n} \n} \n#endif \n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \n#include \"absl/strings/escaping.h\"\n#include \"openssl/chacha.h\"\n#include \"openssl/rand.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nstatic const uint8_t kZeroNonce[12] = {0};\nnamespace http2 {\nnamespace test {\nHttp2Random::Http2Random() {\n RAND_bytes(key_, sizeof(key_));\n QUICHE_LOG(INFO) << \"Initialized test RNG with the following key: \" << Key();\n}\nHttp2Random::Http2Random(absl::string_view key) {\n std::string decoded_key = absl::HexStringToBytes(key);\n QUICHE_CHECK_EQ(sizeof(key_), decoded_key.size());\n memcpy(key_, decoded_key.data(), sizeof(key_));\n}\nstd::string Http2Random::Key() const {\n return absl::BytesToHexString(\n absl::string_view(reinterpret_cast(key_), sizeof(key_)));\n}\nvoid Http2Random::FillRandom(void* buffer, size_t buffer_size) {\n memset(buffer, 0, buffer_size);\n uint8_t* buffer_u8 = reinterpret_cast(buffer);\n CRYPTO_chacha_20(buffer_u8, buffer_u8, buffer_size, key_, kZeroNonce,\n counter_++);\n}\nstd::string Http2Random::RandString(int length) {\n std::string result;\n result.resize(length);\n FillRandom(&result[0], length);\n return result;\n}\nuint64_t Http2Random::Rand64() {\n union {\n uint64_t number;\n uint8_t bytes[sizeof(uint64_t)];\n } result;\n FillRandom(result.bytes, sizeof(result.bytes));\n return result.number;\n}\ndouble Http2Random::RandDouble() {\n union {\n double f;\n uint64_t i;\n } value;\n value.i = (1023ull << 52ull) | (Rand64() & 0xfffffffffffffu);\n return value.f - 1.0;\n}\nstd::string Http2Random::RandStringWithAlphabet(int length,\n absl::string_view alphabet) {\n std::string result;\n result.resize(length);\n for (int i = 0; i < length; i++) {\n result[i] = alphabet[Uniform(alphabet.size())];\n }\n return result;\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/http2_random.h\"\n#include \n#include \n#include \n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(Http2RandomTest, ProducesDifferentNumbers) {\n Http2Random random;\n uint64_t value1 = random.Rand64();\n uint64_t value2 = random.Rand64();\n uint64_t value3 = random.Rand64();\n EXPECT_NE(value1, value2);\n EXPECT_NE(value2, value3);\n EXPECT_NE(value3, value1);\n}\nTEST(Http2RandomTest, StartsWithDifferentKeys) {\n Http2Random random1;\n Http2Random random2;\n EXPECT_NE(random1.Key(), random2.Key());\n EXPECT_NE(random1.Rand64(), random2.Rand64());\n EXPECT_NE(random1.Rand64(), random2.Rand64());\n EXPECT_NE(random1.Rand64(), random2.Rand64());\n}\nTEST(Http2RandomTest, ReproducibleRandom) {\n Http2Random random;\n uint64_t value1 = random.Rand64();\n uint64_t value2 = random.Rand64();\n Http2Random clone_random(random.Key());\n EXPECT_EQ(clone_random.Key(), random.Key());\n EXPECT_EQ(value1, clone_random.Rand64());\n EXPECT_EQ(value2, clone_random.Rand64());\n}\nTEST(Http2RandomTest, STLShuffle) {\n Http2Random random;\n const std::string original = \"abcdefghijklmonpqrsuvwxyz\";\n std::string shuffled = original;\n std::shuffle(shuffled.begin(), shuffled.end(), random);\n EXPECT_NE(original, shuffled);\n}\nTEST(Http2RandomTest, RandFloat) {\n Http2Random random;\n for (int i = 0; i < 10000; i++) {\n float value = random.RandFloat();\n ASSERT_GE(value, 0.f);\n ASSERT_LE(value, 1.f);\n }\n}\nTEST(Http2RandomTest, RandStringWithAlphabet) {\n Http2Random random;\n std::string str = random.RandStringWithAlphabet(1000, \"xyz\");\n EXPECT_EQ(1000u, str.size());\n std::set characters(str.begin(), str.end());\n EXPECT_THAT(characters, testing::ElementsAre('x', 'y', 'z'));\n}\nTEST(Http2RandomTest, SkewedLow) {\n Http2Random random;\n constexpr size_t kMax = 1234;\n for (int i = 0; i < 10000; i++) {\n size_t value = random.RandomSizeSkewedLow(kMax);\n ASSERT_GE(value, 0u);\n ASSERT_LE(value, kMax);\n }\n}\nTEST(Http2RandomTest, SkewedLowFullRange) {\n Http2Random random;\n std::set values;\n for (int i = 0; i < 1000; i++) {\n values.insert(random.RandomSizeSkewedLow(3));\n }\n EXPECT_THAT(values, testing::ElementsAre(0, 1, 2, 3));\n}\n} \n} \n} "}}},{"rowIdx":450,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_ENTRY_COLLECTOR_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HPACK_ENTRY_COLLECTOR_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/test_tools/hpack_string_collector.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass QUICHE_NO_EXPORT HpackEntryCollector : public HpackEntryDecoderListener {\n public:\n HpackEntryCollector();\n HpackEntryCollector(const HpackEntryCollector& other);\n HpackEntryCollector(HpackEntryType type, size_t index_or_size);\n HpackEntryCollector(HpackEntryType type, size_t index, bool value_huffman,\n const std::string& value);\n HpackEntryCollector(HpackEntryType type, bool name_huffman,\n const std::string& name, bool value_huffman,\n const std::string& value);\n ~HpackEntryCollector() override;\n void OnIndexedHeader(size_t index) override;\n void OnStartLiteralHeader(HpackEntryType header_type,\n size_t maybe_name_index) override;\n void OnNameStart(bool huffman_encoded, size_t len) override;\n void OnNameData(const char* data, size_t len) override;\n void OnNameEnd() override;\n void OnValueStart(bool huffman_encoded, size_t len) override;\n void OnValueData(const char* data, size_t len) override;\n void OnValueEnd() override;\n void OnDynamicTableSizeUpdate(size_t size) override;\n void Clear();\n bool IsClear() const;\n bool IsComplete() const;\n bool LiteralNameExpected() const;\n bool LiteralValueExpected() const;\n ::testing::AssertionResult ValidateIndexedHeader(size_t expected_index) const;\n ::testing::AssertionResult ValidateLiteralValueHeader(\n HpackEntryType expected_type, size_t expected_index,\n bool expected_value_huffman, absl::string_view expected_value) const;\n ::testing::AssertionResult ValidateLiteralNameValueHeader(\n HpackEntryType expected_type, bool expected_name_huffman,\n absl::string_view expected_name, bool expected_value_huffman,\n absl::string_view expected_value) const;\n ::testing::AssertionResult ValidateDynamicTableSizeUpdate(\n size_t expected_size) const;\n void set_header_type(HpackEntryType v) { header_type_ = v; }\n HpackEntryType header_type() const { return header_type_; }\n void set_index(size_t v) { index_ = v; }\n size_t index() const { return index_; }\n void set_name(const HpackStringCollector& v) { name_ = v; }\n const HpackStringCollector& name() const { return name_; }\n void set_value(const HpackStringCollector& v) { value_ = v; }\n const HpackStringCollector& value() const { return value_; }\n void set_started(bool v) { started_ = v; }\n bool started() const { return started_; }\n void set_ended(bool v) { ended_ = v; }\n bool ended() const { return ended_; }\n void AppendToHpackBlockBuilder(HpackBlockBuilder* hbb) const;\n std::string ToString() const;\n private:\n void Init(HpackEntryType type, size_t maybe_index);\n HpackEntryType header_type_;\n size_t index_;\n HpackStringCollector name_;\n HpackStringCollector value_;\n bool started_ = false;\n bool ended_ = false;\n};\nQUICHE_NO_EXPORT bool operator==(const HpackEntryCollector& a,\n const HpackEntryCollector& b);\nQUICHE_NO_EXPORT bool operator!=(const HpackEntryCollector& a,\n const HpackEntryCollector& b);\nQUICHE_NO_EXPORT std::ostream& operator<<(std::ostream& out,\n const HpackEntryCollector& v);\n} \n} \n#endif \n#include \"quiche/http2/test_tools/hpack_entry_collector.h\"\n#include \n#include \n#include \"absl/strings/str_cat.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/http2/test_tools/hpack_string_collector.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nnamespace http2 {\nnamespace test {\nnamespace {\nconst HpackEntryType kInvalidHeaderType = static_cast(99);\nconst size_t kInvalidIndex = 99999999;\n} \nHpackEntryCollector::HpackEntryCollector() { Clear(); }\nHpackEntryCollector::HpackEntryCollector(const HpackEntryCollector& other) =\n default;\nHpackEntryCollector::HpackEntryCollector(HpackEntryType type,\n size_t index_or_size)\n : header_type_(type), index_(index_or_size), started_(true), ended_(true) {}\nHpackEntryCollector::HpackEntryCollector(HpackEntryType type, size_t index,\n bool value_huffman,\n const std::string& value)\n : header_type_(type),\n index_(index),\n value_(value, value_huffman),\n started_(true),\n ended_(true) {}\nHpackEntryCollector::HpackEntryCollector(HpackEntryType type, bool name_huffman,\n const std::string& name,\n bool value_huffman,\n const std::string& value)\n : header_type_(type),\n index_(0),\n name_(name, name_huffman),\n value_(value, value_huffman),\n started_(true),\n ended_(true) {}\nHpackEntryCollector::~HpackEntryCollector() = default;\nvoid HpackEntryCollector::OnIndexedHeader(size_t index) {\n ASSERT_FALSE(started_);\n ASSERT_TRUE(IsClear()) << ToString();\n Init(HpackEntryType::kIndexedHeader, index);\n ended_ = true;\n}\nvoid HpackEntryCollector::OnStartLiteralHeader(HpackEntryType header_type,\n size_t maybe_name_index) {\n ASSERT_FALSE(started_);\n ASSERT_TRUE(IsClear()) << ToString();\n Init(header_type, maybe_name_index);\n}\nvoid HpackEntryCollector::OnNameStart(bool huffman_encoded, size_t len) {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n ASSERT_FALSE(IsClear());\n ASSERT_TRUE(LiteralNameExpected()) << ToString();\n name_.OnStringStart(huffman_encoded, len);\n}\nvoid HpackEntryCollector::OnNameData(const char* data, size_t len) {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n ASSERT_TRUE(LiteralNameExpected()) << ToString();\n ASSERT_TRUE(name_.IsInProgress());\n name_.OnStringData(data, len);\n}\nvoid HpackEntryCollector::OnNameEnd() {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n ASSERT_TRUE(LiteralNameExpected()) << ToString();\n ASSERT_TRUE(name_.IsInProgress());\n name_.OnStringEnd();\n}\nvoid HpackEntryCollector::OnValueStart(bool huffman_encoded, size_t len) {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n if (LiteralNameExpected()) {\n ASSERT_TRUE(name_.HasEnded());\n }\n ASSERT_TRUE(LiteralValueExpected()) << ToString();\n ASSERT_TRUE(value_.IsClear()) << value_.ToString();\n value_.OnStringStart(huffman_encoded, len);\n}\nvoid HpackEntryCollector::OnValueData(const char* data, size_t len) {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n ASSERT_TRUE(LiteralValueExpected()) << ToString();\n ASSERT_TRUE(value_.IsInProgress());\n value_.OnStringData(data, len);\n}\nvoid HpackEntryCollector::OnValueEnd() {\n ASSERT_TRUE(started_);\n ASSERT_FALSE(ended_);\n ASSERT_TRUE(LiteralValueExpected()) << ToString();\n ASSERT_TRUE(value_.IsInProgress());\n value_.OnStringEnd();\n ended_ = true;\n}\nvoid HpackEntryCollector::OnDynamicTableSizeUpdate(size_t size) {\n ASSERT_FALSE(started_);\n ASSERT_TRUE(IsClear()) << ToString();\n Init(HpackEntryType::kDynamicTableSizeUpdate, size);\n ended_ = true;\n}\nvoid HpackEntryCollector::Clear() {\n header_type_ = kInvalidHeaderType;\n index_ = kInvalidIndex;\n name_.Clear();\n value_.Clear();\n started_ = ended_ = false;\n}\nbool HpackEntryCollector::IsClear() const {\n return header_type_ == kInvalidHeaderType && index_ == kInvalidIndex &&\n name_.IsClear() && value_.IsClear() && !started_ && !ended_;\n}\nbool HpackEntryCollector::IsComplete() const { return started_ && ended_; }\nbool HpackEntryCollector::LiteralNameExpected() const {\n switch (header_type_) {\n case HpackEntryType::kIndexedLiteralHeader:\n case HpackEntryType::kUnindexedLiteralHeader:\n case HpackEntryType::kNeverIndexedLiteralHeader:\n return index_ == 0;\n default:\n return false;\n }\n}\nbool HpackEntryCollector::LiteralValueExpected() const {\n switch (header_type_) {\n case HpackEntryType::kIndexedLiteralHeader:\n case HpackEntryType::kUnindexedLiteralHeader:\n case HpackEntryType::kNeverIndexedLiteralHeader:\n return true;\n default:\n return false;\n }\n}\nAssertionResult HpackEntryCollector::ValidateIndexedHeader(\n size_t expected_index) const {\n HTTP2_VERIFY_TRUE(started_);\n HTTP2_VERIFY_TRUE(ended_);\n HTTP2_VERIFY_EQ(HpackEntryType::kIndexedHeader, header_type_);\n HTTP2_VERIFY_EQ(expected_index, index_);\n return ::testing::AssertionSuccess();\n}\nAssertionResult HpackEntryCollector::ValidateLiteralValueHeader(\n HpackEntryType expected_type, size_t expected_index,\n bool expected_value_huffman, absl::string_view expected_value) const {\n HTTP2_VERIFY_TRUE(started_);\n HTTP2_VERIFY_TRUE(ended_);\n HTTP2_VERIFY_EQ(expected_type, header_type_);\n HTTP2_VERIFY_NE(0u, expected_index);\n HTTP2_VERIFY_EQ(expected_index, index_);\n HTTP2_VERIFY_TRUE(name_.IsClear());\n HTTP2_VERIFY_SUCCESS(\n value_.Collected(expected_value, expected_value_huffman));\n return ::testing::AssertionSuccess();\n}\nAssertionResult HpackEntryCollector::ValidateLiteralNameValueHeader(\n HpackEntryType expected_type, bool expected_name_huffman,\n absl::string_view expected_name, bool expected_value_huffman,\n absl::string_view expected_value) const {\n HTTP2_VERIFY_TRUE(started_);\n HTTP2_VERIFY_TRUE(ended_);\n HTTP2_VERIFY_EQ(expected_type, header_type_);\n HTTP2_VERIFY_EQ(0u, index_);\n HTTP2_VERIFY_SUCCESS(name_.Collected(expected_name, expected_name_huffman));\n HTTP2_VERIFY_SUCCESS(\n value_.Collected(expected_value, expected_value_huffman));\n return ::testing::AssertionSuccess();\n}\nAssertionResult HpackEntryCollector::ValidateDynamicTableSizeUpdate(\n size_t size) const {\n HTTP2_VERIFY_TRUE(started_);\n HTTP2_VERIFY_TRUE(ended_);\n HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate, header_type_);\n HTTP2_VERIFY_EQ(index_, size);\n return ::testing::AssertionSuccess();\n}\nvoid HpackEntryCollector::AppendToHpackBlockBuilder(\n HpackBlockBuilder* hbb) const {\n ASSERT_TRUE(started_ && ended_) << *this;\n switch (header_type_) {\n case HpackEntryType::kIndexedHeader:\n hbb->AppendIndexedHeader(index_);\n return;\n case HpackEntryType::kDynamicTableSizeUpdate:\n hbb->AppendDynamicTableSizeUpdate(index_);\n return;\n case HpackEntryType::kIndexedLiteralHeader:\n case HpackEntryType::kUnindexedLiteralHeader:\n case HpackEntryType::kNeverIndexedLiteralHeader:\n ASSERT_TRUE(value_.HasEnded()) << *this;\n if (index_ != 0) {\n QUICHE_CHECK(name_.IsClear());\n hbb->AppendNameIndexAndLiteralValue(header_type_, index_,\n value_.huffman_encoded, value_.s);\n } else {\n QUICHE_CHECK(name_.HasEnded()) << *this;\n hbb->AppendLiteralNameAndValue(header_type_, name_.huffman_encoded,\n name_.s, value_.huffman_encoded,\n value_.s);\n }\n return;\n default:\n ADD_FAILURE() << *this;\n }\n}\nstd::string HpackEntryCollector::ToString() const {\n std::string result(\"Type=\");\n switch (header_type_) {\n case HpackEntryType::kIndexedHeader:\n result += \"IndexedHeader\";\n break;\n case HpackEntryType::kDynamicTableSizeUpdate:\n result += \"DynamicTableSizeUpdate\";\n break;\n case HpackEntryType::kIndexedLiteralHeader:\n result += \"IndexedLiteralHeader\";\n break;\n case HpackEntryType::kUnindexedLiteralHeader:\n result += \"UnindexedLiteralHeader\";\n break;\n case HpackEntryType::kNeverIndexedLiteralHeader:\n result += \"NeverIndexedLiteralHeader\";\n break;\n default:\n if (header_type_ == kInvalidHeaderType) {\n result += \"\";\n } else {\n absl::StrAppend(&result, header_type_);\n }\n }\n if (index_ != 0) {\n absl::StrAppend(&result, \" Index=\", index_);\n }\n if (!name_.IsClear()) {\n absl::StrAppend(&result, \" Name\", name_.ToString());\n }\n if (!value_.IsClear()) {\n absl::StrAppend(&result, \" Value\", value_.ToString());\n }\n if (!started_) {\n EXPECT_FALSE(ended_);\n absl::StrAppend(&result, \" !started\");\n } else if (!ended_) {\n absl::StrAppend(&result, \" !ended\");\n } else {\n absl::StrAppend(&result, \" Complete\");\n }\n return result;\n}\nvoid HpackEntryCollector::Init(HpackEntryType type, size_t maybe_index) {\n ASSERT_TRUE(IsClear()) << ToString();\n header_type_ = type;\n index_ = maybe_index;\n started_ = true;\n}\nbool operator==(const HpackEntryCollector& a, const HpackEntryCollector& b) {\n return a.name() == b.name() && a.value() == b.value() &&\n a.index() == b.index() && a.header_type() == b.header_type() &&\n a.started() == b.started() && a.ended() == b.ended();\n}\nbool operator!=(const HpackEntryCollector& a, const HpackEntryCollector& b) {\n return !(a == b);\n}\nstd::ostream& operator<<(std::ostream& out, const HpackEntryCollector& v) {\n return out << v.ToString();\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/hpack_entry_collector.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::HasSubstr;\nnamespace http2 {\nnamespace test {\nnamespace {\nTEST(HpackEntryCollectorTest, Clear) {\n HpackEntryCollector collector;\n QUICHE_VLOG(1) << collector;\n EXPECT_THAT(collector.ToString(), HasSubstr(\"!started\"));\n EXPECT_TRUE(collector.IsClear());\n collector.set_header_type(HpackEntryType::kIndexedLiteralHeader);\n EXPECT_FALSE(collector.IsClear());\n QUICHE_VLOG(1) << collector;\n collector.Clear();\n EXPECT_TRUE(collector.IsClear());\n collector.set_index(123);\n EXPECT_FALSE(collector.IsClear());\n QUICHE_VLOG(1) << collector;\n collector.Clear();\n EXPECT_TRUE(collector.IsClear());\n collector.set_name(HpackStringCollector(\"name\", true));\n EXPECT_FALSE(collector.IsClear());\n QUICHE_VLOG(1) << collector;\n collector.Clear();\n EXPECT_TRUE(collector.IsClear());\n collector.set_value(HpackStringCollector(\"value\", false));\n EXPECT_FALSE(collector.IsClear());\n QUICHE_VLOG(1) << collector;\n}\nvoid IndexedHeaderErrorTest() {\n HpackEntryCollector collector;\n collector.OnIndexedHeader(1);\n collector.OnIndexedHeader(234);\n}\nTEST(HpackEntryCollectorTest, IndexedHeader) {\n HpackEntryCollector collector;\n collector.OnIndexedHeader(123);\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsComplete());\n EXPECT_TRUE(collector.ValidateIndexedHeader(123));\n EXPECT_THAT(collector.ToString(), HasSubstr(\"IndexedHeader\"));\n EXPECT_THAT(collector.ToString(), HasSubstr(\"Complete\"));\n EXPECT_FATAL_FAILURE(IndexedHeaderErrorTest(), \"Value of: started_\");\n}\nvoid LiteralValueErrorTest() {\n HpackEntryCollector collector;\n collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);\n collector.OnNameStart(false, 10);\n}\nTEST(HpackEntryCollectorTest, LiteralValueHeader) {\n HpackEntryCollector collector;\n collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 4);\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_FALSE(collector.IsComplete());\n EXPECT_THAT(collector.ToString(), HasSubstr(\"!ended\"));\n collector.OnValueStart(true, 5);\n QUICHE_VLOG(1) << collector;\n collector.OnValueData(\"value\", 5);\n collector.OnValueEnd();\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsComplete());\n EXPECT_TRUE(collector.ValidateLiteralValueHeader(\n HpackEntryType::kIndexedLiteralHeader, 4, true, \"value\"));\n EXPECT_THAT(collector.ToString(), HasSubstr(\"IndexedLiteralHeader\"));\n EXPECT_THAT(collector.ToString(), HasSubstr(\"Complete\"));\n EXPECT_FATAL_FAILURE(LiteralValueErrorTest(),\n \"Value of: LiteralNameExpected\");\n}\nvoid LiteralNameValueHeaderErrorTest() {\n HpackEntryCollector collector;\n collector.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader, 0);\n collector.OnValueStart(false, 10);\n}\nTEST(HpackEntryCollectorTest, LiteralNameValueHeader) {\n HpackEntryCollector collector;\n collector.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader, 0);\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_FALSE(collector.IsComplete());\n collector.OnNameStart(false, 4);\n collector.OnNameData(\"na\", 2);\n QUICHE_VLOG(1) << collector;\n collector.OnNameData(\"me\", 2);\n collector.OnNameEnd();\n collector.OnValueStart(true, 5);\n QUICHE_VLOG(1) << collector;\n collector.OnValueData(\"Value\", 5);\n collector.OnValueEnd();\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsComplete());\n EXPECT_TRUE(collector.ValidateLiteralNameValueHeader(\n HpackEntryType::kUnindexedLiteralHeader, false, \"name\", true, \"Value\"));\n EXPECT_FATAL_FAILURE(LiteralNameValueHeaderErrorTest(),\n \"Value of: name_.HasEnded\");\n}\nvoid DynamicTableSizeUpdateErrorTest() {\n HpackEntryCollector collector;\n collector.OnDynamicTableSizeUpdate(123);\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsComplete());\n EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(123));\n collector.OnDynamicTableSizeUpdate(234);\n}\nTEST(HpackEntryCollectorTest, DynamicTableSizeUpdate) {\n HpackEntryCollector collector;\n collector.OnDynamicTableSizeUpdate(8192);\n QUICHE_VLOG(1) << collector;\n EXPECT_FALSE(collector.IsClear());\n EXPECT_TRUE(collector.IsComplete());\n EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(8192));\n EXPECT_EQ(collector,\n HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8192));\n EXPECT_NE(collector,\n HpackEntryCollector(HpackEntryType::kIndexedHeader, 8192));\n EXPECT_NE(collector,\n HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8191));\n EXPECT_FATAL_FAILURE(DynamicTableSizeUpdateErrorTest(), \"Value of: started_\");\n}\n} \n} \n} "}}},{"rowIdx":451,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HTTP2_FRAME_BUILDER_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HTTP2_FRAME_BUILDER_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/http2_structures.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace http2 {\nnamespace test {\nclass QUICHE_NO_EXPORT Http2FrameBuilder {\n public:\n Http2FrameBuilder(Http2FrameType type, uint8_t flags, uint32_t stream_id);\n explicit Http2FrameBuilder(const Http2FrameHeader& v);\n Http2FrameBuilder() {}\n ~Http2FrameBuilder() {}\n size_t size() const { return buffer_.size(); }\n const std::string& buffer() const { return buffer_; }\n void Append(absl::string_view s);\n void AppendBytes(const void* data, uint32_t num_bytes);\n template \n void AppendBytes(T (&buf)[N]) {\n AppendBytes(buf, N * sizeof(buf[0]));\n }\n void AppendZeroes(size_t num_zero_bytes);\n void AppendUInt8(uint8_t value);\n void AppendUInt16(uint16_t value);\n void AppendUInt24(uint32_t value);\n void AppendUInt31(uint32_t value);\n void AppendUInt32(uint32_t value);\n void Append(Http2ErrorCode error_code);\n void Append(Http2FrameType type);\n void Append(Http2SettingsParameter parameter);\n void Append(const Http2FrameHeader& v);\n void Append(const Http2PriorityFields& v);\n void Append(const Http2RstStreamFields& v);\n void Append(const Http2SettingFields& v);\n void Append(const Http2PushPromiseFields& v);\n void Append(const Http2PingFields& v);\n void Append(const Http2GoAwayFields& v);\n void Append(const Http2WindowUpdateFields& v);\n void Append(const Http2AltSvcFields& v);\n void Append(const Http2PriorityUpdateFields& v);\n void WriteAt(absl::string_view s, size_t offset);\n void WriteBytesAt(const void* data, uint32_t num_bytes, size_t offset);\n void WriteUInt24At(uint32_t value, size_t offset);\n void SetPayloadLength(uint32_t payload_length);\n size_t SetPayloadLength();\n private:\n std::string buffer_;\n};\n} \n} \n#endif \n#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#ifdef WIN32\n#include \n#else\n#include \n#include \n#endif\n#include \"absl/strings/str_cat.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nHttp2FrameBuilder::Http2FrameBuilder(Http2FrameType type, uint8_t flags,\n uint32_t stream_id) {\n AppendUInt24(0); \n Append(type);\n AppendUInt8(flags);\n AppendUInt31(stream_id);\n}\nHttp2FrameBuilder::Http2FrameBuilder(const Http2FrameHeader& v) { Append(v); }\nvoid Http2FrameBuilder::Append(absl::string_view s) {\n absl::StrAppend(&buffer_, s);\n}\nvoid Http2FrameBuilder::AppendBytes(const void* data, uint32_t num_bytes) {\n Append(absl::string_view(static_cast(data), num_bytes));\n}\nvoid Http2FrameBuilder::AppendZeroes(size_t num_zero_bytes) {\n char zero = 0;\n buffer_.append(num_zero_bytes, zero);\n}\nvoid Http2FrameBuilder::AppendUInt8(uint8_t value) { AppendBytes(&value, 1); }\nvoid Http2FrameBuilder::AppendUInt16(uint16_t value) {\n value = htons(value);\n AppendBytes(&value, 2);\n}\nvoid Http2FrameBuilder::AppendUInt24(uint32_t value) {\n EXPECT_EQ(value, value & 0xffffff);\n value = htonl(value);\n AppendBytes(reinterpret_cast(&value) + 1, 3);\n}\nvoid Http2FrameBuilder::AppendUInt31(uint32_t value) {\n uint32_t tmp = value & StreamIdMask();\n EXPECT_EQ(value, value & StreamIdMask())\n << \"High-bit of uint32_t should be clear.\";\n value = htonl(tmp);\n AppendBytes(&value, 4);\n}\nvoid Http2FrameBuilder::AppendUInt32(uint32_t value) {\n value = htonl(value);\n AppendBytes(&value, sizeof(value));\n}\nvoid Http2FrameBuilder::Append(Http2ErrorCode error_code) {\n AppendUInt32(static_cast(error_code));\n}\nvoid Http2FrameBuilder::Append(Http2FrameType type) {\n AppendUInt8(static_cast(type));\n}\nvoid Http2FrameBuilder::Append(Http2SettingsParameter parameter) {\n AppendUInt16(static_cast(parameter));\n}\nvoid Http2FrameBuilder::Append(const Http2FrameHeader& v) {\n AppendUInt24(v.payload_length);\n Append(v.type);\n AppendUInt8(v.flags);\n AppendUInt31(v.stream_id);\n}\nvoid Http2FrameBuilder::Append(const Http2PriorityFields& v) {\n uint32_t tmp = v.stream_dependency & StreamIdMask();\n EXPECT_EQ(tmp, v.stream_dependency);\n if (v.is_exclusive) {\n tmp |= 0x80000000;\n }\n AppendUInt32(tmp);\n ASSERT_LE(1u, v.weight);\n ASSERT_LE(v.weight, 256u);\n AppendUInt8(v.weight - 1);\n}\nvoid Http2FrameBuilder::Append(const Http2RstStreamFields& v) {\n Append(v.error_code);\n}\nvoid Http2FrameBuilder::Append(const Http2SettingFields& v) {\n Append(v.parameter);\n AppendUInt32(v.value);\n}\nvoid Http2FrameBuilder::Append(const Http2PushPromiseFields& v) {\n AppendUInt31(v.promised_stream_id);\n}\nvoid Http2FrameBuilder::Append(const Http2PingFields& v) {\n AppendBytes(v.opaque_bytes, sizeof Http2PingFields::opaque_bytes);\n}\nvoid Http2FrameBuilder::Append(const Http2GoAwayFields& v) {\n AppendUInt31(v.last_stream_id);\n Append(v.error_code);\n}\nvoid Http2FrameBuilder::Append(const Http2WindowUpdateFields& v) {\n EXPECT_NE(0u, v.window_size_increment) << \"Increment must be non-zero.\";\n AppendUInt31(v.window_size_increment);\n}\nvoid Http2FrameBuilder::Append(const Http2AltSvcFields& v) {\n AppendUInt16(v.origin_length);\n}\nvoid Http2FrameBuilder::Append(const Http2PriorityUpdateFields& v) {\n AppendUInt31(v.prioritized_stream_id);\n}\nvoid Http2FrameBuilder::WriteAt(absl::string_view s, size_t offset) {\n ASSERT_LE(offset, buffer_.size());\n size_t len = offset + s.size();\n if (len > buffer_.size()) {\n buffer_.resize(len);\n }\n for (size_t ndx = 0; ndx < s.size(); ++ndx) {\n buffer_[offset + ndx] = s[ndx];\n }\n}\nvoid Http2FrameBuilder::WriteBytesAt(const void* data, uint32_t num_bytes,\n size_t offset) {\n WriteAt(absl::string_view(static_cast(data), num_bytes), offset);\n}\nvoid Http2FrameBuilder::WriteUInt24At(uint32_t value, size_t offset) {\n ASSERT_LT(value, static_cast(1 << 24));\n value = htonl(value);\n WriteBytesAt(reinterpret_cast(&value) + 1, sizeof(value) - 1, offset);\n}\nvoid Http2FrameBuilder::SetPayloadLength(uint32_t payload_length) {\n WriteUInt24At(payload_length, 0);\n}\nsize_t Http2FrameBuilder::SetPayloadLength() {\n EXPECT_GE(size(), Http2FrameHeader::EncodedSize());\n uint32_t payload_length = size() - Http2FrameHeader::EncodedSize();\n SetPayloadLength(payload_length);\n return payload_length;\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/http2_frame_builder.h\"\n#include \n#include \"absl/strings/escaping.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nconst char kHighBitSetMsg[] = \"High-bit of uint32_t should be clear\";\nTEST(Http2FrameBuilderTest, Constructors) {\n {\n Http2FrameBuilder fb;\n EXPECT_EQ(0u, fb.size());\n }\n {\n Http2FrameBuilder fb(Http2FrameType::DATA, 0, 123);\n EXPECT_EQ(9u, fb.size());\n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"000000\" \n \"00\" \n \"00\" \n \"0000007b\", \n &expected_data));\n EXPECT_EQ(expected_data, fb.buffer());\n }\n {\n Http2FrameHeader header;\n header.payload_length = (1 << 24) - 1;\n header.type = Http2FrameType::HEADERS;\n header.flags = Http2FrameFlag::END_HEADERS;\n header.stream_id = StreamIdMask();\n Http2FrameBuilder fb(header);\n EXPECT_EQ(9u, fb.size());\n std::string expected_data;\n ASSERT_TRUE(absl::HexStringToBytes(\n \"ffffff\" \n \"01\" \n \"04\" \n \"7fffffff\", \n &expected_data));\n EXPECT_EQ(expected_data, fb.buffer());\n }\n}\nTEST(Http2FrameBuilderTest, SetPayloadLength) {\n Http2FrameBuilder fb(Http2FrameType::DATA, PADDED, 20000);\n EXPECT_EQ(9u, fb.size());\n fb.AppendUInt8(50); \n EXPECT_EQ(10u, fb.size());\n fb.Append(\"ten bytes.\");\n EXPECT_EQ(20u, fb.size());\n fb.AppendZeroes(50);\n EXPECT_EQ(70u, fb.size());\n fb.SetPayloadLength();\n EXPECT_EQ(70u, fb.size());\n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"00003d\" \n \"00\" \n \"08\" \n \"00004e20\" \n \"32\" \n \"74656e2062797465732e\" \n \"00000000000000000000\" \n \"00000000000000000000\" \n \"00000000000000000000\" \n \"00000000000000000000\" \n \"00000000000000000000\", \n &expected_data));\n EXPECT_EQ(expected_data, fb.buffer());\n}\nTEST(Http2FrameBuilderTest, Settings) {\n Http2FrameBuilder fb(Http2FrameType::SETTINGS, 0, 0);\n Http2SettingFields sf;\n sf.parameter = Http2SettingsParameter::HEADER_TABLE_SIZE;\n sf.value = 1 << 12;\n fb.Append(sf);\n sf.parameter = Http2SettingsParameter::ENABLE_PUSH;\n sf.value = 0;\n fb.Append(sf);\n sf.parameter = Http2SettingsParameter::MAX_CONCURRENT_STREAMS;\n sf.value = ~0;\n fb.Append(sf);\n sf.parameter = Http2SettingsParameter::INITIAL_WINDOW_SIZE;\n sf.value = 1 << 16;\n fb.Append(sf);\n sf.parameter = Http2SettingsParameter::MAX_FRAME_SIZE;\n sf.value = 1 << 14;\n fb.Append(sf);\n sf.parameter = Http2SettingsParameter::MAX_HEADER_LIST_SIZE;\n sf.value = 1 << 10;\n fb.Append(sf);\n size_t payload_size = 6 * Http2SettingFields::EncodedSize();\n EXPECT_EQ(Http2FrameHeader::EncodedSize() + payload_size, fb.size());\n fb.SetPayloadLength(payload_size);\n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"000024\" \n \"04\" \n \"00\" \n \"00000000\" \n \"0001\" \n \"00001000\" \n \"0002\" \n \"00000000\" \n \"0003\" \n \"ffffffff\" \n \"0004\" \n \"00010000\" \n \"0005\" \n \"00004000\" \n \"0006\" \n \"00000400\", \n &expected_data));\n EXPECT_EQ(expected_data, fb.buffer());\n}\nTEST(Http2FrameBuilderTest, EnhanceYourCalm) {\n std::string expected_data;\n ASSERT_TRUE(absl::HexStringToBytes(\"0000000b\", &expected_data));\n {\n Http2FrameBuilder fb;\n fb.Append(Http2ErrorCode::ENHANCE_YOUR_CALM);\n EXPECT_EQ(expected_data, fb.buffer());\n }\n {\n Http2FrameBuilder fb;\n Http2RstStreamFields rsp;\n rsp.error_code = Http2ErrorCode::ENHANCE_YOUR_CALM;\n fb.Append(rsp);\n EXPECT_EQ(expected_data, fb.buffer());\n }\n}\nTEST(Http2FrameBuilderTest, PushPromise) {\n std::string expected_data;\n ASSERT_TRUE(absl::HexStringToBytes(\"7fffffff\", &expected_data));\n {\n Http2FrameBuilder fb;\n fb.Append(Http2PushPromiseFields{0x7fffffff});\n EXPECT_EQ(expected_data, fb.buffer());\n }\n {\n Http2FrameBuilder fb;\n EXPECT_NONFATAL_FAILURE(fb.Append(Http2PushPromiseFields{0xffffffff}),\n kHighBitSetMsg);\n EXPECT_EQ(expected_data, fb.buffer());\n }\n}\nTEST(Http2FrameBuilderTest, Ping) {\n Http2FrameBuilder fb;\n Http2PingFields ping{\"8 bytes\"};\n fb.Append(ping);\n const absl::string_view kData{\"8 bytes\\0\", 8};\n EXPECT_EQ(kData.size(), Http2PingFields::EncodedSize());\n EXPECT_EQ(kData, fb.buffer());\n}\nTEST(Http2FrameBuilderTest, GoAway) {\n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"12345678\" \n \"00000001\", \n &expected_data));\n EXPECT_EQ(expected_data.size(), Http2GoAwayFields::EncodedSize());\n {\n Http2FrameBuilder fb;\n Http2GoAwayFields ga(0x12345678, Http2ErrorCode::PROTOCOL_ERROR);\n fb.Append(ga);\n EXPECT_EQ(expected_data, fb.buffer());\n }\n {\n Http2FrameBuilder fb;\n Http2GoAwayFields ga(0x92345678, Http2ErrorCode::PROTOCOL_ERROR);\n EXPECT_NONFATAL_FAILURE(fb.Append(ga), kHighBitSetMsg);\n EXPECT_EQ(expected_data, fb.buffer());\n }\n}\nTEST(Http2FrameBuilderTest, WindowUpdate) {\n Http2FrameBuilder fb;\n fb.Append(Http2WindowUpdateFields{123456});\n EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0x80000001}),\n kHighBitSetMsg);\n EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0}), \"non-zero\");\n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"0001e240\" \n \"00000001\" \n \"00000000\", \n &expected_data));\n EXPECT_EQ(expected_data.size(), 3 * Http2WindowUpdateFields::EncodedSize());\n EXPECT_EQ(expected_data, fb.buffer());\n}\nTEST(Http2FrameBuilderTest, AltSvc) {\n Http2FrameBuilder fb;\n fb.Append(Http2AltSvcFields{99});\n fb.Append(Http2AltSvcFields{0}); \n std::string expected_data;\n ASSERT_TRUE(\n absl::HexStringToBytes(\"0063\" \n \"0000\", \n &expected_data));\n EXPECT_EQ(expected_data.size(), 2 * Http2AltSvcFields::EncodedSize());\n EXPECT_EQ(expected_data, fb.buffer());\n}\n} \n} \n} "}}},{"rowIdx":452,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_BUILDER_H_\n#define QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_BUILDER_H_\n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/hpack/http2_hpack_constants.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nclass QUICHE_NO_EXPORT HpackBlockBuilder {\n public:\n explicit HpackBlockBuilder(absl::string_view initial_contents)\n : buffer_(initial_contents.data(), initial_contents.size()) {}\n HpackBlockBuilder() {}\n ~HpackBlockBuilder() {}\n size_t size() const { return buffer_.size(); }\n const std::string& buffer() const { return buffer_; }\n void AppendIndexedHeader(uint64_t index) {\n AppendEntryTypeAndVarint(HpackEntryType::kIndexedHeader, index);\n }\n void AppendDynamicTableSizeUpdate(uint64_t size) {\n AppendEntryTypeAndVarint(HpackEntryType::kDynamicTableSizeUpdate, size);\n }\n void AppendNameIndexAndLiteralValue(HpackEntryType entry_type,\n uint64_t name_index,\n bool value_is_huffman_encoded,\n absl::string_view value) {\n EXPECT_NE(0u, name_index);\n AppendEntryTypeAndVarint(entry_type, name_index);\n AppendString(value_is_huffman_encoded, value);\n }\n void AppendLiteralNameAndValue(HpackEntryType entry_type,\n bool name_is_huffman_encoded,\n absl::string_view name,\n bool value_is_huffman_encoded,\n absl::string_view value) {\n AppendEntryTypeAndVarint(entry_type, 0);\n AppendString(name_is_huffman_encoded, name);\n AppendString(value_is_huffman_encoded, value);\n }\n void AppendHighBitsAndVarint(uint8_t high_bits, uint8_t prefix_length,\n uint64_t varint);\n void AppendEntryTypeAndVarint(HpackEntryType entry_type, uint64_t varint);\n void AppendString(bool is_huffman_encoded, absl::string_view str);\n private:\n std::string buffer_;\n};\n} \n} \n#endif \n#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \"quiche/http2/hpack/varint/hpack_varint_encoder.h\"\n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nvoid HpackBlockBuilder::AppendHighBitsAndVarint(uint8_t high_bits,\n uint8_t prefix_length,\n uint64_t varint) {\n EXPECT_LE(3, prefix_length);\n EXPECT_LE(prefix_length, 8);\n HpackVarintEncoder::Encode(high_bits, prefix_length, varint, &buffer_);\n}\nvoid HpackBlockBuilder::AppendEntryTypeAndVarint(HpackEntryType entry_type,\n uint64_t varint) {\n uint8_t high_bits;\n uint8_t prefix_length; \n switch (entry_type) {\n case HpackEntryType::kIndexedHeader:\n high_bits = 0x80;\n prefix_length = 7;\n break;\n case HpackEntryType::kDynamicTableSizeUpdate:\n high_bits = 0x20;\n prefix_length = 5;\n break;\n case HpackEntryType::kIndexedLiteralHeader:\n high_bits = 0x40;\n prefix_length = 6;\n break;\n case HpackEntryType::kUnindexedLiteralHeader:\n high_bits = 0x00;\n prefix_length = 4;\n break;\n case HpackEntryType::kNeverIndexedLiteralHeader:\n high_bits = 0x10;\n prefix_length = 4;\n break;\n default:\n QUICHE_BUG(http2_bug_110_1) << \"Unreached, entry_type=\" << entry_type;\n high_bits = 0;\n prefix_length = 0;\n break;\n }\n AppendHighBitsAndVarint(high_bits, prefix_length, varint);\n}\nvoid HpackBlockBuilder::AppendString(bool is_huffman_encoded,\n absl::string_view str) {\n uint8_t high_bits = is_huffman_encoded ? 0x80 : 0;\n uint8_t prefix_length = 7;\n AppendHighBitsAndVarint(high_bits, prefix_length, str.size());\n buffer_.append(str.data(), str.size());\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/hpack_block_builder.h\"\n#include \n#include \"absl/strings/escaping.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nconst bool kUncompressed = false;\nconst bool kCompressed = true;\nconst uint32_t kStaticTableMethodGET = 2;\nconst uint32_t kStaticTablePathSlash = 4;\nconst uint32_t kStaticTableSchemeHttp = 6;\nTEST(HpackBlockBuilderTest, ExamplesFromSpecC2) {\n {\n HpackBlockBuilder b;\n b.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,\n kUncompressed, \"custom-key\", kUncompressed,\n \"custom-header\");\n EXPECT_EQ(26u, b.size());\n const char kExpected[] =\n \"\\x40\" \n \"\\x0a\" \n \"custom-key\" \n \"\\x0d\" \n \"custom-header\"; \n EXPECT_EQ(kExpected, b.buffer());\n }\n {\n HpackBlockBuilder b;\n b.AppendNameIndexAndLiteralValue(HpackEntryType::kUnindexedLiteralHeader, 4,\n kUncompressed, \"/sample/path\");\n EXPECT_EQ(14u, b.size());\n const char kExpected[] =\n \"\\x04\" \n \"\\x0c\" \n \"/sample/path\"; \n EXPECT_EQ(kExpected, b.buffer());\n }\n {\n HpackBlockBuilder b;\n b.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader,\n kUncompressed, \"password\", kUncompressed,\n \"secret\");\n EXPECT_EQ(17u, b.size());\n const char kExpected[] =\n \"\\x10\" \n \"\\x08\" \n \"password\" \n \"\\x06\" \n \"secret\"; \n EXPECT_EQ(kExpected, b.buffer());\n }\n {\n HpackBlockBuilder b;\n b.AppendIndexedHeader(2);\n EXPECT_EQ(1u, b.size());\n const char kExpected[] = \"\\x82\"; \n EXPECT_EQ(kExpected, b.buffer());\n }\n}\nTEST(HpackBlockBuilderTest, ExamplesFromSpecC3) {\n {\n HpackBlockBuilder b;\n b.AppendIndexedHeader(2); \n b.AppendIndexedHeader(6); \n b.AppendIndexedHeader(4); \n b.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 1,\n kUncompressed, \"www.example.com\");\n EXPECT_EQ(20u, b.size());\n std::string expected;\n ASSERT_TRUE(absl::HexStringToBytes(\n \"828684410f7777772e6578616d706c652e636f6d\", &expected));\n EXPECT_EQ(expected, b.buffer());\n }\n}\nTEST(HpackBlockBuilderTest, ExamplesFromSpecC4) {\n {\n HpackBlockBuilder b;\n b.AppendIndexedHeader(kStaticTableMethodGET);\n b.AppendIndexedHeader(kStaticTableSchemeHttp);\n b.AppendIndexedHeader(kStaticTablePathSlash);\n const char kHuffmanWwwExampleCom[] = {'\\xf1', '\\xe3', '\\xc2', '\\xe5',\n '\\xf2', '\\x3a', '\\x6b', '\\xa0',\n '\\xab', '\\x90', '\\xf4', '\\xff'};\n b.AppendNameIndexAndLiteralValue(\n HpackEntryType::kIndexedLiteralHeader, 1, kCompressed,\n absl::string_view(kHuffmanWwwExampleCom, sizeof kHuffmanWwwExampleCom));\n EXPECT_EQ(17u, b.size());\n std::string expected;\n ASSERT_TRUE(absl::HexStringToBytes(\"828684418cf1e3c2e5f23a6ba0ab90f4ff\",\n &expected));\n EXPECT_EQ(expected, b.buffer());\n }\n}\nTEST(HpackBlockBuilderTest, DynamicTableSizeUpdate) {\n {\n HpackBlockBuilder b;\n b.AppendDynamicTableSizeUpdate(0);\n EXPECT_EQ(1u, b.size());\n const char kData[] = {'\\x20'};\n absl::string_view expected(kData, sizeof kData);\n EXPECT_EQ(expected, b.buffer());\n }\n {\n HpackBlockBuilder b;\n b.AppendDynamicTableSizeUpdate(4096); \n EXPECT_EQ(3u, b.size());\n const char kData[] = {'\\x3f', '\\xe1', '\\x1f'};\n absl::string_view expected(kData, sizeof kData);\n EXPECT_EQ(expected, b.buffer());\n }\n {\n HpackBlockBuilder b;\n b.AppendDynamicTableSizeUpdate(1000000000000); \n EXPECT_EQ(7u, b.size());\n const char kData[] = {'\\x3f', '\\xe1', '\\x9f', '\\x94',\n '\\xa5', '\\x8d', '\\x1d'};\n absl::string_view expected(kData, sizeof kData);\n EXPECT_EQ(expected, b.buffer());\n }\n}\n} \n} \n} "}}},{"rowIdx":453,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_HTTP2_TEST_TOOLS_RANDOM_DECODER_TEST_BASE_H_\n#define QUICHE_HTTP2_TEST_TOOLS_RANDOM_DECODER_TEST_BASE_H_\n#include \n#include \n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\n#include \"quiche/common/quiche_callbacks.h\"\nnamespace http2 {\nnamespace test {\ntemplate \nabsl::string_view ToStringPiece(T (&data)[N]) {\n return absl::string_view(reinterpret_cast(data), N * sizeof(T));\n}\ntemplate ::value>::type>\nvoid CorruptEnum(T* out, Http2Random* rng) {\n using underlying_type_T = typename std::underlying_type::type;\n using unsigned_underlying_type_T =\n typename std::make_unsigned::type;\n auto r = static_cast(rng->Rand32());\n *out = static_cast(r);\n}\nclass QUICHE_NO_EXPORT RandomDecoderTest : public quiche::test::QuicheTest {\n public:\n using SelectSize = quiche::MultiUseCallback;\n using AssertionResult = ::testing::AssertionResult;\n using Validator = quiche::MultiUseCallback;\n using NoArgValidator = quiche::MultiUseCallback;\n RandomDecoderTest();\n protected:\n virtual DecodeStatus StartDecoding(DecodeBuffer* db) = 0;\n virtual DecodeStatus ResumeDecoding(DecodeBuffer* db) = 0;\n virtual bool StopDecodeOnDone();\n DecodeStatus DecodeSegments(DecodeBuffer* original,\n const SelectSize& select_size);\n ::testing::AssertionResult DecodeSegmentsAndValidate(\n DecodeBuffer* original, const SelectSize& select_size,\n const Validator& validator) {\n DecodeStatus status = DecodeSegments(original, select_size);\n return validator(*original, status);\n }\n static SelectSize SelectRemaining() {\n return [](bool , size_t , size_t remaining) -> size_t {\n return remaining;\n };\n }\n static SelectSize SelectOne() {\n return [](bool , size_t ,\n size_t ) -> size_t { return 1; };\n }\n static SelectSize SelectZeroAndOne(bool return_non_zero_on_first);\n SelectSize SelectRandom(bool return_non_zero_on_first);\n AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* original,\n bool return_non_zero_on_first,\n const Validator& validator);\n static Validator ToValidator(std::nullptr_t) {\n return [](const DecodeBuffer& , DecodeStatus ) {\n return ::testing::AssertionSuccess();\n };\n }\n static Validator ToValidator(Validator validator) {\n if (validator == nullptr) {\n return ToValidator(nullptr);\n }\n return validator;\n }\n static Validator ToValidator(NoArgValidator validator) {\n if (validator == nullptr) {\n return ToValidator(nullptr);\n }\n return [validator = std::move(validator)](const DecodeBuffer& ,\n DecodeStatus ) {\n return validator();\n };\n }\n static Validator ValidateDoneAndEmpty(Validator wrapped) {\n return [wrapped = std::move(wrapped)](\n const DecodeBuffer& input,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);\n HTTP2_VERIFY_EQ(0u, input.Remaining()) << \"\\nOffset=\" << input.Offset();\n if (wrapped) {\n return wrapped(input, status);\n }\n return ::testing::AssertionSuccess();\n };\n }\n static Validator ValidateDoneAndEmpty(NoArgValidator wrapped) {\n return [wrapped = std::move(wrapped)](\n const DecodeBuffer& input,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);\n HTTP2_VERIFY_EQ(0u, input.Remaining()) << \"\\nOffset=\" << input.Offset();\n if (wrapped) {\n return wrapped();\n }\n return ::testing::AssertionSuccess();\n };\n }\n static Validator ValidateDoneAndEmpty() {\n return ValidateDoneAndEmpty(NoArgValidator());\n }\n static Validator ValidateDoneAndOffset(uint32_t offset, Validator wrapped) {\n return [wrapped = std::move(wrapped), offset](\n const DecodeBuffer& input,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);\n HTTP2_VERIFY_EQ(offset, input.Offset())\n << \"\\nRemaining=\" << input.Remaining();\n if (wrapped) {\n return wrapped(input, status);\n }\n return ::testing::AssertionSuccess();\n };\n }\n static Validator ValidateDoneAndOffset(uint32_t offset,\n NoArgValidator wrapped) {\n return [wrapped = std::move(wrapped), offset](\n const DecodeBuffer& input,\n DecodeStatus status) -> AssertionResult {\n HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);\n HTTP2_VERIFY_EQ(offset, input.Offset())\n << \"\\nRemaining=\" << input.Remaining();\n if (wrapped) {\n return wrapped();\n }\n return ::testing::AssertionSuccess();\n };\n }\n static Validator ValidateDoneAndOffset(uint32_t offset) {\n return ValidateDoneAndOffset(offset, NoArgValidator());\n }\n Http2Random& Random() { return random_; }\n Http2Random* RandomPtr() { return &random_; }\n uint32_t RandStreamId();\n bool stop_decode_on_done_ = true;\n private:\n Http2Random random_;\n};\n} \n} \n#endif \n#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/http2_constants.h\"\n#include \"quiche/http2/test_tools/verify_macros.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::AssertionResult;\nnamespace http2 {\nnamespace test {\nRandomDecoderTest::RandomDecoderTest() = default;\nbool RandomDecoderTest::StopDecodeOnDone() { return stop_decode_on_done_; }\nDecodeStatus RandomDecoderTest::DecodeSegments(DecodeBuffer* original,\n const SelectSize& select_size) {\n DecodeStatus status = DecodeStatus::kDecodeInProgress;\n bool first = true;\n QUICHE_VLOG(2) << \"DecodeSegments: input size=\" << original->Remaining();\n while (first || original->HasData()) {\n size_t remaining = original->Remaining();\n size_t size =\n std::min(remaining, select_size(first, original->Offset(), remaining));\n DecodeBuffer db(original->cursor(), size);\n QUICHE_VLOG(2) << \"Decoding \" << size << \" bytes of \" << remaining\n << \" remaining\";\n if (first) {\n first = false;\n status = StartDecoding(&db);\n } else {\n status = ResumeDecoding(&db);\n }\n if (db.Offset() == 0 && db.HasData() &&\n status != DecodeStatus::kDecodeError) {\n ADD_FAILURE() << \"Decoder didn't make any progress; db.FullSize=\"\n << db.FullSize()\n << \" original.Offset=\" << original->Offset();\n return DecodeStatus::kDecodeError;\n }\n original->AdvanceCursor(db.Offset());\n switch (status) {\n case DecodeStatus::kDecodeDone:\n if (original->Empty() || StopDecodeOnDone()) {\n return DecodeStatus::kDecodeDone;\n }\n continue;\n case DecodeStatus::kDecodeInProgress:\n continue;\n case DecodeStatus::kDecodeError:\n return DecodeStatus::kDecodeError;\n }\n }\n return status;\n}\nAssertionResult RandomDecoderTest::DecodeAndValidateSeveralWays(\n DecodeBuffer* original, bool return_non_zero_on_first,\n const Validator& validator) {\n const uint32_t original_remaining = original->Remaining();\n QUICHE_VLOG(1) << \"DecodeAndValidateSeveralWays - Start, remaining = \"\n << original_remaining;\n uint32_t first_consumed;\n {\n DecodeBuffer input(original->cursor(), original_remaining);\n QUICHE_VLOG(2) << \"DecodeSegmentsAndValidate with SelectRemaining\";\n HTTP2_VERIFY_SUCCESS(\n DecodeSegmentsAndValidate(&input, SelectRemaining(), validator))\n << \"\\nFailed with SelectRemaining; input.Offset=\" << input.Offset()\n << \"; input.Remaining=\" << input.Remaining();\n first_consumed = input.Offset();\n }\n if (original_remaining <= 30) {\n DecodeBuffer input(original->cursor(), original_remaining);\n QUICHE_VLOG(2) << \"DecodeSegmentsAndValidate with SelectOne\";\n HTTP2_VERIFY_SUCCESS(\n DecodeSegmentsAndValidate(&input, SelectOne(), validator))\n << \"\\nFailed with SelectOne; input.Offset=\" << input.Offset()\n << \"; input.Remaining=\" << input.Remaining();\n HTTP2_VERIFY_EQ(first_consumed, input.Offset())\n << \"\\nFailed with SelectOne\";\n }\n if (original_remaining <= 20) {\n DecodeBuffer input(original->cursor(), original_remaining);\n QUICHE_VLOG(2) << \"DecodeSegmentsAndValidate with SelectZeroAndOne\";\n HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate(\n &input, SelectZeroAndOne(return_non_zero_on_first), validator))\n << \"\\nFailed with SelectZeroAndOne\";\n HTTP2_VERIFY_EQ(first_consumed, input.Offset())\n << \"\\nFailed with SelectZeroAndOne; input.Offset=\" << input.Offset()\n << \"; input.Remaining=\" << input.Remaining();\n }\n {\n DecodeBuffer input(original->cursor(), original_remaining);\n QUICHE_VLOG(2) << \"DecodeSegmentsAndValidate with SelectRandom\";\n HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate(\n &input, SelectRandom(return_non_zero_on_first), validator))\n << \"\\nFailed with SelectRandom; input.Offset=\" << input.Offset()\n << \"; input.Remaining=\" << input.Remaining();\n HTTP2_VERIFY_EQ(first_consumed, input.Offset())\n << \"\\nFailed with SelectRandom\";\n }\n HTTP2_VERIFY_EQ(original_remaining, original->Remaining());\n original->AdvanceCursor(first_consumed);\n QUICHE_VLOG(1) << \"DecodeAndValidateSeveralWays - SUCCESS\";\n return ::testing::AssertionSuccess();\n}\nRandomDecoderTest::SelectSize RandomDecoderTest::SelectZeroAndOne(\n bool return_non_zero_on_first) {\n std::shared_ptr zero_next(new bool);\n *zero_next = !return_non_zero_on_first;\n return [zero_next](bool , size_t ,\n size_t ) -> size_t {\n if (*zero_next) {\n *zero_next = false;\n return 0;\n } else {\n *zero_next = true;\n return 1;\n }\n };\n}\nRandomDecoderTest::SelectSize RandomDecoderTest::SelectRandom(\n bool return_non_zero_on_first) {\n return [this, return_non_zero_on_first](bool first, size_t ,\n size_t remaining) -> size_t {\n uint32_t r = random_.Rand32();\n if (first && return_non_zero_on_first) {\n QUICHE_CHECK_LT(0u, remaining);\n if (remaining == 1) {\n return 1;\n }\n return 1 + (r % remaining); \n }\n return r % (remaining + 1); \n };\n}\nuint32_t RandomDecoderTest::RandStreamId() {\n return random_.Rand32() & StreamIdMask();\n}\n} \n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/http2/test_tools/random_decoder_test_base.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"quiche/http2/decoder/decode_buffer.h\"\n#include \"quiche/http2/decoder/decode_status.h\"\n#include \"quiche/http2/test_tools/http2_random.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\n#include \"quiche/common/quiche_callbacks.h\"\nnamespace http2 {\nnamespace test {\nnamespace {\nconst char kData[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};\nconst bool kReturnNonZeroOnFirst = true;\nconst bool kMayReturnZeroOnFirst = false;\nclass RandomDecoderTestTest : public RandomDecoderTest {\n public:\n RandomDecoderTestTest() : data_db_(kData) {\n QUICHE_CHECK_EQ(sizeof kData, 8u);\n }\n protected:\n typedef quiche::MultiUseCallback DecodingFn;\n DecodeStatus StartDecoding(DecodeBuffer* db) override {\n ++start_decoding_calls_;\n if (start_decoding_fn_) {\n return start_decoding_fn_(db);\n }\n return DecodeStatus::kDecodeError;\n }\n DecodeStatus ResumeDecoding(DecodeBuffer* db) override {\n ++resume_decoding_calls_;\n if (resume_decoding_fn_) {\n return resume_decoding_fn_(db);\n }\n return DecodeStatus::kDecodeError;\n }\n bool StopDecodeOnDone() override {\n ++stop_decode_on_done_calls_;\n if (override_stop_decode_on_done_) {\n return sub_stop_decode_on_done_;\n }\n return RandomDecoderTest::StopDecodeOnDone();\n }\n size_t start_decoding_calls_ = 0;\n size_t resume_decoding_calls_ = 0;\n size_t stop_decode_on_done_calls_ = 0;\n DecodingFn start_decoding_fn_;\n DecodingFn resume_decoding_fn_;\n DecodeBuffer data_db_;\n bool sub_stop_decode_on_done_ = true;\n bool override_stop_decode_on_done_ = true;\n};\nTEST_F(RandomDecoderTestTest, StopOnStartPartiallyDone) {\n start_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_EQ(kData, db->cursor());\n EXPECT_EQ(sizeof kData, db->Remaining());\n db->DecodeUInt8();\n return DecodeStatus::kDecodeDone;\n };\n EXPECT_EQ(DecodeStatus::kDecodeDone,\n DecodeSegments(&data_db_, SelectRemaining()));\n EXPECT_EQ(1u, data_db_.Offset());\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_EQ(0u, resume_decoding_calls_);\n EXPECT_EQ(1u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, StopOnResumePartiallyDone) {\n start_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, start_decoding_calls_);\n db->DecodeUInt8();\n return DecodeStatus::kDecodeInProgress;\n };\n resume_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, resume_decoding_calls_);\n EXPECT_EQ(data_db_.cursor(), db->cursor());\n db->DecodeUInt16();\n return DecodeStatus::kDecodeDone;\n };\n override_stop_decode_on_done_ = false;\n stop_decode_on_done_ = true;\n EXPECT_EQ(DecodeStatus::kDecodeDone,\n DecodeSegments(&data_db_, SelectRemaining()));\n EXPECT_EQ(3u, data_db_.Offset());\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_EQ(1u, resume_decoding_calls_);\n EXPECT_EQ(1u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, InProgressWhenEmpty) {\n start_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, start_decoding_calls_);\n if (db->HasData()) {\n db->DecodeUInt8();\n if (db->HasData()) {\n db->DecodeUInt8();\n }\n }\n return DecodeStatus::kDecodeInProgress;\n };\n resume_decoding_fn_ = [](DecodeBuffer* db) {\n if (db->HasData()) {\n db->AdvanceCursor(db->Remaining());\n }\n return DecodeStatus::kDecodeInProgress;\n };\n EXPECT_EQ(DecodeStatus::kDecodeInProgress,\n DecodeSegments(&data_db_, SelectRandom(kMayReturnZeroOnFirst)));\n EXPECT_TRUE(data_db_.Empty());\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_LE(1u, resume_decoding_calls_);\n EXPECT_EQ(0u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, DoneExactlyAtEnd) {\n start_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_EQ(1u, db->Remaining());\n EXPECT_EQ(1u, db->FullSize());\n db->DecodeUInt8();\n return DecodeStatus::kDecodeInProgress;\n };\n resume_decoding_fn_ = [this](DecodeBuffer* db) {\n EXPECT_EQ(1u, db->Remaining());\n EXPECT_EQ(1u, db->FullSize());\n db->DecodeUInt8();\n if (data_db_.Remaining() == 1) {\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n };\n override_stop_decode_on_done_ = true;\n sub_stop_decode_on_done_ = true;\n EXPECT_EQ(DecodeStatus::kDecodeDone, DecodeSegments(&data_db_, SelectOne()));\n EXPECT_EQ(0u, data_db_.Remaining());\n EXPECT_EQ(1u, start_decoding_calls_);\n EXPECT_EQ((sizeof kData) - 1, resume_decoding_calls_);\n EXPECT_EQ(0u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, DecodeSeveralWaysToEnd) {\n size_t decoded_since_start = 0;\n auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {\n decoded_since_start += db->Remaining();\n db->AdvanceCursor(db->Remaining());\n EXPECT_EQ(0u, db->Remaining());\n if (decoded_since_start == data_db_.FullSize()) {\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n };\n start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {\n decoded_since_start = 0;\n return shared_fn(db);\n };\n resume_decoding_fn_ = shared_fn;\n Validator validator = ValidateDoneAndEmpty();\n EXPECT_TRUE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst,\n validator));\n EXPECT_EQ(0u, data_db_.Remaining());\n EXPECT_EQ(4u, start_decoding_calls_);\n EXPECT_EQ(0u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, DecodeTwoWaysAndStopEarly) {\n size_t decoded_since_start = 0;\n auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {\n uint32_t amount = db->Remaining();\n if (start_decoding_calls_ == 2 && amount > 1) {\n amount = 1;\n }\n decoded_since_start += amount;\n db->AdvanceCursor(amount);\n if (decoded_since_start == data_db_.FullSize()) {\n return DecodeStatus::kDecodeDone;\n }\n if (decoded_since_start > 1 && start_decoding_calls_ == 2) {\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n };\n start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {\n decoded_since_start = 0;\n return shared_fn(db);\n };\n resume_decoding_fn_ = shared_fn;\n Validator validator = [this](const DecodeBuffer& ,\n DecodeStatus status) -> AssertionResult {\n if (start_decoding_calls_ <= 2 && status != DecodeStatus::kDecodeDone) {\n return ::testing::AssertionFailure()\n << \"Expected DecodeStatus::kDecodeDone, not \" << status;\n }\n if (start_decoding_calls_ > 2) {\n return ::testing::AssertionFailure()\n << \"How did we get to pass \" << start_decoding_calls_;\n }\n return ::testing::AssertionSuccess();\n };\n EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst,\n validator));\n EXPECT_EQ(2u, start_decoding_calls_);\n EXPECT_EQ(1u, stop_decode_on_done_calls_);\n}\nTEST_F(RandomDecoderTestTest, DecodeThreeWaysAndError) {\n size_t decoded_since_start = 0;\n auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {\n if (start_decoding_calls_ == 3 && decoded_since_start > 0) {\n return DecodeStatus::kDecodeError;\n }\n uint32_t amount = db->Remaining();\n if (start_decoding_calls_ == 3 && amount > 1) {\n amount = 1;\n }\n decoded_since_start += amount;\n db->AdvanceCursor(amount);\n if (decoded_since_start == data_db_.FullSize()) {\n return DecodeStatus::kDecodeDone;\n }\n return DecodeStatus::kDecodeInProgress;\n };\n start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {\n decoded_since_start = 0;\n return shared_fn(db);\n };\n resume_decoding_fn_ = shared_fn;\n Validator validator = ValidateDoneAndEmpty();\n EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kReturnNonZeroOnFirst,\n validator));\n EXPECT_EQ(3u, start_decoding_calls_);\n EXPECT_EQ(0u, stop_decode_on_done_calls_);\n}\nTEST(CorruptEnumTest, ManyValues) {\n std::set values;\n DecodeStatus status;\n QUICHE_LOG(INFO) << \"sizeof status = \" << sizeof status;\n Http2Random rng;\n for (int ndx = 0; ndx < 256; ++ndx) {\n CorruptEnum(&status, &rng);\n values.insert(static_cast(status));\n }\n}\ntypedef typename std::underlying_type::type DecodeStatusUT;\nstruct CorruptEnumTestStruct {\n DecodeStatusUT filler1;\n DecodeStatus status;\n DecodeStatusUT filler2;\n};\nTEST(CorruptEnumTest, CorruptsOnlyEnum) {\n Http2Random rng;\n for (const DecodeStatusUT filler : {DecodeStatusUT(), ~DecodeStatusUT()}) {\n QUICHE_LOG(INFO) << \"filler=0x\" << std::hex << filler;\n CorruptEnumTestStruct s;\n s.filler1 = filler;\n s.filler2 = filler;\n for (int ndx = 0; ndx < 256; ++ndx) {\n CorruptEnum(&s.status, &rng);\n EXPECT_EQ(s.filler1, filler);\n EXPECT_EQ(s.filler2, filler);\n }\n }\n}\n} \n} \n} "}}},{"rowIdx":454,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_BLIND_SIGN_AUTH_CACHED_BLIND_SIGN_AUTH_H_\n#define QUICHE_BLIND_SIGN_AUTH_CACHED_BLIND_SIGN_AUTH_H_\n#include \n#include \n#include \"absl/status/statusor.h\"\n#include \"absl/types/span.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_mutex.h\"\n#include \"quiche/common/quiche_circular_deque.h\"\nnamespace quiche {\ninline constexpr int kBlindSignAuthRequestMaxTokens = 1024;\nclass QUICHE_EXPORT CachedBlindSignAuth : public BlindSignAuthInterface {\n public:\n CachedBlindSignAuth(\n BlindSignAuthInterface* blind_sign_auth,\n int max_tokens_per_request = kBlindSignAuthRequestMaxTokens)\n : blind_sign_auth_(blind_sign_auth),\n max_tokens_per_request_(max_tokens_per_request) {}\n void GetTokens(std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback) override;\n void ClearCache() {\n QuicheWriterMutexLock lock(&mutex_);\n cached_tokens_.clear();\n }\n private:\n void HandleGetTokensResponse(\n SignedTokenCallback callback, int num_tokens,\n absl::StatusOr> tokens);\n std::vector CreateOutputTokens(int num_tokens)\n QUICHE_EXCLUSIVE_LOCKS_REQUIRED(mutex_);\n void RemoveExpiredTokens() QUICHE_EXCLUSIVE_LOCKS_REQUIRED(mutex_);\n BlindSignAuthInterface* blind_sign_auth_;\n int max_tokens_per_request_;\n QuicheMutex mutex_;\n QuicheCircularDeque cached_tokens_ QUICHE_GUARDED_BY(mutex_);\n};\n} \n#endif \n#include \"quiche/blind_sign_auth/cached_blind_sign_auth.h\"\n#include \n#include \n#include \n#include \n#include \"absl/functional/bind_front.h\"\n#include \"absl/status/status.h\"\n#include \"absl/status/statusor.h\"\n#include \"absl/strings/str_format.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"absl/types/span.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_mutex.h\"\nnamespace quiche {\nconstexpr absl::Duration kFreshnessConstant = absl::Minutes(5);\nvoid CachedBlindSignAuth::GetTokens(std::optional oauth_token,\n int num_tokens, ProxyLayer proxy_layer,\n BlindSignAuthServiceType service_type,\n SignedTokenCallback callback) {\n if (num_tokens > max_tokens_per_request_) {\n std::move(callback)(absl::InvalidArgumentError(\n absl::StrFormat(\"Number of tokens requested exceeds maximum: %d\",\n kBlindSignAuthRequestMaxTokens)));\n return;\n }\n if (num_tokens < 0) {\n std::move(callback)(absl::InvalidArgumentError(absl::StrFormat(\n \"Negative number of tokens requested: %d\", num_tokens)));\n return;\n }\n std::vector output_tokens;\n {\n QuicheWriterMutexLock lock(&mutex_);\n RemoveExpiredTokens();\n if (static_cast(num_tokens) <= cached_tokens_.size()) {\n output_tokens = CreateOutputTokens(num_tokens);\n }\n }\n if (!output_tokens.empty() || num_tokens == 0) {\n std::move(callback)(absl::MakeSpan(output_tokens));\n return;\n }\n SignedTokenCallback caching_callback =\n absl::bind_front(&CachedBlindSignAuth::HandleGetTokensResponse, this,\n std::move(callback), num_tokens);\n blind_sign_auth_->GetTokens(oauth_token, kBlindSignAuthRequestMaxTokens,\n proxy_layer, service_type,\n std::move(caching_callback));\n}\nvoid CachedBlindSignAuth::HandleGetTokensResponse(\n SignedTokenCallback callback, int num_tokens,\n absl::StatusOr> tokens) {\n if (!tokens.ok()) {\n QUICHE_LOG(WARNING) << \"BlindSignAuth::GetTokens failed: \"\n << tokens.status();\n std::move(callback)(tokens);\n return;\n }\n if (tokens->size() < static_cast(num_tokens) ||\n tokens->size() > kBlindSignAuthRequestMaxTokens) {\n QUICHE_LOG(WARNING) << \"Expected \" << num_tokens << \" tokens, got \"\n << tokens->size();\n }\n std::vector output_tokens;\n size_t cache_size;\n {\n QuicheWriterMutexLock lock(&mutex_);\n for (const BlindSignToken& token : *tokens) {\n cached_tokens_.push_back(token);\n }\n RemoveExpiredTokens();\n cache_size = cached_tokens_.size();\n if (cache_size >= static_cast(num_tokens)) {\n output_tokens = CreateOutputTokens(num_tokens);\n }\n }\n if (!output_tokens.empty()) {\n std::move(callback)(absl::MakeSpan(output_tokens));\n return;\n }\n std::move(callback)(absl::ResourceExhaustedError(absl::StrFormat(\n \"Requested %d tokens, cache only has %d after GetTokensRequest\",\n num_tokens, cache_size)));\n}\nstd::vector CachedBlindSignAuth::CreateOutputTokens(\n int num_tokens) {\n std::vector output_tokens;\n if (cached_tokens_.size() < static_cast(num_tokens)) {\n QUICHE_LOG(FATAL) << \"Check failed, not enough tokens in cache: \"\n << cached_tokens_.size() << \" < \" << num_tokens;\n }\n for (int i = 0; i < num_tokens; i++) {\n output_tokens.push_back(std::move(cached_tokens_.front()));\n cached_tokens_.pop_front();\n }\n return output_tokens;\n}\nvoid CachedBlindSignAuth::RemoveExpiredTokens() {\n size_t original_size = cached_tokens_.size();\n absl::Time now_plus_five_mins = absl::Now() + kFreshnessConstant;\n for (size_t i = 0; i < original_size; i++) {\n BlindSignToken token = std::move(cached_tokens_.front());\n cached_tokens_.pop_front();\n if (token.expiration > now_plus_five_mins) {\n cached_tokens_.push_back(std::move(token));\n }\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/blind_sign_auth/cached_blind_sign_auth.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"absl/status/status.h\"\n#include \"absl/status/statusor.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_format.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"absl/types/span.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/blind_sign_auth/test_tools/mock_blind_sign_auth_interface.h\"\n#include \"quiche/common/platform/api/quiche_mutex.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\n#include \"quiche/common/test_tools/quiche_test_utils.h\"\nnamespace quiche {\nnamespace test {\nnamespace {\nusing ::testing::_;\nusing ::testing::InvokeArgument;\nusing ::testing::Unused;\nclass CachedBlindSignAuthTest : public QuicheTest {\n protected:\n void SetUp() override {\n cached_blind_sign_auth_ =\n std::make_unique(&mock_blind_sign_auth_interface_);\n }\n void TearDown() override {\n fake_tokens_.clear();\n cached_blind_sign_auth_.reset();\n }\n public:\n std::vector MakeFakeTokens(int num_tokens) {\n std::vector fake_tokens;\n for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) {\n fake_tokens.push_back(BlindSignToken{absl::StrCat(\"token:\", i),\n absl::Now() + absl::Hours(1)});\n }\n return fake_tokens;\n }\n std::vector MakeExpiredTokens(int num_tokens) {\n std::vector fake_tokens;\n for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) {\n fake_tokens.push_back(BlindSignToken{absl::StrCat(\"token:\", i),\n absl::Now() - absl::Hours(1)});\n }\n return fake_tokens;\n }\n MockBlindSignAuthInterface mock_blind_sign_auth_interface_;\n std::unique_ptr cached_blind_sign_auth_;\n std::optional oauth_token_ = \"oauth_token\";\n std::vector fake_tokens_;\n};\nTEST_F(CachedBlindSignAuthTest, TestGetTokensOneCallSuccessful) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(1)\n .WillOnce([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeFakeTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = 5;\n QuicheNotification done;\n SignedTokenCallback callback =\n [num_tokens, &done](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i));\n }\n done.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));\n done.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensMultipleRemoteCallsSuccessful) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(2)\n .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeFakeTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens - 1;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [num_tokens, &first](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i));\n }\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n QuicheNotification second;\n SignedTokenCallback second_callback =\n [num_tokens, &second](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n EXPECT_EQ(tokens->at(0).token,\n absl::StrCat(\"token:\", kBlindSignAuthRequestMaxTokens - 1));\n for (int i = 1; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i - 1));\n }\n second.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));\n second.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensSecondRequestFilledFromCache) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(1)\n .WillOnce([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeFakeTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens / 2;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [num_tokens, &first](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i));\n }\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n QuicheNotification second;\n SignedTokenCallback second_callback =\n [num_tokens, &second](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token,\n absl::StrCat(\"token:\", i + num_tokens));\n }\n second.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));\n second.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensThirdRequestRefillsCache) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(2)\n .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeFakeTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens / 2;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [num_tokens, &first](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i));\n }\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n QuicheNotification second;\n SignedTokenCallback second_callback =\n [num_tokens, &second](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(num_tokens, tokens->size());\n for (int i = 0; i < num_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token,\n absl::StrCat(\"token:\", i + num_tokens));\n }\n second.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));\n second.WaitForNotification();\n QuicheNotification third;\n int third_request_tokens = 10;\n SignedTokenCallback third_callback =\n [third_request_tokens,\n &third](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(third_request_tokens, tokens->size());\n for (int i = 0; i < third_request_tokens; i++) {\n EXPECT_EQ(tokens->at(i).token, absl::StrCat(\"token:\", i));\n }\n third.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, third_request_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(third_callback));\n third.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensRequestTooLarge) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(0);\n int num_tokens = kBlindSignAuthRequestMaxTokens + 1;\n SignedTokenCallback callback =\n [](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);\n EXPECT_THAT(\n tokens.status().message(),\n absl::StrFormat(\"Number of tokens requested exceeds maximum: %d\",\n kBlindSignAuthRequestMaxTokens));\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensRequestNegative) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(0);\n int num_tokens = -1;\n SignedTokenCallback callback =\n [num_tokens](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);\n EXPECT_THAT(tokens.status().message(),\n absl::StrFormat(\"Negative number of tokens requested: %d\",\n num_tokens));\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));\n}\nTEST_F(CachedBlindSignAuthTest, TestHandleGetTokensResponseErrorHandling) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(2)\n .WillOnce([](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n std::move(callback)(absl::InternalError(\"AuthAndSign failed\"));\n })\n .WillOnce([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeFakeTokens(num_tokens);\n fake_tokens_.pop_back();\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [&first](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);\n EXPECT_THAT(tokens.status().message(), \"AuthAndSign failed\");\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n QuicheNotification second;\n SignedTokenCallback second_callback =\n [&second](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(),\n absl::StatusCode::kResourceExhausted);\n second.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));\n second.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestGetTokensZeroTokensRequested) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(0);\n int num_tokens = 0;\n SignedTokenCallback callback =\n [](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n EXPECT_EQ(tokens->size(), 0);\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));\n}\nTEST_F(CachedBlindSignAuthTest, TestExpiredTokensArePruned) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(1)\n .WillOnce([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeExpiredTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [&first](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(),\n absl::StatusCode::kResourceExhausted);\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n}\nTEST_F(CachedBlindSignAuthTest, TestClearCacheRemovesTokens) {\n EXPECT_CALL(mock_blind_sign_auth_interface_,\n GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))\n .Times(2)\n .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,\n SignedTokenCallback callback) {\n fake_tokens_ = MakeExpiredTokens(num_tokens);\n std::move(callback)(absl::MakeSpan(fake_tokens_));\n });\n int num_tokens = kBlindSignAuthRequestMaxTokens / 2;\n QuicheNotification first;\n SignedTokenCallback first_callback =\n [&first](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(),\n absl::StatusCode::kResourceExhausted);\n first.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));\n first.WaitForNotification();\n cached_blind_sign_auth_->ClearCache();\n QuicheNotification second;\n SignedTokenCallback second_callback =\n [&second](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(),\n absl::StatusCode::kResourceExhausted);\n second.Notify();\n };\n cached_blind_sign_auth_->GetTokens(\n oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));\n second.WaitForNotification();\n}\n} \n} \n} "}}},{"rowIdx":455,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_\n#define QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_\n#include \n#include \n#include \n#include \"absl/status/statusor.h\"\n#include \"absl/time/time.h\"\n#include \"anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h\"\n#include \"anonymous_tokens/cpp/privacy_pass/token_encodings.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_protos.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_response.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace quiche {\nclass QUICHE_EXPORT BlindSignAuth : public BlindSignAuthInterface {\n public:\n explicit BlindSignAuth(BlindSignMessageInterface* fetcher,\n privacy::ppn::BlindSignAuthOptions auth_options)\n : fetcher_(fetcher), auth_options_(std::move(auth_options)) {}\n void GetTokens(std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback) override;\n private:\n void GetInitialDataCallback(\n std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback,\n absl::StatusOr response);\n void GeneratePrivacyPassTokens(\n privacy::ppn::GetInitialDataResponse initial_data_response,\n std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback);\n void PrivacyPassAuthAndSignCallback(\n std::string encoded_extensions, absl::Time public_key_expiry_time,\n anonymous_tokens::GeoHint geo_hint,\n anonymous_tokens::AnonymousTokensUseCase use_case,\n std::vector>\n privacy_pass_clients,\n SignedTokenCallback callback,\n absl::StatusOr response);\n privacy::ppn::ProxyLayer QuicheProxyLayerToPpnProxyLayer(\n quiche::ProxyLayer proxy_layer);\n BlindSignMessageInterface* fetcher_ = nullptr;\n privacy::ppn::BlindSignAuthOptions auth_options_;\n};\nstd::string BlindSignAuthServiceTypeToString(\n quiche::BlindSignAuthServiceType service_type);\n} \n#endif \n#include \"quiche/blind_sign_auth/blind_sign_auth.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"absl/functional/bind_front.h\"\n#include \"absl/status/status.h\"\n#include \"absl/status/statusor.h\"\n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"absl/types/span.h\"\n#include \"anonymous_tokens/cpp/crypto/crypto_utils.h\"\n#include \"anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h\"\n#include \"anonymous_tokens/cpp/privacy_pass/token_encodings.h\"\n#include \"anonymous_tokens/cpp/shared/proto_utils.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_protos.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_response.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/quiche_random.h\"\nnamespace quiche {\nnamespace {\ntemplate \nstd::string OmitDefault(T value) {\n return value == 0 ? \"\" : absl::StrCat(value);\n}\nconstexpr absl::string_view kIssuerHostname =\n \"https:\n} \nvoid BlindSignAuth::GetTokens(std::optional oauth_token,\n int num_tokens, ProxyLayer proxy_layer,\n BlindSignAuthServiceType service_type,\n SignedTokenCallback callback) {\n privacy::ppn::GetInitialDataRequest request;\n request.set_use_attestation(false);\n request.set_service_type(BlindSignAuthServiceTypeToString(service_type));\n request.set_location_granularity(\n privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);\n request.set_validation_version(2);\n request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));\n std::string body = request.SerializeAsString();\n BlindSignMessageCallback initial_data_callback = absl::bind_front(\n &BlindSignAuth::GetInitialDataCallback, this, oauth_token, num_tokens,\n proxy_layer, service_type, std::move(callback));\n fetcher_->DoRequest(BlindSignMessageRequestType::kGetInitialData, oauth_token,\n body, std::move(initial_data_callback));\n}\nvoid BlindSignAuth::GetInitialDataCallback(\n std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback,\n absl::StatusOr response) {\n if (!response.ok()) {\n QUICHE_LOG(WARNING) << \"GetInitialDataRequest failed: \"\n << response.status();\n std::move(callback)(response.status());\n return;\n }\n absl::StatusCode code = response->status_code();\n if (code != absl::StatusCode::kOk) {\n std::string message =\n absl::StrCat(\"GetInitialDataRequest failed with code: \", code);\n QUICHE_LOG(WARNING) << message;\n std::move(callback)(absl::Status(code, message));\n return;\n }\n privacy::ppn::GetInitialDataResponse initial_data_response;\n if (!initial_data_response.ParseFromString(response->body())) {\n QUICHE_LOG(WARNING) << \"Failed to parse GetInitialDataResponse\";\n std::move(callback)(\n absl::InternalError(\"Failed to parse GetInitialDataResponse\"));\n return;\n }\n bool use_privacy_pass_client =\n initial_data_response.has_privacy_pass_data() &&\n auth_options_.enable_privacy_pass();\n if (use_privacy_pass_client) {\n QUICHE_DVLOG(1) << \"Using Privacy Pass client\";\n GeneratePrivacyPassTokens(initial_data_response, std::move(oauth_token),\n num_tokens, proxy_layer, service_type,\n std::move(callback));\n } else {\n QUICHE_LOG(ERROR) << \"Non-Privacy Pass tokens are no longer supported\";\n std::move(callback)(absl::UnimplementedError(\n \"Non-Privacy Pass tokens are no longer supported\"));\n }\n}\nvoid BlindSignAuth::GeneratePrivacyPassTokens(\n privacy::ppn::GetInitialDataResponse initial_data_response,\n std::optional oauth_token, int num_tokens,\n ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,\n SignedTokenCallback callback) {\n anonymous_tokens::RSAPublicKey public_key_proto;\n if (!public_key_proto.ParseFromString(\n initial_data_response.at_public_metadata_public_key()\n .serialized_public_key())) {\n std::move(callback)(\n absl::InvalidArgumentError(\"Failed to parse Privacy Pass public key\"));\n return;\n }\n absl::StatusOr> bssl_rsa_key =\n anonymous_tokens::CreatePublicKeyRSA(\n public_key_proto.n(), public_key_proto.e());\n if (!bssl_rsa_key.ok()) {\n std::move(callback)(bssl_rsa_key.status());\n return;\n }\n absl::StatusOr extensions =\n anonymous_tokens::DecodeExtensions(\n initial_data_response.privacy_pass_data()\n .public_metadata_extensions());\n if (!extensions.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to decode extensions: \"\n << extensions.status();\n std::move(callback)(extensions.status());\n return;\n }\n std::vector kExpectedExtensionTypes = {\n 0x0001, 0x0002,\n 0xF001, 0xF002, 0xF003};\n absl::Status result =\n anonymous_tokens::ValidateExtensionsOrderAndValues(\n *extensions, absl::MakeSpan(kExpectedExtensionTypes), absl::Now());\n if (!result.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to validate extensions: \" << result;\n std::move(callback)(result);\n return;\n }\n absl::StatusOr\n expiration_timestamp = anonymous_tokens::\n ExpirationTimestamp::FromExtension(extensions->extensions.at(0));\n if (!expiration_timestamp.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to parse expiration timestamp: \"\n << expiration_timestamp.status();\n std::move(callback)(expiration_timestamp.status());\n return;\n }\n absl::Time public_metadata_expiry_time =\n absl::FromUnixSeconds(expiration_timestamp->timestamp);\n absl::StatusOr geo_hint =\n anonymous_tokens::GeoHint::FromExtension(\n extensions->extensions.at(1));\n QUICHE_CHECK(geo_hint.ok());\n anonymous_tokens::TokenChallenge challenge;\n challenge.issuer_name = kIssuerHostname;\n absl::StatusOr token_challenge =\n anonymous_tokens::MarshalTokenChallenge(challenge);\n if (!token_challenge.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to marshal token challenge: \"\n << token_challenge.status();\n std::move(callback)(token_challenge.status());\n return;\n }\n QuicheRandom* random = QuicheRandom::GetInstance();\n std::vector\n extended_token_requests;\n std::vector>\n privacy_pass_clients;\n std::vector privacy_pass_blinded_tokens;\n for (int i = 0; i < num_tokens; i++) {\n auto client = anonymous_tokens::\n PrivacyPassRsaBssaPublicMetadataClient::Create(*bssl_rsa_key.value());\n if (!client.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to create Privacy Pass client: \"\n << client.status();\n std::move(callback)(client.status());\n return;\n }\n std::string nonce_rand(32, '\\0');\n random->RandBytes(nonce_rand.data(), nonce_rand.size());\n absl::StatusOr\n extended_token_request = client.value()->CreateTokenRequest(\n *token_challenge, nonce_rand,\n initial_data_response.privacy_pass_data().token_key_id(),\n *extensions);\n if (!extended_token_request.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to create ExtendedTokenRequest: \"\n << extended_token_request.status();\n std::move(callback)(extended_token_request.status());\n return;\n }\n privacy_pass_clients.push_back(*std::move(client));\n extended_token_requests.push_back(*extended_token_request);\n privacy_pass_blinded_tokens.push_back(absl::Base64Escape(\n extended_token_request->request.blinded_token_request));\n }\n privacy::ppn::AuthAndSignRequest sign_request;\n sign_request.set_service_type(BlindSignAuthServiceTypeToString(service_type));\n sign_request.set_key_type(privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);\n sign_request.set_key_version(\n initial_data_response.at_public_metadata_public_key().key_version());\n sign_request.mutable_blinded_token()->Assign(\n privacy_pass_blinded_tokens.begin(), privacy_pass_blinded_tokens.end());\n sign_request.mutable_public_metadata_extensions()->assign(\n initial_data_response.privacy_pass_data().public_metadata_extensions());\n sign_request.set_do_not_use_rsa_public_exponent(true);\n sign_request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));\n absl::StatusOr\n use_case = anonymous_tokens::ParseUseCase(\n initial_data_response.at_public_metadata_public_key().use_case());\n if (!use_case.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to parse use case: \" << use_case.status();\n std::move(callback)(use_case.status());\n return;\n }\n BlindSignMessageCallback auth_and_sign_callback =\n absl::bind_front(&BlindSignAuth::PrivacyPassAuthAndSignCallback, this,\n std::move(initial_data_response.privacy_pass_data()\n .public_metadata_extensions()),\n public_metadata_expiry_time, *geo_hint, *use_case,\n std::move(privacy_pass_clients), std::move(callback));\n fetcher_->DoRequest(BlindSignMessageRequestType::kAuthAndSign, oauth_token,\n sign_request.SerializeAsString(),\n std::move(auth_and_sign_callback));\n}\nvoid BlindSignAuth::PrivacyPassAuthAndSignCallback(\n std::string encoded_extensions, absl::Time public_key_expiry_time,\n anonymous_tokens::GeoHint geo_hint,\n anonymous_tokens::AnonymousTokensUseCase use_case,\n std::vector>\n privacy_pass_clients,\n SignedTokenCallback callback,\n absl::StatusOr response) {\n if (!response.ok()) {\n QUICHE_LOG(WARNING) << \"AuthAndSign failed: \" << response.status();\n std::move(callback)(response.status());\n return;\n }\n absl::StatusCode code = response->status_code();\n if (code != absl::StatusCode::kOk) {\n std::string message = absl::StrCat(\"AuthAndSign failed with code: \", code);\n QUICHE_LOG(WARNING) << message;\n std::move(callback)(absl::Status(code, message));\n return;\n }\n privacy::ppn::AuthAndSignResponse sign_response;\n if (!sign_response.ParseFromString(response->body())) {\n QUICHE_LOG(WARNING) << \"Failed to parse AuthAndSignResponse\";\n std::move(callback)(\n absl::InternalError(\"Failed to parse AuthAndSignResponse\"));\n return;\n }\n if (static_cast(sign_response.blinded_token_signature_size()) !=\n privacy_pass_clients.size()) {\n QUICHE_LOG(WARNING) << \"Number of signatures does not equal number of \"\n \"Privacy Pass tokens sent\";\n std::move(callback)(\n absl::InternalError(\"Number of signatures does not equal number of \"\n \"Privacy Pass tokens sent\"));\n return;\n }\n std::vector tokens_vec;\n for (int i = 0; i < sign_response.blinded_token_signature_size(); i++) {\n std::string unescaped_blinded_sig;\n if (!absl::Base64Unescape(sign_response.blinded_token_signature()[i],\n &unescaped_blinded_sig)) {\n QUICHE_LOG(WARNING) << \"Failed to unescape blinded signature\";\n std::move(callback)(\n absl::InternalError(\"Failed to unescape blinded signature\"));\n return;\n }\n absl::StatusOr token =\n privacy_pass_clients[i]->FinalizeToken(unescaped_blinded_sig);\n if (!token.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to finalize token: \" << token.status();\n std::move(callback)(token.status());\n return;\n }\n absl::StatusOr marshaled_token =\n anonymous_tokens::MarshalToken(*token);\n if (!marshaled_token.ok()) {\n QUICHE_LOG(WARNING) << \"Failed to marshal token: \"\n << marshaled_token.status();\n std::move(callback)(marshaled_token.status());\n return;\n }\n privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;\n privacy_pass_token_data.mutable_token()->assign(\n absl::WebSafeBase64Escape(*marshaled_token));\n privacy_pass_token_data.mutable_encoded_extensions()->assign(\n absl::WebSafeBase64Escape(encoded_extensions));\n privacy_pass_token_data.set_use_case_override(use_case);\n tokens_vec.push_back(\n BlindSignToken{privacy_pass_token_data.SerializeAsString(),\n public_key_expiry_time, geo_hint});\n }\n std::move(callback)(absl::Span(tokens_vec));\n}\nprivacy::ppn::ProxyLayer BlindSignAuth::QuicheProxyLayerToPpnProxyLayer(\n quiche::ProxyLayer proxy_layer) {\n switch (proxy_layer) {\n case ProxyLayer::kProxyA: {\n return privacy::ppn::ProxyLayer::PROXY_A;\n }\n case ProxyLayer::kProxyB: {\n return privacy::ppn::ProxyLayer::PROXY_B;\n }\n }\n}\nstd::string BlindSignAuthServiceTypeToString(\n quiche::BlindSignAuthServiceType service_type) {\n switch (service_type) {\n case BlindSignAuthServiceType::kChromeIpBlinding: {\n return \"chromeipblinding\";\n }\n case BlindSignAuthServiceType::kCronetIpBlinding: {\n return \"cronetipblinding\";\n }\n case BlindSignAuthServiceType::kWebviewIpBlinding: {\n return \"chromeipblinding\";\n }\n }\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/blind_sign_auth/blind_sign_auth.h\"\n#include \n#include \n#include \n#include \n#include \"absl/status/status.h\"\n#include \"absl/status/statusor.h\"\n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"absl/types/span.h\"\n#include \"anonymous_tokens/cpp/crypto/crypto_utils.h\"\n#include \"anonymous_tokens/cpp/privacy_pass/token_encodings.h\"\n#include \"anonymous_tokens/cpp/testing/utils.h\"\n#include \"openssl/base.h\"\n#include \"openssl/digest.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_auth_protos.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_interface.h\"\n#include \"quiche/blind_sign_auth/blind_sign_message_response.h\"\n#include \"quiche/blind_sign_auth/test_tools/mock_blind_sign_message_interface.h\"\n#include \"quiche/common/platform/api/quiche_mutex.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\n#include \"quiche/common/test_tools/quiche_test_utils.h\"\nnamespace quiche {\nnamespace test {\nnamespace {\nusing ::testing::_;\nusing ::testing::Eq;\nusing ::testing::InSequence;\nusing ::testing::Invoke;\nusing ::testing::StartsWith;\nusing ::testing::Unused;\nclass BlindSignAuthTest : public QuicheTest {\n protected:\n void SetUp() override {\n auto [test_rsa_public_key, test_rsa_private_key] =\n anonymous_tokens::GetStrongTestRsaKeyPair2048();\n ANON_TOKENS_ASSERT_OK_AND_ASSIGN(\n rsa_public_key_,\n anonymous_tokens::CreatePublicKeyRSA(\n test_rsa_public_key.n, test_rsa_public_key.e));\n ANON_TOKENS_ASSERT_OK_AND_ASSIGN(\n rsa_private_key_,\n anonymous_tokens::CreatePrivateKeyRSA(\n test_rsa_private_key.n, test_rsa_private_key.e,\n test_rsa_private_key.d, test_rsa_private_key.p,\n test_rsa_private_key.q, test_rsa_private_key.dp,\n test_rsa_private_key.dq, test_rsa_private_key.crt));\n anonymous_tokens::RSAPublicKey public_key;\n public_key.set_n(test_rsa_public_key.n);\n public_key.set_e(test_rsa_public_key.e);\n public_key_proto_.set_key_version(1);\n public_key_proto_.set_use_case(\"TEST_USE_CASE\");\n public_key_proto_.set_serialized_public_key(public_key.SerializeAsString());\n public_key_proto_.set_sig_hash_type(\n anonymous_tokens::AT_HASH_TYPE_SHA384);\n public_key_proto_.set_mask_gen_function(\n anonymous_tokens::AT_MGF_SHA384);\n public_key_proto_.set_salt_length(48);\n public_key_proto_.set_key_size(256);\n public_key_proto_.set_message_mask_type(\n anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);\n public_key_proto_.set_message_mask_size(0);\n expected_get_initial_data_request_.set_use_attestation(false);\n expected_get_initial_data_request_.set_service_type(\"chromeipblinding\");\n expected_get_initial_data_request_.set_location_granularity(\n privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);\n expected_get_initial_data_request_.set_validation_version(2);\n expected_get_initial_data_request_.set_proxy_layer(privacy::ppn::PROXY_A);\n privacy::ppn::GetInitialDataResponse fake_get_initial_data_response;\n *fake_get_initial_data_response.mutable_at_public_metadata_public_key() =\n public_key_proto_;\n fake_get_initial_data_response_ = fake_get_initial_data_response;\n privacy::ppn::GetInitialDataResponse::PrivacyPassData privacy_pass_data;\n ANON_TOKENS_ASSERT_OK_AND_ASSIGN(\n std::string public_key_der,\n anonymous_tokens::RsaSsaPssPublicKeyToDerEncoding(\n rsa_public_key_.get()));\n const EVP_MD* sha256 = EVP_sha256();\n ANON_TOKENS_ASSERT_OK_AND_ASSIGN(\n token_key_id_, anonymous_tokens::ComputeHash(\n public_key_der, *sha256));\n anonymous_tokens::ExpirationTimestamp\n expiration_timestamp;\n int64_t one_hour_away = absl::ToUnixSeconds(absl::Now() + absl::Hours(1));\n expiration_timestamp.timestamp = one_hour_away - (one_hour_away % 900);\n expiration_timestamp.timestamp_precision = 900;\n absl::StatusOr\n expiration_extension = expiration_timestamp.AsExtension();\n QUICHE_EXPECT_OK(expiration_extension);\n extensions_.extensions.push_back(*expiration_extension);\n anonymous_tokens::GeoHint geo_hint;\n geo_hint.geo_hint = \"US,US-AL,ALABASTER\";\n absl::StatusOr\n geo_hint_extension = geo_hint.AsExtension();\n QUICHE_EXPECT_OK(geo_hint_extension);\n extensions_.extensions.push_back(*geo_hint_extension);\n anonymous_tokens::ServiceType service_type;\n service_type.service_type_id =\n anonymous_tokens::ServiceType::kChromeIpBlinding;\n absl::StatusOr\n service_type_extension = service_type.AsExtension();\n QUICHE_EXPECT_OK(service_type_extension);\n extensions_.extensions.push_back(*service_type_extension);\n anonymous_tokens::DebugMode debug_mode;\n debug_mode.mode = anonymous_tokens::DebugMode::kDebug;\n absl::StatusOr\n debug_mode_extension = debug_mode.AsExtension();\n QUICHE_EXPECT_OK(debug_mode_extension);\n extensions_.extensions.push_back(*debug_mode_extension);\n anonymous_tokens::ProxyLayer proxy_layer;\n proxy_layer.layer =\n anonymous_tokens::ProxyLayer::kProxyA;\n absl::StatusOr\n proxy_layer_extension = proxy_layer.AsExtension();\n QUICHE_EXPECT_OK(proxy_layer_extension);\n extensions_.extensions.push_back(*proxy_layer_extension);\n absl::StatusOr serialized_extensions =\n anonymous_tokens::EncodeExtensions(extensions_);\n QUICHE_EXPECT_OK(serialized_extensions);\n privacy_pass_data.set_token_key_id(token_key_id_);\n privacy_pass_data.set_public_metadata_extensions(*serialized_extensions);\n *fake_get_initial_data_response.mutable_public_metadata_info() =\n public_metadata_info_;\n *fake_get_initial_data_response.mutable_privacy_pass_data() =\n privacy_pass_data;\n fake_get_initial_data_response_ = fake_get_initial_data_response;\n privacy::ppn::BlindSignAuthOptions options;\n options.set_enable_privacy_pass(true);\n blind_sign_auth_ =\n std::make_unique(&mock_message_interface_, options);\n }\n void TearDown() override { blind_sign_auth_.reset(nullptr); }\n public:\n void CreateSignResponse(const std::string& body, bool use_privacy_pass) {\n privacy::ppn::AuthAndSignRequest request;\n ASSERT_TRUE(request.ParseFromString(body));\n EXPECT_EQ(request.service_type(), \"chromeipblinding\");\n EXPECT_EQ(request.key_type(), privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);\n EXPECT_EQ(request.public_key_hash(), \"\");\n EXPECT_EQ(request.key_version(), public_key_proto_.key_version());\n EXPECT_EQ(request.do_not_use_rsa_public_exponent(), true);\n EXPECT_NE(request.blinded_token().size(), 0);\n if (use_privacy_pass) {\n EXPECT_EQ(request.public_metadata_extensions(),\n fake_get_initial_data_response_.privacy_pass_data()\n .public_metadata_extensions());\n } else {\n EXPECT_EQ(request.public_metadata_info().SerializeAsString(),\n public_metadata_info_.SerializeAsString());\n }\n privacy::ppn::AuthAndSignResponse response;\n for (const auto& request_token : request.blinded_token()) {\n std::string decoded_blinded_token;\n ASSERT_TRUE(absl::Base64Unescape(request_token, &decoded_blinded_token));\n if (use_privacy_pass) {\n absl::StatusOr signature =\n anonymous_tokens::TestSignWithPublicMetadata(\n decoded_blinded_token, request.public_metadata_extensions(),\n *rsa_private_key_, false);\n QUICHE_EXPECT_OK(signature);\n response.add_blinded_token_signature(absl::Base64Escape(*signature));\n } else {\n absl::StatusOr serialized_token =\n anonymous_tokens::TestSign(\n decoded_blinded_token, rsa_private_key_.get());\n QUICHE_EXPECT_OK(serialized_token);\n response.add_blinded_token_signature(\n absl::Base64Escape(*serialized_token));\n }\n }\n sign_response_ = response;\n }\n void ValidateGetTokensOutput(absl::Span tokens) {\n for (const auto& token : tokens) {\n privacy::ppn::SpendTokenData spend_token_data;\n ASSERT_TRUE(spend_token_data.ParseFromString(token.token));\n EXPECT_EQ(spend_token_data.public_metadata().SerializeAsString(),\n public_metadata_info_.public_metadata().SerializeAsString());\n EXPECT_THAT(spend_token_data.unblinded_token(), StartsWith(\"blind:\"));\n EXPECT_GE(spend_token_data.unblinded_token_signature().size(),\n spend_token_data.unblinded_token().size());\n EXPECT_EQ(spend_token_data.signing_key_version(),\n public_key_proto_.key_version());\n EXPECT_NE(spend_token_data.use_case(),\n anonymous_tokens::AnonymousTokensUseCase::\n ANONYMOUS_TOKENS_USE_CASE_UNDEFINED);\n EXPECT_NE(spend_token_data.message_mask(), \"\");\n }\n }\n void ValidatePrivacyPassTokensOutput(absl::Span tokens) {\n for (const auto& token : tokens) {\n privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;\n ASSERT_TRUE(privacy_pass_token_data.ParseFromString(token.token));\n std::string decoded_token;\n ASSERT_TRUE(absl::WebSafeBase64Unescape(privacy_pass_token_data.token(),\n &decoded_token));\n std::string decoded_extensions;\n ASSERT_TRUE(absl::WebSafeBase64Unescape(\n privacy_pass_token_data.encoded_extensions(), &decoded_extensions));\n EXPECT_EQ(token.geo_hint.geo_hint, \"US,US-AL,ALABASTER\");\n EXPECT_EQ(token.geo_hint.country_code, \"US\");\n EXPECT_EQ(token.geo_hint.region, \"US-AL\");\n EXPECT_EQ(token.geo_hint.city, \"ALABASTER\");\n }\n }\n MockBlindSignMessageInterface mock_message_interface_;\n std::unique_ptr blind_sign_auth_;\n anonymous_tokens::RSABlindSignaturePublicKey\n public_key_proto_;\n bssl::UniquePtr rsa_public_key_;\n bssl::UniquePtr rsa_private_key_;\n std::string token_key_id_;\n anonymous_tokens::Extensions extensions_;\n privacy::ppn::PublicMetadataInfo public_metadata_info_;\n privacy::ppn::AuthAndSignResponse sign_response_;\n privacy::ppn::GetInitialDataResponse fake_get_initial_data_response_;\n std::string oauth_token_ = \"oauth_token\";\n privacy::ppn::GetInitialDataRequest expected_get_initial_data_request_;\n};\nTEST_F(BlindSignAuthTest, TestGetTokensFailedNetworkError) {\n EXPECT_CALL(mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),\n Eq(oauth_token_), _, _))\n .Times(1)\n .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {\n std::move(get_initial_data_cb)(\n absl::InternalError(\"Failed to create socket\"));\n });\n EXPECT_CALL(mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))\n .Times(0);\n int num_tokens = 1;\n QuicheNotification done;\n SignedTokenCallback callback =\n [&done](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);\n done.Notify();\n };\n blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding,\n std::move(callback));\n done.WaitForNotification();\n}\nTEST_F(BlindSignAuthTest, TestGetTokensFailedBadGetInitialDataResponse) {\n *fake_get_initial_data_response_.mutable_at_public_metadata_public_key()\n ->mutable_use_case() = \"SPAM\";\n BlindSignMessageResponse fake_public_key_response(\n absl::StatusCode::kOk,\n fake_get_initial_data_response_.SerializeAsString());\n EXPECT_CALL(\n mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),\n Eq(oauth_token_),\n Eq(expected_get_initial_data_request_.SerializeAsString()), _))\n .Times(1)\n .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {\n std::move(get_initial_data_cb)(fake_public_key_response);\n });\n EXPECT_CALL(mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))\n .Times(0);\n int num_tokens = 1;\n QuicheNotification done;\n SignedTokenCallback callback =\n [&done](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);\n done.Notify();\n };\n blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding,\n std::move(callback));\n done.WaitForNotification();\n}\nTEST_F(BlindSignAuthTest, TestGetTokensFailedBadAuthAndSignResponse) {\n BlindSignMessageResponse fake_public_key_response(\n absl::StatusCode::kOk,\n fake_get_initial_data_response_.SerializeAsString());\n {\n InSequence seq;\n EXPECT_CALL(\n mock_message_interface_,\n DoRequest(\n Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),\n Eq(expected_get_initial_data_request_.SerializeAsString()), _))\n .Times(1)\n .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {\n std::move(get_initial_data_cb)(fake_public_key_response);\n });\n EXPECT_CALL(mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),\n Eq(oauth_token_), _, _))\n .Times(1)\n .WillOnce(Invoke([this](Unused, Unused, const std::string& body,\n BlindSignMessageCallback callback) {\n CreateSignResponse(body, false);\n sign_response_.add_blinded_token_signature(\"invalid_signature%\");\n BlindSignMessageResponse response(absl::StatusCode::kOk,\n sign_response_.SerializeAsString());\n std::move(callback)(response);\n }));\n }\n int num_tokens = 1;\n QuicheNotification done;\n SignedTokenCallback callback =\n [&done](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);\n done.Notify();\n };\n blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding,\n std::move(callback));\n done.WaitForNotification();\n}\nTEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensSucceeds) {\n BlindSignMessageResponse fake_public_key_response(\n absl::StatusCode::kOk,\n fake_get_initial_data_response_.SerializeAsString());\n {\n InSequence seq;\n EXPECT_CALL(\n mock_message_interface_,\n DoRequest(\n Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),\n Eq(expected_get_initial_data_request_.SerializeAsString()), _))\n .Times(1)\n .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {\n std::move(get_initial_data_cb)(fake_public_key_response);\n });\n EXPECT_CALL(mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),\n Eq(oauth_token_), _, _))\n .Times(1)\n .WillOnce(Invoke([this](Unused, Unused, const std::string& body,\n BlindSignMessageCallback callback) {\n CreateSignResponse(body, true);\n BlindSignMessageResponse response(absl::StatusCode::kOk,\n sign_response_.SerializeAsString());\n std::move(callback)(response);\n }));\n }\n int num_tokens = 1;\n QuicheNotification done;\n SignedTokenCallback callback =\n [this, &done](absl::StatusOr> tokens) {\n QUICHE_EXPECT_OK(tokens);\n ValidatePrivacyPassTokensOutput(*tokens);\n done.Notify();\n };\n blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding,\n std::move(callback));\n done.WaitForNotification();\n}\nTEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensFailsWithBadExtensions) {\n privacy::ppn::BlindSignAuthOptions options;\n options.set_enable_privacy_pass(true);\n blind_sign_auth_ =\n std::make_unique(&mock_message_interface_, options);\n public_key_proto_.set_message_mask_type(\n anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);\n public_key_proto_.set_message_mask_size(0);\n *fake_get_initial_data_response_.mutable_at_public_metadata_public_key() =\n public_key_proto_;\n fake_get_initial_data_response_.mutable_privacy_pass_data()\n ->set_public_metadata_extensions(\"spam\");\n BlindSignMessageResponse fake_public_key_response(\n absl::StatusCode::kOk,\n fake_get_initial_data_response_.SerializeAsString());\n EXPECT_CALL(\n mock_message_interface_,\n DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),\n Eq(oauth_token_),\n Eq(expected_get_initial_data_request_.SerializeAsString()), _))\n .Times(1)\n .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {\n std::move(get_initial_data_cb)(fake_public_key_response);\n });\n int num_tokens = 1;\n QuicheNotification done;\n SignedTokenCallback callback =\n [&done](absl::StatusOr> tokens) {\n EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);\n done.Notify();\n };\n blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,\n BlindSignAuthServiceType::kChromeIpBlinding,\n std::move(callback));\n done.WaitForNotification();\n}\n} \n} \n} "}}},{"rowIdx":456,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_BALSA_HEADER_PROPERTIES_H_\n#define QUICHE_BALSA_HEADER_PROPERTIES_H_\n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace quiche::header_properties {\nQUICHE_EXPORT bool IsMultivaluedHeader(absl::string_view header);\ninline constexpr char kInvalidHeaderKeyCharList[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,\n 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13,\n 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,\n 0x1E, 0x1F, ' ', '\"', '(', ')', ',', '/', ';', '<',\n '=', '>', '?', '@', '[', '\\\\', ']', '{', '}', 0x7F};\ninline constexpr char kInvalidHeaderKeyCharListAllowDoubleQuote[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,\n 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13,\n 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,\n 0x1E, 0x1F, ' ', '(', ')', ',', '/', ';', '<', '=',\n '>', '?', '@', '[', '\\\\', ']', '{', '}', 0x7F};\ninline constexpr char kInvalidHeaderCharList[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0B,\n 0x0C, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,\n 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x7F};\nQUICHE_EXPORT bool IsInvalidHeaderKeyChar(uint8_t c);\nQUICHE_EXPORT bool IsInvalidHeaderKeyCharAllowDoubleQuote(uint8_t c);\nQUICHE_EXPORT bool IsInvalidHeaderChar(uint8_t c);\nQUICHE_EXPORT bool HasInvalidHeaderChars(absl::string_view value);\n} \n#endif \n#include \"quiche/balsa/header_properties.h\"\n#include \n#include \"absl/container/flat_hash_set.h\"\n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/quiche_text_utils.h\"\nnamespace quiche::header_properties {\nnamespace {\nusing MultivaluedHeadersSet =\n absl::flat_hash_set;\nMultivaluedHeadersSet* buildMultivaluedHeaders() {\n return new MultivaluedHeadersSet({\n \"accept\",\n \"accept-charset\",\n \"accept-encoding\",\n \"accept-language\",\n \"accept-ranges\",\n \"access-control-allow-headers\",\n \"access-control-allow-methods\",\n \"access-control-expose-headers\",\n \"access-control-request-headers\",\n \"allow\",\n \"cache-control\",\n \"cdn-cache-control\",\n \"connection\",\n \"content-encoding\",\n \"content-language\",\n \"expect\",\n \"if-match\",\n \"if-none-match\",\n \"link\",\n \"pragma\",\n \"proxy-authenticate\",\n \"te\",\n \"sec-websocket-extensions\",\n \"set-cookie\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"vary\",\n \"via\",\n \"warning\",\n \"www-authenticate\",\n \"x-forwarded-for\",\n \"x-go\" \"ogle-cache-control\",\n });\n}\nstd::array buildInvalidHeaderKeyCharLookupTable() {\n std::array invalidCharTable;\n invalidCharTable.fill(false);\n for (uint8_t c : kInvalidHeaderKeyCharList) {\n invalidCharTable[c] = true;\n }\n return invalidCharTable;\n}\nstd::array buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote() {\n std::array invalidCharTable;\n invalidCharTable.fill(false);\n for (uint8_t c : kInvalidHeaderKeyCharListAllowDoubleQuote) {\n invalidCharTable[c] = true;\n }\n return invalidCharTable;\n}\nstd::array buildInvalidCharLookupTable() {\n std::array invalidCharTable;\n invalidCharTable.fill(false);\n for (uint8_t c : kInvalidHeaderCharList) {\n invalidCharTable[c] = true;\n }\n return invalidCharTable;\n}\n} \nbool IsMultivaluedHeader(absl::string_view header) {\n static const MultivaluedHeadersSet* const multivalued_headers =\n buildMultivaluedHeaders();\n return multivalued_headers->contains(header);\n}\nbool IsInvalidHeaderKeyChar(uint8_t c) {\n static const std::array invalidHeaderKeyCharTable =\n buildInvalidHeaderKeyCharLookupTable();\n return invalidHeaderKeyCharTable[c];\n}\nbool IsInvalidHeaderKeyCharAllowDoubleQuote(uint8_t c) {\n static const std::array invalidHeaderKeyCharTable =\n buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote();\n return invalidHeaderKeyCharTable[c];\n}\nbool IsInvalidHeaderChar(uint8_t c) {\n static const std::array invalidCharTable =\n buildInvalidCharLookupTable();\n return invalidCharTable[c];\n}\nbool HasInvalidHeaderChars(absl::string_view value) {\n for (const char c : value) {\n if (IsInvalidHeaderChar(c)) {\n return true;\n }\n }\n return false;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/balsa/header_properties.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace quiche::header_properties::test {\nnamespace {\nTEST(HeaderPropertiesTest, IsMultivaluedHeaderIsCaseInsensitive) {\n EXPECT_TRUE(IsMultivaluedHeader(\"content-encoding\"));\n EXPECT_TRUE(IsMultivaluedHeader(\"Content-Encoding\"));\n EXPECT_TRUE(IsMultivaluedHeader(\"set-cookie\"));\n EXPECT_TRUE(IsMultivaluedHeader(\"sEt-cOOkie\"));\n EXPECT_TRUE(IsMultivaluedHeader(\"X-Goo\" \"gle-Cache-Control\"));\n EXPECT_TRUE(IsMultivaluedHeader(\"access-control-expose-HEADERS\"));\n EXPECT_FALSE(IsMultivaluedHeader(\"set-cook\"));\n EXPECT_FALSE(IsMultivaluedHeader(\"content-length\"));\n EXPECT_FALSE(IsMultivaluedHeader(\"Content-Length\"));\n}\nTEST(HeaderPropertiesTest, IsInvalidHeaderKeyChar) {\n EXPECT_TRUE(IsInvalidHeaderKeyChar(0x00));\n EXPECT_TRUE(IsInvalidHeaderKeyChar(0x06));\n EXPECT_TRUE(IsInvalidHeaderKeyChar(0x09));\n EXPECT_TRUE(IsInvalidHeaderKeyChar(0x1F));\n EXPECT_TRUE(IsInvalidHeaderKeyChar(0x7F));\n EXPECT_TRUE(IsInvalidHeaderKeyChar(' '));\n EXPECT_TRUE(IsInvalidHeaderKeyChar('\"'));\n EXPECT_TRUE(IsInvalidHeaderKeyChar('\\t'));\n EXPECT_TRUE(IsInvalidHeaderKeyChar('\\r'));\n EXPECT_TRUE(IsInvalidHeaderKeyChar('\\n'));\n EXPECT_TRUE(IsInvalidHeaderKeyChar('}'));\n EXPECT_FALSE(IsInvalidHeaderKeyChar('a'));\n EXPECT_FALSE(IsInvalidHeaderKeyChar('B'));\n EXPECT_FALSE(IsInvalidHeaderKeyChar('7'));\n EXPECT_FALSE(IsInvalidHeaderKeyChar(0x42));\n EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7C));\n EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7E));\n}\nTEST(HeaderPropertiesTest, IsInvalidHeaderKeyCharAllowDoubleQuote) {\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x00));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x06));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x09));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x1F));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7F));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(' '));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\\t'));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\\r'));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\\n'));\n EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('}'));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('\"'));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('a'));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('B'));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('7'));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x42));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7C));\n EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7E));\n}\nTEST(HeaderPropertiesTest, IsInvalidHeaderChar) {\n EXPECT_TRUE(IsInvalidHeaderChar(0x00));\n EXPECT_TRUE(IsInvalidHeaderChar(0x06));\n EXPECT_TRUE(IsInvalidHeaderChar(0x1F));\n EXPECT_TRUE(IsInvalidHeaderChar(0x7F));\n EXPECT_FALSE(IsInvalidHeaderChar(0x09));\n EXPECT_FALSE(IsInvalidHeaderChar(' '));\n EXPECT_FALSE(IsInvalidHeaderChar('\\t'));\n EXPECT_FALSE(IsInvalidHeaderChar('\\r'));\n EXPECT_FALSE(IsInvalidHeaderChar('\\n'));\n EXPECT_FALSE(IsInvalidHeaderChar('a'));\n EXPECT_FALSE(IsInvalidHeaderChar('B'));\n EXPECT_FALSE(IsInvalidHeaderChar('7'));\n EXPECT_FALSE(IsInvalidHeaderChar(0x42));\n EXPECT_FALSE(IsInvalidHeaderChar(0x7D));\n}\nTEST(HeaderPropertiesTest, KeyMoreRestrictiveThanValue) {\n for (int c = 0; c < 255; ++c) {\n if (IsInvalidHeaderChar(c)) {\n EXPECT_TRUE(IsInvalidHeaderKeyChar(c)) << c;\n }\n }\n}\nTEST(HeaderPropertiesTest, HasInvalidHeaderChars) {\n const char with_null[] = \"Here's l\\x00king at you, kid\";\n EXPECT_TRUE(HasInvalidHeaderChars(std::string(with_null, sizeof(with_null))));\n EXPECT_TRUE(HasInvalidHeaderChars(\"Why's \\x06 afraid of \\x07? \\x07\\x08\\x09\"));\n EXPECT_TRUE(HasInvalidHeaderChars(\"\\x1Flower power\"));\n EXPECT_TRUE(HasInvalidHeaderChars(\"\\x7Flowers more powers\"));\n EXPECT_FALSE(HasInvalidHeaderChars(\"Plenty of space\"));\n EXPECT_FALSE(HasInvalidHeaderChars(\"Keeping \\tabs\"));\n EXPECT_FALSE(HasInvalidHeaderChars(\"Al\\right\"));\n EXPECT_FALSE(HasInvalidHeaderChars(\"\\new day\"));\n EXPECT_FALSE(HasInvalidHeaderChars(\"\\x42 is a nice character\"));\n}\n} \n} "}}},{"rowIdx":457,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_BALSA_BALSA_FRAME_H_\n#define QUICHE_BALSA_BALSA_FRAME_H_\n#include \n#include \n#include \n#include \n#include \n#include \"quiche/balsa/balsa_enums.h\"\n#include \"quiche/balsa/balsa_headers.h\"\n#include \"quiche/balsa/balsa_visitor_interface.h\"\n#include \"quiche/balsa/framer_interface.h\"\n#include \"quiche/balsa/http_validation_policy.h\"\n#include \"quiche/balsa/noop_balsa_visitor.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\n#include \"quiche/common/platform/api/quiche_flag_utils.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace quiche {\nnamespace test {\nclass BalsaFrameTestPeer;\n} \nclass QUICHE_EXPORT BalsaFrame : public FramerInterface {\n public:\n typedef std::vector > Lines;\n typedef BalsaHeaders::HeaderLineDescription HeaderLineDescription;\n typedef BalsaHeaders::HeaderLines HeaderLines;\n typedef BalsaHeaders::HeaderTokenList HeaderTokenList;\n enum class InvalidCharsLevel { kOff, kError };\n static constexpr int32_t kValidTerm1 = '\\n' << 16 | '\\r' << 8 | '\\n';\n static constexpr int32_t kValidTerm1Mask = 0xFF << 16 | 0xFF << 8 | 0xFF;\n static constexpr int32_t kValidTerm2 = '\\n' << 8 | '\\n';\n static constexpr int32_t kValidTerm2Mask = 0xFF << 8 | 0xFF;\n BalsaFrame()\n : last_char_was_slash_r_(false),\n saw_non_newline_char_(false),\n start_was_space_(true),\n chunk_length_character_extracted_(false),\n is_request_(true),\n allow_reading_until_close_for_request_(false),\n request_was_head_(false),\n max_header_length_(16 * 1024),\n visitor_(&do_nothing_visitor_),\n chunk_length_remaining_(0),\n content_length_remaining_(0),\n last_slash_n_idx_(0),\n term_chars_(0),\n parse_state_(BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE),\n last_error_(BalsaFrameEnums::BALSA_NO_ERROR),\n continue_headers_(nullptr),\n headers_(nullptr),\n start_of_trailer_line_(0),\n trailer_length_(0),\n invalid_chars_level_(InvalidCharsLevel::kOff),\n use_interim_headers_callback_(false) {}\n ~BalsaFrame() override {}\n void Reset();\n void set_balsa_headers(BalsaHeaders* headers) {\n if (headers_ != headers) {\n headers_ = headers;\n }\n if (headers_ != nullptr) {\n headers_->Clear();\n }\n }\n void set_continue_headers(BalsaHeaders* continue_headers) {\n if (continue_headers_ != continue_headers) {\n continue_headers_ = continue_headers;\n }\n if (continue_headers_ != nullptr) {\n continue_headers_->Clear();\n }\n }\n void EnableTrailers() {\n if (is_request()) {\n QUICHE_CODE_COUNT(balsa_trailer_in_request);\n }\n if (trailers_ == nullptr) {\n trailers_ = std::make_unique();\n }\n }\n void set_balsa_visitor(BalsaVisitorInterface* visitor) {\n visitor_ = visitor;\n if (visitor_ == nullptr) {\n visitor_ = &do_nothing_visitor_;\n }\n }\n void set_invalid_chars_level(InvalidCharsLevel v) {\n invalid_chars_level_ = v;\n }\n bool invalid_chars_error_enabled() {\n return invalid_chars_level_ == InvalidCharsLevel::kError;\n }\n void set_http_validation_policy(const HttpValidationPolicy& policy) {\n http_validation_policy_ = policy;\n }\n const HttpValidationPolicy& http_validation_policy() const {\n return http_validation_policy_;\n }\n void set_is_request(bool is_request) { is_request_ = is_request; }\n bool is_request() const { return is_request_; }\n void set_request_was_head(bool request_was_head) {\n request_was_head_ = request_was_head;\n }\n void set_max_header_length(size_t max_header_length) {\n max_header_length_ = max_header_length;\n }\n size_t max_header_length() const { return max_header_length_; }\n bool MessageFullyRead() const {\n return parse_state_ == BalsaFrameEnums::MESSAGE_FULLY_READ;\n }\n BalsaFrameEnums::ParseState ParseState() const { return parse_state_; }\n bool Error() const { return parse_state_ == BalsaFrameEnums::ERROR; }\n BalsaFrameEnums::ErrorCode ErrorCode() const { return last_error_; }\n const BalsaHeaders* headers() const { return headers_; }\n BalsaHeaders* mutable_headers() { return headers_; }\n size_t BytesSafeToSplice() const;\n void BytesSpliced(size_t bytes_spliced);\n size_t ProcessInput(const char* input, size_t size) override;\n void set_allow_reading_until_close_for_request(bool set) {\n allow_reading_until_close_for_request_ = set;\n }\n void AllowArbitraryBody() {\n parse_state_ = BalsaFrameEnums::READING_UNTIL_CLOSE;\n }\n void set_use_interim_headers_callback(bool set) {\n use_interim_headers_callback_ = set;\n }\n void set_parse_truncated_headers_even_when_headers_too_long(bool set) {\n parse_truncated_headers_even_when_headers_too_long_ = set;\n }\n protected:\n inline BalsaHeadersEnums::ContentLengthStatus ProcessContentLengthLine(\n size_t line_idx, size_t* length);\n inline void ProcessTransferEncodingLine(size_t line_idx);\n void ProcessFirstLine(char* begin, char* end);\n void CleanUpKeyValueWhitespace(const char* stream_begin,\n const char* line_begin, const char* current,\n const char* line_end,\n HeaderLineDescription* current_header_line);\n void ProcessHeaderLines(const Lines& lines, bool is_trailer,\n BalsaHeaders* headers);\n bool CheckHeaderLinesForInvalidChars(const Lines& lines,\n const BalsaHeaders* headers);\n inline size_t ProcessHeaders(const char* message_start,\n size_t message_length);\n void AssignParseStateAfterHeadersHaveBeenParsed();\n inline bool LineFramingFound(char current_char) {\n return current_char == '\\n';\n }\n inline int32_t HeaderFramingFound(char current_char) {\n if (current_char == '\\n' || current_char == '\\r') {\n term_chars_ <<= 8;\n term_chars_ |= current_char & 0xFF;\n if ((term_chars_ & kValidTerm1Mask) == kValidTerm1) {\n term_chars_ = 0;\n return kValidTerm1;\n }\n if ((term_chars_ & kValidTerm2Mask) == kValidTerm2) {\n term_chars_ = 0;\n return kValidTerm2;\n }\n } else {\n term_chars_ = 0;\n }\n return 0;\n }\n inline bool HeaderFramingMayBeFound() const { return term_chars_ != 0; }\n private:\n friend class test::BalsaFrameTestPeer;\n bool FindColonsAndParseIntoKeyValue(const Lines& lines, bool is_trailer,\n BalsaHeaders* headers);\n void HandleError(BalsaFrameEnums::ErrorCode error_code);\n void HandleWarning(BalsaFrameEnums::ErrorCode error_code);\n void HandleHeadersTooLongError();\n bool last_char_was_slash_r_;\n bool saw_non_newline_char_;\n bool start_was_space_;\n bool chunk_length_character_extracted_;\n bool is_request_; \n bool allow_reading_until_close_for_request_;\n bool request_was_head_; \n size_t max_header_length_; \n BalsaVisitorInterface* visitor_;\n size_t chunk_length_remaining_;\n size_t content_length_remaining_;\n size_t last_slash_n_idx_;\n uint32_t term_chars_;\n BalsaFrameEnums::ParseState parse_state_;\n BalsaFrameEnums::ErrorCode last_error_;\n Lines lines_;\n BalsaHeaders* continue_headers_; \n BalsaHeaders* headers_; \n NoOpBalsaVisitor do_nothing_visitor_;\n Lines trailer_lines_;\n size_t start_of_trailer_line_;\n size_t trailer_length_;\n std::unique_ptr trailers_;\n InvalidCharsLevel invalid_chars_level_; \n HttpValidationPolicy http_validation_policy_;\n bool use_interim_headers_callback_;\n bool parse_truncated_headers_even_when_headers_too_long_ = false;\n};\n} \n#endif \n#include \"quiche/balsa/balsa_frame.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"absl/strings/match.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/string_view.h\"\n#include \"quiche/balsa/balsa_enums.h\"\n#include \"quiche/balsa/balsa_headers.h\"\n#include \"quiche/balsa/balsa_visitor_interface.h\"\n#include \"quiche/balsa/header_properties.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#define CHAR_LT(a, b) \\\n (static_cast(a) < static_cast(b))\n#define CHAR_LE(a, b) \\\n (static_cast(a) <= static_cast(b))\n#define CHAR_GT(a, b) \\\n (static_cast(a) > static_cast(b))\n#define CHAR_GE(a, b) \\\n (static_cast(a) >= static_cast(b))\n#define QUICHE_DCHECK_CHAR_GE(a, b) \\\n QUICHE_DCHECK_GE(static_cast(a), static_cast(b))\nnamespace quiche {\nnamespace {\nusing FirstLineValidationOption =\n HttpValidationPolicy::FirstLineValidationOption;\nconstexpr size_t kContinueStatusCode = 100;\nconstexpr size_t kSwitchingProtocolsStatusCode = 101;\nconstexpr absl::string_view kChunked = \"chunked\";\nconstexpr absl::string_view kContentLength = \"content-length\";\nconstexpr absl::string_view kIdentity = \"identity\";\nconstexpr absl::string_view kTransferEncoding = \"transfer-encoding\";\nbool IsInterimResponse(size_t response_code) {\n return response_code >= 100 && response_code < 200;\n}\n} \nvoid BalsaFrame::Reset() {\n last_char_was_slash_r_ = false;\n saw_non_newline_char_ = false;\n start_was_space_ = true;\n chunk_length_character_extracted_ = false;\n allow_reading_until_close_for_request_ = false;\n chunk_length_remaining_ = 0;\n content_length_remaining_ = 0;\n last_slash_n_idx_ = 0;\n term_chars_ = 0;\n parse_state_ = BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE;\n last_error_ = BalsaFrameEnums::BALSA_NO_ERROR;\n lines_.clear();\n if (continue_headers_ != nullptr) {\n continue_headers_->Clear();\n }\n if (headers_ != nullptr) {\n headers_->Clear();\n }\n trailer_lines_.clear();\n start_of_trailer_line_ = 0;\n trailer_length_ = 0;\n if (trailers_ != nullptr) {\n trailers_->Clear();\n }\n}\nnamespace {\ninline char* ParseOneIsland(char* current, char* begin, char* end,\n size_t* first_whitespace, size_t* first_nonwhite) {\n *first_whitespace = current - begin;\n while (current < end && CHAR_LE(*current, ' ')) {\n ++current;\n }\n *first_nonwhite = current - begin;\n while (current < end && CHAR_GT(*current, ' ')) {\n ++current;\n }\n return current;\n}\n} \nbool ParseHTTPFirstLine(char* begin, char* end, bool is_request,\n BalsaHeaders* headers,\n BalsaFrameEnums::ErrorCode* error_code,\n FirstLineValidationOption whitespace_option) {\n while (begin < end && (end[-1] == '\\n' || end[-1] == '\\r')) {\n --end;\n }\n if (whitespace_option != FirstLineValidationOption::NONE) {\n constexpr absl::string_view kBadWhitespace = \"\\r\\t\";\n char* pos = std::find_first_of(begin, end, kBadWhitespace.begin(),\n kBadWhitespace.end());\n if (pos != end) {\n if (whitespace_option == FirstLineValidationOption::REJECT) {\n *error_code = static_cast(\n BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE +\n static_cast(is_request));\n return false;\n }\n QUICHE_DCHECK(whitespace_option == FirstLineValidationOption::SANITIZE);\n std::replace_if(\n pos, end, [](char c) { return c == '\\r' || c == '\\t'; }, ' ');\n }\n }\n char* current = ParseOneIsland(begin, begin, end, &headers->whitespace_1_idx_,\n &headers->non_whitespace_1_idx_);\n current = ParseOneIsland(current, begin, end, &headers->whitespace_2_idx_,\n &headers->non_whitespace_2_idx_);\n current = ParseOneIsland(current, begin, end, &headers->whitespace_3_idx_,\n &headers->non_whitespace_3_idx_);\n const char* last = end;\n while (current <= last && CHAR_LE(*last, ' ')) {\n --last;\n }\n headers->whitespace_4_idx_ = last - begin + 1;\n QUICHE_DCHECK(begin == end || static_cast(*begin) > ' ');\n QUICHE_DCHECK_EQ(0u, headers->whitespace_1_idx_);\n QUICHE_DCHECK_EQ(0u, headers->non_whitespace_1_idx_);\n QUICHE_DCHECK(begin == end ||\n headers->non_whitespace_1_idx_ < headers->whitespace_2_idx_);\n if (headers->non_whitespace_2_idx_ == headers->whitespace_3_idx_) {\n *error_code = static_cast(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION +\n static_cast(is_request));\n if (!is_request) { \n return false;\n }\n }\n if (headers->whitespace_3_idx_ == headers->non_whitespace_3_idx_) {\n if (*error_code == BalsaFrameEnums::BALSA_NO_ERROR) {\n *error_code = static_cast(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE +\n static_cast(is_request));\n }\n }\n if (!is_request) {\n headers->parsed_response_code_ = 0;\n if (headers->non_whitespace_2_idx_ < headers->whitespace_3_idx_) {\n if (!absl::SimpleAtoi(\n absl::string_view(begin + headers->non_whitespace_2_idx_,\n headers->non_whitespace_3_idx_ -\n headers->non_whitespace_2_idx_),\n &headers->parsed_response_code_)) {\n *error_code = BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT;\n return false;\n }\n }\n }\n return true;\n}\nnamespace {\nbool IsValidTargetUri(absl::string_view method, absl::string_view target_uri) {\n if (target_uri.empty()) {\n QUICHE_CODE_COUNT(invalid_target_uri_empty);\n return false;\n }\n if (target_uri == \"*\") {\n if (method == \"OPTIONS\") {\n return true;\n }\n QUICHE_CODE_COUNT(invalid_target_uri_asterisk_not_options);\n return false;\n }\n if (method == \"CONNECT\") {\n size_t index = target_uri.find_last_of(':');\n if (index == absl::string_view::npos || index == 0) {\n QUICHE_CODE_COUNT(invalid_target_uri_connect_missing_port);\n return false;\n }\n if (target_uri[0] == '[' && target_uri[index - 1] != ']') {\n QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_v6_literal);\n return false;\n }\n int port;\n if (!absl::SimpleAtoi(target_uri.substr(index + 1), &port) || port < 0 ||\n port > 65535) {\n QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_port);\n return false;\n }\n return true;\n }\n if (target_uri[0] == '/' || absl::StrContains(target_uri, \":\n return true;\n }\n QUICHE_CODE_COUNT(invalid_target_uri_bad_path);\n return false;\n}\n} \nvoid BalsaFrame::ProcessFirstLine(char* begin, char* end) {\n BalsaFrameEnums::ErrorCode previous_error = last_error_;\n if (!ParseHTTPFirstLine(\n begin, end, is_request_, headers_, &last_error_,\n http_validation_policy().sanitize_cr_tab_in_first_line)) {\n parse_state_ = BalsaFrameEnums::ERROR;\n HandleError(last_error_);\n return;\n }\n if (previous_error != last_error_) {\n HandleWarning(last_error_);\n }\n const absl::string_view line_input(\n begin + headers_->non_whitespace_1_idx_,\n headers_->whitespace_4_idx_ - headers_->non_whitespace_1_idx_);\n const absl::string_view part1(\n begin + headers_->non_whitespace_1_idx_,\n headers_->whitespace_2_idx_ - headers_->non_whitespace_1_idx_);\n const absl::string_view part2(\n begin + headers_->non_whitespace_2_idx_,\n headers_->whitespace_3_idx_ - headers_->non_whitespace_2_idx_);\n const absl::string_view part3(\n begin + headers_->non_whitespace_3_idx_,\n headers_->whitespace_4_idx_ - headers_->non_whitespace_3_idx_);\n if (is_request_) {\n const bool is_valid_target_uri = IsValidTargetUri(part1, part2);\n if (http_validation_policy().disallow_invalid_target_uris &&\n !is_valid_target_uri) {\n parse_state_ = BalsaFrameEnums::ERROR;\n last_error_ = BalsaFrameEnums::INVALID_TARGET_URI;\n HandleError(last_error_);\n return;\n }\n visitor_->OnRequestFirstLineInput(line_input, part1, part2, part3);\n if (part3.empty()) {\n parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ;\n }\n return;\n }\n visitor_->OnResponseFirstLineInput(line_input, part1, part2, part3);\n}\nvoid BalsaFrame::CleanUpKeyValueWhitespace(\n const char* stream_begin, const char* line_begin, const char* current,\n const char* line_end, HeaderLineDescription* current_header_line) {\n const char* colon_loc = current;\n QUICHE_DCHECK_LT(colon_loc, line_end);\n QUICHE_DCHECK_EQ(':', *colon_loc);\n QUICHE_DCHECK_EQ(':', *current);\n QUICHE_DCHECK_CHAR_GE(' ', *line_end)\n << \"\\\"\" << std::string(line_begin, line_end) << \"\\\"\";\n --current;\n while (current > line_begin && CHAR_LE(*current, ' ')) {\n --current;\n }\n current += static_cast(current != colon_loc);\n current_header_line->key_end_idx = current - stream_begin;\n current = colon_loc;\n QUICHE_DCHECK_EQ(':', *current);\n ++current;\n while (current < line_end && CHAR_LE(*current, ' ')) {\n ++current;\n }\n current_header_line->value_begin_idx = current - stream_begin;\n QUICHE_DCHECK_GE(current_header_line->key_end_idx,\n current_header_line->first_char_idx);\n QUICHE_DCHECK_GE(current_header_line->value_begin_idx,\n current_header_line->key_end_idx);\n QUICHE_DCHECK_GE(current_header_line->last_char_idx,\n current_header_line->value_begin_idx);\n}\nbool BalsaFrame::FindColonsAndParseIntoKeyValue(const Lines& lines,\n bool is_trailer,\n BalsaHeaders* headers) {\n QUICHE_DCHECK(!lines.empty());\n const char* stream_begin = headers->OriginalHeaderStreamBegin();\n const Lines::size_type lines_size_m1 = lines.size() - 1;\n int first_header_idx = (is_trailer ? 0 : 1);\n const char* current = stream_begin + lines[first_header_idx].first;\n for (Lines::size_type i = first_header_idx; i < lines_size_m1;) {\n const char* line_begin = stream_begin + lines[i].first;\n for (++i; i < lines_size_m1; ++i) {\n const char c = *(stream_begin + lines[i].first);\n if (CHAR_GT(c, ' ')) {\n break;\n }\n if ((c != ' ' && c != '\\t') ||\n http_validation_policy().disallow_header_continuation_lines) {\n HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_FORMAT\n : BalsaFrameEnums::INVALID_HEADER_FORMAT);\n return false;\n }\n }\n const char* line_end = stream_begin + lines[i - 1].second;\n QUICHE_DCHECK_LT(line_begin - stream_begin, line_end - stream_begin);\n --line_end;\n QUICHE_DCHECK_EQ('\\n', *line_end)\n << \"\\\"\" << std::string(line_begin, line_end) << \"\\\"\";\n while (CHAR_LE(*line_end, ' ') && line_end > line_begin) {\n --line_end;\n }\n ++line_end;\n QUICHE_DCHECK_CHAR_GE(' ', *line_end);\n QUICHE_DCHECK_LT(line_begin, line_end);\n headers->header_lines_.push_back(HeaderLineDescription(\n line_begin - stream_begin, line_end - stream_begin,\n line_end - stream_begin, line_end - stream_begin, 0));\n if (current >= line_end) {\n if (http_validation_policy().require_header_colon) {\n HandleError(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON\n : BalsaFrameEnums::HEADER_MISSING_COLON);\n return false;\n }\n HandleWarning(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON\n : BalsaFrameEnums::HEADER_MISSING_COLON);\n continue;\n }\n if (current < line_begin) {\n current = line_begin;\n }\n for (; current < line_end; ++current) {\n if (*current == ':') {\n break;\n }\n if (http_validation_policy().disallow_double_quote_in_header_name) {\n if (header_properties::IsInvalidHeaderKeyChar(*current)) {\n Ha"},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/balsa/balsa_frame.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"absl/strings/escaping.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_format.h\"\n#include \"absl/strings/str_replace.h\"\n#include \"absl/strings/string_view.h\"\n#include \"quiche/balsa/balsa_enums.h\"\n#include \"quiche/balsa/balsa_headers.h\"\n#include \"quiche/balsa/balsa_visitor_interface.h\"\n#include \"quiche/balsa/http_validation_policy.h\"\n#include \"quiche/balsa/noop_balsa_visitor.h\"\n#include \"quiche/balsa/simple_buffer.h\"\n#include \"quiche/common/platform/api/quiche_command_line_flags.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_flags.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nusing ::testing::_;\nusing ::testing::AnyNumber;\nusing ::testing::AtLeast;\nusing ::testing::InSequence;\nusing ::testing::IsEmpty;\nusing ::testing::Mock;\nusing ::testing::NiceMock;\nusing ::testing::Pointee;\nusing ::testing::Property;\nusing ::testing::Range;\nusing ::testing::StrEq;\nusing ::testing::StrictMock;\nDEFINE_QUICHE_COMMAND_LINE_FLAG(\n std::string, randseed, \"\",\n \"This is the seed for Pseudo-random number\"\n \" generator used when generating random messages for unittests\");\nnamespace quiche::test {\nusing RandomEngine = std::mt19937;\nclass BalsaFrameTestPeer {\n public:\n static int32_t HeaderFramingFound(BalsaFrame* balsa_frame, char c) {\n return balsa_frame->HeaderFramingFound(c);\n }\n static void FindColonsAndParseIntoKeyValue(BalsaFrame* balsa_frame,\n const BalsaFrame::Lines& lines,\n bool is_trailer,\n BalsaHeaders* headers) {\n balsa_frame->FindColonsAndParseIntoKeyValue(lines, is_trailer, headers);\n }\n};\nclass BalsaHeadersTestPeer {\n public:\n static void WriteFromFramer(BalsaHeaders* headers, const char* ptr,\n size_t size) {\n headers->WriteFromFramer(ptr, size);\n }\n};\nnamespace {\nclass TestSeed {\n public:\n TestSeed() : test_seed_(0), user_supplied_seed_(false) {}\n void Initialize(const std::string& seed_flag) {\n if (!seed_flag.empty()) {\n ASSERT_TRUE(absl::SimpleAtoi(seed_flag, &test_seed_));\n user_supplied_seed_ = true;\n }\n }\n int GetSeed() const {\n int seed =\n (user_supplied_seed_ ? test_seed_\n : testing::UnitTest::GetInstance()->random_seed());\n QUICHE_LOG(INFO) << \"**** The current seed is \" << seed << \" ****\";\n return seed;\n }\n private:\n int test_seed_;\n bool user_supplied_seed_;\n};\nstatic bool RandomBool(RandomEngine& rng) { return rng() % 2 != 0; }\nstd::string EscapeString(absl::string_view message) {\n return absl::StrReplaceAll(\n message, {{\"\\n\", \"\\\\\\\\n\\n\"}, {\"\\\\r\", \"\\\\\\\\r\"}, {\"\\\\t\", \"\\\\\\\\t\"}});\n}\nchar random_lws(RandomEngine& rng) {\n if (RandomBool(rng)) {\n return '\\t';\n }\n return ' ';\n}\nconst char* random_line_term(RandomEngine& rng) {\n if (RandomBool(rng)) {\n return \"\\r\\n\";\n }\n return \"\\n\";\n}\nvoid AppendRandomWhitespace(RandomEngine& rng, std::stringstream* s) {\n for (int i = 0; i < 1000 && RandomBool(rng); ++i) {\n *s << random_lws(rng);\n }\n}\nstd::string CreateFirstLine(const char* tokens[3], const char* whitespace[4],\n const char* line_ending) {\n QUICHE_CHECK(tokens != nullptr);\n QUICHE_CHECK(whitespace != nullptr);\n QUICHE_CHECK(line_ending != nullptr);\n QUICHE_CHECK(std::string(line_ending) == \"\\n\" ||\n std::string(line_ending) == \"\\r\\n\")\n << \"line_ending: \" << EscapeString(line_ending);\n SimpleBuffer firstline_buffer;\n firstline_buffer.WriteString(whitespace[0]);\n for (int i = 0; i < 3; ++i) {\n firstline_buffer.WriteString(tokens[i]);\n firstline_buffer.WriteString(whitespace[i + 1]);\n }\n firstline_buffer.WriteString(line_ending);\n return std::string(firstline_buffer.GetReadableRegion());\n}\nstd::string CreateMessage(const char* firstline,\n const std::pair* headers,\n size_t headers_len, const char* colon,\n const char* line_ending, const char* body) {\n SimpleBuffer request_buffer;\n request_buffer.WriteString(firstline);\n if (headers_len > 0) {\n QUICHE_CHECK(headers != nullptr);\n QUICHE_CHECK(colon != nullptr);\n }\n QUICHE_CHECK(line_ending != nullptr);\n QUICHE_CHECK(std::string(line_ending) == \"\\n\" ||\n std::string(line_ending) == \"\\r\\n\")\n << \"line_ending: \" << EscapeString(line_ending);\n QUICHE_CHECK(body != nullptr);\n for (size_t i = 0; i < headers_len; ++i) {\n bool only_whitespace_in_key = true;\n {\n const char* tmp_key = headers[i].first.c_str();\n while (*tmp_key != '\\0') {\n if (*tmp_key > ' ') {\n only_whitespace_in_key = false;\n break;\n }\n ++tmp_key;\n }\n }\n const char* tmp_colon = colon;\n if (only_whitespace_in_key) {\n while (*tmp_colon != ':') {\n ++tmp_colon;\n }\n }\n request_buffer.WriteString(headers[i].first);\n request_buffer.WriteString(tmp_colon);\n request_buffer.WriteString(headers[i].second);\n request_buffer.WriteString(line_ending);\n }\n request_buffer.WriteString(line_ending);\n request_buffer.WriteString(body);\n return std::string(request_buffer.GetReadableRegion());\n}\nvoid VerifyRequestFirstLine(const char* tokens[3],\n const BalsaHeaders& headers) {\n EXPECT_EQ(tokens[0], headers.request_method());\n EXPECT_EQ(tokens[1], headers.request_uri());\n EXPECT_EQ(0u, headers.parsed_response_code());\n EXPECT_EQ(tokens[2], headers.request_version());\n}\nvoid VerifyResponseFirstLine(const char* tokens[3],\n size_t expected_response_code,\n const BalsaHeaders& headers) {\n EXPECT_EQ(tokens[0], headers.response_version());\n EXPECT_EQ(tokens[1], headers.response_code());\n EXPECT_EQ(expected_response_code, headers.parsed_response_code());\n EXPECT_EQ(tokens[2], headers.response_reason_phrase());\n}\nvoid VerifyHeaderLines(\n const std::pair* expected_headers,\n size_t headers_len, const BalsaHeaders& headers) {\n BalsaHeaders::const_header_lines_iterator it = headers.lines().begin();\n for (size_t i = 0; it != headers.lines().end(); ++it, ++i) {\n ASSERT_GT(headers_len, i);\n std::string actual_key;\n std::string actual_value;\n if (!it->first.empty()) {\n actual_key = std::string(it->first);\n }\n if (!it->second.empty()) {\n actual_value = std::string(it->second);\n }\n EXPECT_THAT(actual_key, StrEq(expected_headers[i].first));\n EXPECT_THAT(actual_value, StrEq(expected_headers[i].second));\n }\n EXPECT_TRUE(headers.lines().end() == it);\n}\nvoid FirstLineParsedCorrectlyHelper(const char* tokens[3],\n size_t expected_response_code,\n bool is_request, const char* whitespace) {\n BalsaHeaders headers;\n BalsaFrame framer;\n framer.set_is_request(is_request);\n framer.set_balsa_headers(&headers);\n const char* tmp_tokens[3] = {tokens[0], tokens[1], tokens[2]};\n const char* tmp_whitespace[4] = {\"\", whitespace, whitespace, \"\"};\n for (int j = 2; j >= 0; --j) {\n framer.Reset();\n std::string firstline = CreateFirstLine(tmp_tokens, tmp_whitespace, \"\\n\");\n std::string message =\n CreateMessage(firstline.c_str(), nullptr, 0, nullptr, \"\\n\", \"\");\n SCOPED_TRACE(absl::StrFormat(\"input: \\n%s\", EscapeString(message)));\n EXPECT_GE(message.size(),\n framer.ProcessInput(message.data(), message.size()));\n if (is_request || j >= 1) {\n EXPECT_FALSE(framer.Error());\n if (is_request) {\n EXPECT_TRUE(framer.MessageFullyRead());\n }\n if (j == 0) {\n expected_response_code = 0;\n }\n if (is_request) {\n VerifyRequestFirstLine(tmp_tokens, *framer.headers());\n } else {\n VerifyResponseFirstLine(tmp_tokens, expected_response_code,\n *framer.headers());\n }\n } else {\n EXPECT_TRUE(framer.Error());\n }\n tmp_tokens[j] = \"\";\n tmp_whitespace[j] = \"\";\n }\n}\nTEST(HTTPBalsaFrame, ParseStateToString) {\n EXPECT_STREQ(\"ERROR\",\n BalsaFrameEnums::ParseStateToString(BalsaFrameEnums::ERROR));\n EXPECT_STREQ(\"READING_HEADER_AND_FIRSTLINE\",\n BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE));\n EXPECT_STREQ(\"READING_CHUNK_LENGTH\",\n BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_CHUNK_LENGTH));\n EXPECT_STREQ(\"READING_CHUNK_EXTENSION\",\n BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_CHUNK_EXTENSION));\n EXPECT_STREQ(\"READING_CHUNK_DATA\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_CHUNK_DATA));\n EXPECT_STREQ(\"READING_CHUNK_TERM\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_CHUNK_TERM));\n EXPECT_STREQ(\"READING_LAST_CHUNK_TERM\",\n BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_LAST_CHUNK_TERM));\n EXPECT_STREQ(\"READING_TRAILER\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_TRAILER));\n EXPECT_STREQ(\"READING_UNTIL_CLOSE\",\n BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_UNTIL_CLOSE));\n EXPECT_STREQ(\"READING_CONTENT\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::READING_CONTENT));\n EXPECT_STREQ(\"MESSAGE_FULLY_READ\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::MESSAGE_FULLY_READ));\n EXPECT_STREQ(\"UNKNOWN_STATE\", BalsaFrameEnums::ParseStateToString(\n BalsaFrameEnums::NUM_STATES));\n EXPECT_STREQ(\"UNKNOWN_STATE\",\n BalsaFrameEnums::ParseStateToString(\n static_cast(-1)));\n for (int i = 0; i < BalsaFrameEnums::NUM_STATES; ++i) {\n EXPECT_STRNE(\"UNKNOWN_STATE\",\n BalsaFrameEnums::ParseStateToString(\n static_cast(i)));\n }\n}\nTEST(HTTPBalsaFrame, ErrorCodeToString) {\n EXPECT_STREQ(\"NO_STATUS_LINE_IN_RESPONSE\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::NO_STATUS_LINE_IN_RESPONSE));\n EXPECT_STREQ(\"NO_REQUEST_LINE_IN_REQUEST\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST));\n EXPECT_STREQ(\"FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION));\n EXPECT_STREQ(\"FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD));\n EXPECT_STREQ(\n \"FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE));\n EXPECT_STREQ(\n \"FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI));\n EXPECT_STREQ(\n \"FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE));\n EXPECT_STREQ(\n \"FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION));\n EXPECT_STREQ(\"FAILED_CONVERTING_STATUS_CODE_TO_INT\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT));\n EXPECT_STREQ(\"HEADERS_TOO_LONG\", BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::HEADERS_TOO_LONG));\n EXPECT_STREQ(\"UNPARSABLE_CONTENT_LENGTH\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH));\n EXPECT_STREQ(\"MAYBE_BODY_BUT_NO_CONTENT_LENGTH\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH));\n EXPECT_STREQ(\"HEADER_MISSING_COLON\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::HEADER_MISSING_COLON));\n EXPECT_STREQ(\"INVALID_CHUNK_LENGTH\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::INVALID_CHUNK_LENGTH));\n EXPECT_STREQ(\"CHUNK_LENGTH_OVERFLOW\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW));\n EXPECT_STREQ(\"CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO));\n EXPECT_STREQ(\"CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::\n CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT));\n EXPECT_STREQ(\"MULTIPLE_CONTENT_LENGTH_KEYS\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS));\n EXPECT_STREQ(\"MULTIPLE_TRANSFER_ENCODING_KEYS\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::MULTIPLE_TRANSFER_ENCODING_KEYS));\n EXPECT_STREQ(\"INVALID_HEADER_FORMAT\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::INVALID_HEADER_FORMAT));\n EXPECT_STREQ(\"INVALID_TRAILER_FORMAT\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::INVALID_TRAILER_FORMAT));\n EXPECT_STREQ(\"TRAILER_TOO_LONG\", BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::TRAILER_TOO_LONG));\n EXPECT_STREQ(\"TRAILER_MISSING_COLON\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::TRAILER_MISSING_COLON));\n EXPECT_STREQ(\"INTERNAL_LOGIC_ERROR\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::INTERNAL_LOGIC_ERROR));\n EXPECT_STREQ(\"INVALID_HEADER_CHARACTER\",\n BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::INVALID_HEADER_CHARACTER));\n EXPECT_STREQ(\"UNKNOWN_ERROR\", BalsaFrameEnums::ErrorCodeToString(\n BalsaFrameEnums::NUM_ERROR_CODES));\n EXPECT_STREQ(\"UNKNOWN_ERROR\",\n BalsaFrameEnums::ErrorCodeToString(\n static_cast(-1)));\n for (int i = 0; i < BalsaFrameEnums::NUM_ERROR_CODES; ++i) {\n EXPECT_STRNE(\"UNKNOWN_ERROR\",\n BalsaFrameEnums::ErrorCodeToString(\n static_cast(i)));\n }\n}\nclass FakeHeaders {\n public:\n struct KeyValuePair {\n KeyValuePair(const std::string& key, const std::string& value)\n : key(key), value(value) {}\n KeyValuePair() {}\n std::string key;\n std::string value;\n };\n typedef std::vector KeyValuePairs;\n KeyValuePairs key_value_pairs_;\n bool operator==(const FakeHeaders& other) const {\n if (key_value_pairs_.size() != other.key_value_pairs_.size()) {\n return false;\n }\n for (KeyValuePairs::size_type i = 0; i < key_value_pairs_.size(); ++i) {\n if (key_value_pairs_[i].key != other.key_value_pairs_[i].key) {\n return false;\n }\n if (key_value_pairs_[i].value != other.key_value_pairs_[i].value) {\n return false;\n }\n }\n return true;\n }\n void AddKeyValue(const std::string& key, const std::string& value) {\n key_value_pairs_.push_back(KeyValuePair(key, value));\n }\n};\nclass BalsaVisitorMock : public BalsaVisitorInterface {\n public:\n ~BalsaVisitorMock() override = default;\n void ProcessHeaders(const BalsaHeaders& headers) override {\n FakeHeaders fake_headers;\n GenerateFakeHeaders(headers, &fake_headers);\n ProcessHeaders(fake_headers);\n }\n void OnTrailers(std::unique_ptr trailers) override {\n FakeHeaders fake_trailers;\n GenerateFakeHeaders(*trailers, &fake_trailers);\n OnTrailers(fake_trailers);\n }\n MOCK_METHOD(void, OnRawBodyInput, (absl::string_view input), (override));\n MOCK_METHOD(void, OnBodyChunkInput, (absl::string_view input), (override));\n MOCK_METHOD(void, OnHeaderInput, (absl::string_view input), (override));\n MOCK_METHOD(void, OnTrailerInput, (absl::string_view input), (override));\n MOCK_METHOD(void, ProcessHeaders, (const FakeHeaders& headers));\n MOCK_METHOD(void, OnTrailers, (const FakeHeaders& trailers));\n MOCK_METHOD(void, OnRequestFirstLineInput,\n (absl::string_view line_input, absl::string_view method_input,\n absl::string_view request_uri, absl::string_view version_input),\n (override));\n MOCK_METHOD(void, OnResponseFirstLineInput,\n (absl::string_view line_input, absl::string_view version_input,\n absl::string_view status_input, absl::string_view reason_input),\n (override));\n MOCK_METHOD(void, OnChunkLength, (size_t length), (override));\n MOCK_METHOD(void, OnChunkExtensionInput, (absl::string_view input),\n (override));\n MOCK_METHOD(void, OnInterimHeaders, (std::unique_ptr headers),\n (override));\n MOCK_METHOD(void, ContinueHeaderDone, (), (override));\n MOCK_METHOD(void, HeaderDone, (), (override));\n MOCK_METHOD(void, MessageDone, (), (override));\n MOCK_METHOD(void, HandleError, (BalsaFrameEnums::ErrorCode error_code),\n (override));\n MOCK_METHOD(void, HandleWarning, (BalsaFrameEnums::ErrorCode error_code),\n (override));\n private:\n static void GenerateFakeHeaders(const BalsaHeaders& headers,\n FakeHeaders* fake_headers) {\n for (const auto& line : headers.lines()) {\n fake_headers->AddKeyValue(std::string(line.first),\n std::string(line.second));\n }\n }\n};\nclass HTTPBalsaFrameTest : public QuicheTest {\n protected:\n void SetUp() override {\n balsa_frame_.set_balsa_headers(&headers_);\n balsa_frame_.set_balsa_visitor(&visitor_mock_);\n balsa_frame_.set_is_request(true);\n balsa_frame_.EnableTrailers();\n }\n void VerifyFirstLineParsing(const std::string& firstline,\n BalsaFrameEnums::ErrorCode error_code) {\n balsa_frame_.ProcessInput(firstline.data(), firstline.size());\n EXPECT_EQ(error_code, balsa_frame_.ErrorCode());\n }\n BalsaHeaders headers_;\n BalsaFrame balsa_frame_;\n NiceMock visitor_mock_;\n};\nTEST_F(HTTPBalsaFrameTest, TestHeaderFramingFound) {\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ' '));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(BalsaFrame::kValidTerm1,\n BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\t'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(BalsaFrame::kValidTerm1,\n BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, 'a'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(BalsaFrame::kValidTerm2,\n BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '1'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(BalsaFrame::kValidTerm2,\n BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ':'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\r'));\n EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\\n'));\n}\nTEST_F(HTTPBalsaFrameTest, MissingColonInTrailer) {\n const absl::string_view trailer = \"kv\\r\\n\\r\\n\";\n BalsaFrame::Lines lines;\n lines.push_back({0, 4});\n lines.push_back({4, trailer.length()});\n BalsaHeaders trailers;\n BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),\n trailer.length());\n BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(\n &balsa_frame_, lines, true , &trailers);\n EXPECT_FALSE(balsa_frame_.Error());\n EXPECT_EQ(BalsaFrameEnums::TRAILER_MISSING_COLON, balsa_frame_.ErrorCode());\n}\nTEST_F(HTTPBalsaFrameTest, FindColonsAndParseIntoKeyValueInTrailer) {\n const absl::string_view trailer_line1 = \"Fraction: 0.23\\r\\n\";\n const absl::string_view trailer_line2 = \"Some:junk \\r\\n\";\n const absl::string_view trailer_line3 = \"\\r\\n\";\n const std::string trailer =\n absl::StrCat(trailer_line1, trailer_line2, trailer_line3);\n BalsaFrame::Lines lines;\n lines.push_back({0, trailer_line1.length()});\n lines.push_back({trailer_line1.length(),\n trailer_line1.length() + trailer_line2.length()});\n lines.push_back(\n {trailer_line1.length() + trailer_line2.length(), trailer.length()});\n BalsaHeaders trailers;\n BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),\n trailer.length());\n BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(\n &balsa_frame_, lines, true , &trailers);\n EXPECT_FALSE(balsa_frame_.Error());\n absl::string_view fraction = trailers.GetHeader(\"Fraction\");\n EXPECT_EQ(\"0.23\", fraction);\n absl::string_view some = trailers.GetHeader(\"Some\");\n EXPECT_EQ(\"junk\", some);\n}\nTEST_F(HTTPBalsaFrameTest, InvalidTrailer) {\n const absl::string_view trailer_line1 = \"Fraction : 0.23\\r\\n\";\n const absl::string_view trailer_line2 = \"Some\\t :junk \\r\\n\";\n const absl::string_view trailer_line3 = \"\\r\\n\";\n const std::string trailer =\n absl::StrCat(trailer_line1, trailer_line2, trailer_line3);\n BalsaFrame::Lines lines;\n lines.push_back({0, trailer_line1.length()});\n lines.push_back({trailer_line1.length(),\n trailer_line1.length() + trailer_line2.length()});\n lines.push_back(\n {trailer_line1.length() + trailer_line2.length(), trailer.length()});\n BalsaHeaders trailers;\n BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),\n trailer.length());\n BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(\n &balsa_frame_, lines, true , &trailers);\n EXPECT_TRUE(balsa_frame_.Error());\n EXPECT_EQ(BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER,\n balsa_frame_.ErrorCode());\n}\nTEST_F(HTTPBalsaFrameTest, OneCharacterFirstLineParsedAsExpected) {\n VerifyFirstLineParsing(\n \"a\\r\\n\\r\\n\", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD);\n}\nTEST_F(HTTPBalsaFrameTest,\n OneCharacterFirstLineWithWhitespaceParsedAsExpected) {\n VerifyFirstLineParsing(\n \"a \\r\\n\\r\\n\", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD);\n}\nTEST_F(HTTPBalsaFrameTest, WhitespaceOnlyFirstLineIsNotACompleteHeader) {\n VerifyFirstLineParsing(\" \\n\\n\", BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST);\n}\nTEST(HTTPBalsaFrame, RequestFirstLineParsedCorrectly) {\n const char* request_tokens[3] = {\"GET\", \"/jjsdjrqk\", \"HTTP/1.0\"};\n FirstLineParsedCorrectlyHelper(request_tokens, 0, true, \" \");\n FirstLineParsedCorrectlyHelper(request_tokens, 0, true, \"\\t\");\n FirstLineParsedCorrectlyHelper(request_tokens, 0, true, \"\\t \");\n FirstLineParsedCorrectlyHelper(request_tokens, 0, true, \" \\t\");\n FirstLineParsedCorrectlyHelper(request_tokens, 0, true, \" \\t \\t \");\n}\nTEST(HTTPBalsaFrame, RequestLineSanitizedProperly) {\n SCOPED_TRACE(\"Testing that the request line is properly sanitized.\");\n using enum HttpValidationPolicy::FirstLineValidationOption;\n using FirstLineValidationOption =\n HttpValidationPolicy::FirstLineValidationOption;\n struct TestCase {\n const absl::string_view input; \n const absl::string_view parsed; \n FirstLineValidationOption option; \n BalsaFrameEnums::ErrorCode expected_error;\n };\n const std::vector cases = {\n {\"GET / HTTP/1.1\\r\\n\", \"GET / HTTP/1.1\", NONE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET / HTTP/1.1\\r\\n\", \"GET / HTTP/1.1\", SANITIZE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET / HTTP/1.1\\r\\n\", \"GET / HTTP/1.1\", REJECT,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET /\\rHTTP/1.1\\r\\n\", \"GET /\\rHTTP/1.1\", NONE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET /\\rHTTP/1.1\\r\\n\", \"GET / HTTP/1.1\", SANITIZE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET /\\rHTTP/1.1\\r\\n\", \"\", REJECT,\n BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},\n {\"GET \\t/ HTTP/1.1\\r\\n\", \"GET \\t/ HTTP/1.1\", NONE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET \\t/ HTTP/1.1\\r\\n\", \"GET / HTTP/1.1\", SANITIZE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET \\t/ HTTP/1.1\\r\\n\", \"\", REJECT,\n BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},\n {\"GET \\t/\\rHTTP/1.1 \\r\\n\", \"GET \\t/\\rHTTP/1.1\", NONE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET \\t/\\rHTTP/1.1 \\r\\n\", \"GET / HTTP/1.1\", SANITIZE,\n BalsaFrameEnums::BALSA_NO_ERROR},\n {\"GET \\t/\\rHTTP/1.1 \\r\\n\", \"\", REJECT,\n BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},\n };\n const absl::string_view kHeaderLineAndEnding = \"Foo: bar\\r\\n\\r\\n\";\n for (auto& [firstline, parsed, ws_option, expected_error] : cases) {\n SCOPED_TRACE(\n absl::StrCat(\"Input: \", absl::CEscape(firstline),\n \" Expected output: \", absl::CEscape(parsed),\n \" whitespace option: \", static_cast(ws_option)));\n const std::string input = absl::StrCat(firstline, kHeaderLineAndEnding);\n BalsaHeaders headers;\n BalsaFrame framer;\n HttpValidationPolicy policy;\n policy.sanitize_cr_tab_in_first_line = ws_option;\n framer.set_http_validation_policy(policy);\n framer.set_is_request(true);\n framer.set_balsa_headers(&headers);\n framer.ProcessInput(input.data(), input.size());\n EXPECT_EQ(headers.first_line(),"}}},{"rowIdx":458,"cells":{"Repo":{"kind":"string","value":"quiche"},"Code":{"kind":"string","value":"#ifndef QUICHE_BALSA_SIMPLE_BUFFER_H_\n#define QUICHE_BALSA_SIMPLE_BUFFER_H_\n#include \n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_export.h\"\nnamespace quiche {\nnamespace test {\nclass SimpleBufferTest;\n} \nclass QUICHE_EXPORT SimpleBuffer {\n public:\n struct ReleasedBuffer {\n std::unique_ptr buffer;\n size_t size;\n };\n SimpleBuffer() = default;\n explicit SimpleBuffer(int size);\n SimpleBuffer(const SimpleBuffer&) = delete;\n SimpleBuffer& operator=(const SimpleBuffer&) = delete;\n virtual ~SimpleBuffer() { delete[] storage_; }\n int ReadableBytes() const { return write_idx_ - read_idx_; }\n bool Empty() const { return read_idx_ == write_idx_; }\n int Write(const char* bytes, int size);\n int WriteString(absl::string_view piece) {\n return Write(piece.data(), piece.size());\n }\n void GetWritablePtr(char** ptr, int* size) const {\n *ptr = storage_ + write_idx_;\n *size = storage_size_ - write_idx_;\n }\n void GetReadablePtr(char** ptr, int* size) const {\n *ptr = storage_ + read_idx_;\n *size = write_idx_ - read_idx_;\n }\n absl::string_view GetReadableRegion() const {\n return absl::string_view(storage_ + read_idx_, write_idx_ - read_idx_);\n }\n int Read(char* bytes, int size);\n void Clear() { read_idx_ = write_idx_ = 0; }\n void Reserve(int size);\n void AdvanceReadablePtr(int amount_to_advance);\n void AdvanceWritablePtr(int amount_to_advance);\n ReleasedBuffer Release();\n private:\n friend class test::SimpleBufferTest;\n char* storage_ = nullptr;\n int write_idx_ = 0;\n int read_idx_ = 0;\n int storage_size_ = 0;\n};\n} \n#endif \n#include \"quiche/balsa/simple_buffer.h\"\n#include \n#include \n#include \n#include \"quiche/common/platform/api/quiche_bug_tracker.h\"\n#include \"quiche/common/platform/api/quiche_logging.h\"\nnamespace quiche {\nconstexpr int kMinimumSimpleBufferSize = 10;\nSimpleBuffer::SimpleBuffer(int size) { Reserve(size); }\nint SimpleBuffer::Write(const char* bytes, int size) {\n if (size <= 0) {\n QUICHE_BUG_IF(simple_buffer_write_negative_size, size < 0)\n << \"size must not be negative: \" << size;\n return 0;\n }\n Reserve(size);\n memcpy(storage_ + write_idx_, bytes, size);\n AdvanceWritablePtr(size);\n return size;\n}\nint SimpleBuffer::Read(char* bytes, int size) {\n if (size < 0) {\n QUICHE_BUG(simple_buffer_read_negative_size)\n << \"size must not be negative: \" << size;\n return 0;\n }\n char* read_ptr = nullptr;\n int read_size = 0;\n GetReadablePtr(&read_ptr, &read_size);\n read_size = std::min(read_size, size);\n if (read_size == 0) {\n return 0;\n }\n memcpy(bytes, read_ptr, read_size);\n AdvanceReadablePtr(read_size);\n return read_size;\n}\nvoid SimpleBuffer::Reserve(int size) {\n if (size < 0) {\n QUICHE_BUG(simple_buffer_reserve_negative_size)\n << \"size must not be negative: \" << size;\n return;\n }\n if (size == 0 || storage_size_ - write_idx_ >= size) {\n return;\n }\n char* read_ptr = nullptr;\n int read_size = 0;\n GetReadablePtr(&read_ptr, &read_size);\n if (read_ptr == nullptr) {\n QUICHE_DCHECK_EQ(0, read_size);\n size = std::max(size, kMinimumSimpleBufferSize);\n storage_ = new char[size];\n storage_size_ = size;\n return;\n }\n if (read_size + size <= storage_size_) {\n memmove(storage_, read_ptr, read_size);\n read_idx_ = 0;\n write_idx_ = read_size;\n return;\n }\n storage_size_ = std::max(2 * storage_size_, size + read_size);\n char* new_storage = new char[storage_size_];\n memcpy(new_storage, read_ptr, read_size);\n delete[] storage_;\n read_idx_ = 0;\n write_idx_ = read_size;\n storage_ = new_storage;\n}\nvoid SimpleBuffer::AdvanceReadablePtr(int amount_to_advance) {\n if (amount_to_advance < 0) {\n QUICHE_BUG(simple_buffer_advance_read_negative_arg)\n << \"amount_to_advance must not be negative: \" << amount_to_advance;\n return;\n }\n read_idx_ += amount_to_advance;\n if (read_idx_ > write_idx_) {\n QUICHE_BUG(simple_buffer_read_ptr_too_far)\n << \"error: readable pointer advanced beyond writable one\";\n read_idx_ = write_idx_;\n }\n if (read_idx_ == write_idx_) {\n Clear();\n }\n}\nvoid SimpleBuffer::AdvanceWritablePtr(int amount_to_advance) {\n if (amount_to_advance < 0) {\n QUICHE_BUG(simple_buffer_advance_write_negative_arg)\n << \"amount_to_advance must not be negative: \" << amount_to_advance;\n return;\n }\n write_idx_ += amount_to_advance;\n if (write_idx_ > storage_size_) {\n QUICHE_BUG(simple_buffer_write_ptr_too_far)\n << \"error: writable pointer advanced beyond end of storage\";\n write_idx_ = storage_size_;\n }\n}\nSimpleBuffer::ReleasedBuffer SimpleBuffer::Release() {\n if (write_idx_ == 0) {\n return ReleasedBuffer{nullptr, 0};\n }\n ReleasedBuffer buffer{std::unique_ptr(storage_),\n static_cast(write_idx_)};\n Clear();\n storage_ = nullptr;\n storage_size_ = 0;\n return buffer;\n}\n} "},"Unit Test - (Ground Truth)":{"kind":"string","value":"#include \"quiche/balsa/simple_buffer.h\"\n#include \n#include \"absl/strings/string_view.h\"\n#include \"quiche/common/platform/api/quiche_expect_bug.h\"\n#include \"quiche/common/platform/api/quiche_test.h\"\nnamespace quiche {\nnamespace test {\nnamespace {\nconstexpr int kMinimumSimpleBufferSize = 10;\nconst char ibuf[] = {\n \"123456789!@#$%^&*()abcdefghijklmnopqrstu\"\n \"123456789!@#$%^&*()abcdefghijklmnopqrstu\"\n \"123456789!@#$%^&*()abcdefghijklmnopqrstu\"\n \"123456789!@#$%^&*()abcdefghijklmnopqrstu\"\n \"123456789!@#$%^&*()abcdefghijklmnopqrstu\"};\n} \nclass SimpleBufferTest : public QuicheTest {\n public:\n static char* storage(SimpleBuffer& buffer) { return buffer.storage_; }\n static int write_idx(SimpleBuffer& buffer) { return buffer.write_idx_; }\n static int read_idx(SimpleBuffer& buffer) { return buffer.read_idx_; }\n static int storage_size(SimpleBuffer& buffer) { return buffer.storage_size_; }\n};\nnamespace {\nTEST_F(SimpleBufferTest, CreationWithSize) {\n SimpleBuffer buffer1(5);\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer1));\n SimpleBuffer buffer2(25);\n EXPECT_EQ(25, storage_size(buffer2));\n}\nTEST_F(SimpleBufferTest, CreationWithZeroSize) {\n SimpleBuffer buffer(0);\n EXPECT_EQ(0, storage_size(buffer));\n EXPECT_EQ(4, buffer.Write(ibuf, 4));\n EXPECT_EQ(4, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(4, buffer.ReadableBytes());\n}\nTEST_F(SimpleBufferTest, ReadZeroBytes) {\n SimpleBuffer buffer;\n EXPECT_EQ(0, buffer.Read(nullptr, 0));\n}\nTEST_F(SimpleBufferTest, WriteZeroFromNullptr) {\n SimpleBuffer buffer;\n EXPECT_EQ(0, buffer.Write(nullptr, 0));\n}\nTEST(SimpleBufferExpectBug, ReserveNegativeSize) {\n SimpleBuffer buffer;\n EXPECT_QUICHE_BUG(buffer.Reserve(-1), \"size must not be negative\");\n}\nTEST(SimpleBufferExpectBug, ReadNegativeSize) {\n SimpleBuffer buffer;\n EXPECT_QUICHE_BUG(buffer.Read(nullptr, -1), \"size must not be negative\");\n}\nTEST(SimpleBufferExpectBug, WriteNegativeSize) {\n SimpleBuffer buffer;\n EXPECT_QUICHE_BUG(buffer.Write(nullptr, -1), \"size must not be negative\");\n}\nTEST_F(SimpleBufferTest, Basics) {\n SimpleBuffer buffer;\n EXPECT_TRUE(buffer.Empty());\n EXPECT_EQ(\"\", buffer.GetReadableRegion());\n EXPECT_EQ(0, storage_size(buffer));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n char* readable_ptr = nullptr;\n int readable_size = 0;\n buffer.GetReadablePtr(&readable_ptr, &readable_size);\n char* writeable_ptr = nullptr;\n int writable_size = 0;\n buffer.GetWritablePtr(&writeable_ptr, &writable_size);\n EXPECT_EQ(storage(buffer), readable_ptr);\n EXPECT_EQ(0, readable_size);\n EXPECT_EQ(storage(buffer), writeable_ptr);\n EXPECT_EQ(0, writable_size);\n EXPECT_EQ(0, buffer.ReadableBytes());\n const SimpleBuffer buffer2;\n EXPECT_EQ(0, buffer2.ReadableBytes());\n}\nTEST_F(SimpleBufferTest, BasicWR) {\n SimpleBuffer buffer;\n EXPECT_EQ(4, buffer.Write(ibuf, 4));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(4, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(4, buffer.ReadableBytes());\n EXPECT_EQ(\"1234\", buffer.GetReadableRegion());\n int bytes_written = 4;\n EXPECT_TRUE(!buffer.Empty());\n char* readable_ptr = nullptr;\n int readable_size = 0;\n buffer.GetReadablePtr(&readable_ptr, &readable_size);\n char* writeable_ptr = nullptr;\n int writable_size = 0;\n buffer.GetWritablePtr(&writeable_ptr, &writable_size);\n EXPECT_EQ(storage(buffer), readable_ptr);\n EXPECT_EQ(4, readable_size);\n EXPECT_EQ(storage(buffer) + 4, writeable_ptr);\n EXPECT_EQ(6, writable_size);\n char obuf[ABSL_ARRAYSIZE(ibuf)];\n int bytes_read = 0;\n EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 40));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(0, buffer.ReadableBytes());\n EXPECT_EQ(\"\", buffer.GetReadableRegion());\n bytes_read += 4;\n EXPECT_TRUE(buffer.Empty());\n buffer.GetReadablePtr(&readable_ptr, &readable_size);\n buffer.GetWritablePtr(&writeable_ptr, &writable_size);\n EXPECT_EQ(storage(buffer), readable_ptr);\n EXPECT_EQ(0, readable_size);\n EXPECT_EQ(storage(buffer), writeable_ptr);\n EXPECT_EQ(kMinimumSimpleBufferSize, writable_size);\n EXPECT_EQ(bytes_written, bytes_read);\n for (int i = 0; i < bytes_read; ++i) {\n EXPECT_EQ(obuf[i], ibuf[i]);\n }\n EXPECT_EQ(10, buffer.Write(ibuf + bytes_written, 10));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(10, write_idx(buffer));\n EXPECT_EQ(10, storage_size(buffer));\n EXPECT_EQ(10, buffer.ReadableBytes());\n bytes_written += 10;\n EXPECT_TRUE(!buffer.Empty());\n EXPECT_EQ(6, buffer.Read(obuf + bytes_read, 6));\n EXPECT_EQ(6, read_idx(buffer));\n EXPECT_EQ(10, write_idx(buffer));\n EXPECT_EQ(10, storage_size(buffer));\n EXPECT_EQ(4, buffer.ReadableBytes());\n bytes_read += 6;\n EXPECT_TRUE(!buffer.Empty());\n EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 7));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(10, storage_size(buffer));\n EXPECT_EQ(0, buffer.ReadableBytes());\n bytes_read += 4;\n EXPECT_TRUE(buffer.Empty());\n EXPECT_EQ(bytes_written, bytes_read);\n for (int i = 0; i < bytes_read; ++i) {\n EXPECT_EQ(obuf[i], ibuf[i]);\n }\n}\nTEST_F(SimpleBufferTest, Reserve) {\n SimpleBuffer buffer;\n EXPECT_EQ(0, storage_size(buffer));\n buffer.WriteString(\"foo\");\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n buffer.Reserve(kMinimumSimpleBufferSize + 1);\n EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));\n buffer.Clear();\n buffer.AdvanceWritablePtr(kMinimumSimpleBufferSize);\n buffer.AdvanceReadablePtr(kMinimumSimpleBufferSize - 2);\n EXPECT_EQ(kMinimumSimpleBufferSize, write_idx(buffer));\n EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));\n buffer.Reserve(kMinimumSimpleBufferSize + 1);\n EXPECT_EQ(2, write_idx(buffer));\n EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));\n}\nTEST_F(SimpleBufferTest, Extend) {\n SimpleBuffer buffer;\n EXPECT_EQ(7, buffer.Write(ibuf, 7));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(7, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(7, buffer.ReadableBytes());\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(7, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(7, buffer.ReadableBytes());\n int bytes_written = 7;\n EXPECT_EQ(4, buffer.Write(ibuf + bytes_written, 4));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(11, write_idx(buffer));\n EXPECT_EQ(20, storage_size(buffer));\n EXPECT_EQ(11, buffer.ReadableBytes());\n bytes_written += 4;\n char obuf[ABSL_ARRAYSIZE(ibuf)];\n EXPECT_EQ(11, buffer.Read(obuf, 11));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(20, storage_size(buffer));\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(0, buffer.ReadableBytes());\n const int bytes_read = 11;\n EXPECT_EQ(bytes_written, bytes_read);\n for (int i = 0; i < bytes_read; ++i) {\n EXPECT_EQ(obuf[i], ibuf[i]);\n }\n}\nTEST_F(SimpleBufferTest, Clear) {\n SimpleBuffer buffer;\n buffer.Clear();\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(0, storage_size(buffer));\n EXPECT_EQ(0, buffer.ReadableBytes());\n buffer.WriteString(\"foo\");\n buffer.Clear();\n EXPECT_EQ(0, read_idx(buffer));\n EXPECT_EQ(0, write_idx(buffer));\n EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));\n EXPECT_EQ(0, buffer.ReadableBytes());\n}\nTEST_F(SimpleBufferTest, LongWrite) {\n SimpleBuffer buffer;\n std::string s1 = \"HTTP/1.1 500 Service Unavailable\";\n buffer.Write(s1.data(), s1.size());\n buffer.Write(\"\\r\\n\", 2);\n std::string key = \"Connection\";\n std::string value = \"close\";\n buffer.Write(key.data(), key.size());\n buffer.Write(\": \", 2);\n buffer.Write(value.data(), value.size());\n buffer.Write(\"\\r\\n\", 2);\n buffer.Write(\"\\r\\n\", 2);\n std::string message =\n \"\\n\"\n \"\\n\"\n \"