ID
int64 0
2.65k
| Language
stringclasses 1
value | Repository Name
stringclasses 14
values | File Name
stringlengths 2
48
| File Path in Repository
stringlengths 11
111
⌀ | File Path for Unit Test
stringlengths 16
116
⌀ | Code
stringlengths 411
31.4k
| Unit Test - (Ground Truth)
stringlengths 40
32.1k
|
---|---|---|---|---|---|---|---|
400 | cpp | google/quiche | nghttp2_data_provider | quiche/http2/adapter/nghttp2_data_provider.cc | quiche/http2/adapter/nghttp2_data_provider_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_NGHTTP2_DATA_PROVIDER_H_
#define QUICHE_HTTP2_ADAPTER_NGHTTP2_DATA_PROVIDER_H_
#include <cstdint>
#include <memory>
#include "quiche/http2/adapter/data_source.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2.h"
namespace http2 {
namespace adapter {
namespace callbacks {
ssize_t VisitorReadCallback(Http2VisitorInterface& visitor, int32_t stream_id,
size_t max_length, uint32_t* data_flags);
ssize_t DataFrameSourceReadCallback(DataFrameSource& source, size_t length,
uint32_t* data_flags);
}
}
}
#endif
#include "quiche/http2/adapter/nghttp2_data_provider.h"
#include <memory>
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2_util.h"
namespace http2 {
namespace adapter {
namespace callbacks {
ssize_t VisitorReadCallback(Http2VisitorInterface& visitor, int32_t stream_id,
size_t max_length, uint32_t* data_flags) {
*data_flags |= NGHTTP2_DATA_FLAG_NO_COPY;
auto [payload_length, end_data, end_stream] =
visitor.OnReadyToSendDataForStream(stream_id, max_length);
if (payload_length == 0 && !end_data) {
return NGHTTP2_ERR_DEFERRED;
} else if (payload_length == DataFrameSource::kError) {
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
if (end_data) {
*data_flags |= NGHTTP2_DATA_FLAG_EOF;
}
if (!end_stream) {
*data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
}
return payload_length;
}
ssize_t DataFrameSourceReadCallback(DataFrameSource& source, size_t length,
uint32_t* data_flags) {
*data_flags |= NGHTTP2_DATA_FLAG_NO_COPY;
auto [result_length, done] = source.SelectPayloadLength(length);
if (result_length == 0 && !done) {
return NGHTTP2_ERR_DEFERRED;
} else if (result_length == DataFrameSource::kError) {
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
if (done) {
*data_flags |= NGHTTP2_DATA_FLAG_EOF;
}
if (!source.send_fin()) {
*data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM;
}
return result_length;
}
}
}
} | #include "quiche/http2/adapter/nghttp2_data_provider.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
const size_t kFrameHeaderSize = 9;
TEST(DataFrameSourceTest, ReadLessThanSourceProvides) {
const int32_t kStreamId = 1;
TestVisitor visitor;
visitor.AppendPayloadForStream(kStreamId, "Example payload");
visitor.SetEndData(kStreamId, true);
VisitorDataSource source(visitor, kStreamId);
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result =
callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags);
ASSERT_EQ(kReadLength, result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_NO_END_STREAM,
data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
source.Send(ToStringView(framehd, kFrameHeaderSize), result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kReadLength);
}
TEST(VisitorTest, ReadLessThanSourceProvides) {
const int32_t kStreamId = 1;
TestVisitor visitor;
visitor.AppendPayloadForStream(kStreamId, "Example payload");
visitor.SetEndData(kStreamId, true);
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId,
kReadLength, &data_flags);
ASSERT_EQ(kReadLength, result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_NO_END_STREAM,
data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize),
result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kReadLength);
}
TEST(DataFrameSourceTest, ReadMoreThanSourceProvides) {
const int32_t kStreamId = 1;
const absl::string_view kPayload = "Example payload";
TestVisitor visitor;
visitor.AppendPayloadForStream(kStreamId, kPayload);
visitor.SetEndData(kStreamId, true);
VisitorDataSource source(visitor, kStreamId);
uint32_t data_flags = 0;
const size_t kReadLength = 30;
ssize_t result =
callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags);
ASSERT_EQ(kPayload.size(), result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
source.Send(ToStringView(framehd, kFrameHeaderSize), result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kPayload.size());
}
TEST(VisitorTest, ReadMoreThanSourceProvides) {
const int32_t kStreamId = 1;
const absl::string_view kPayload = "Example payload";
TestVisitor visitor;
visitor.AppendPayloadForStream(kStreamId, kPayload);
visitor.SetEndData(kStreamId, true);
VisitorDataSource source(visitor, kStreamId);
uint32_t data_flags = 0;
const size_t kReadLength = 30;
ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId,
kReadLength, &data_flags);
ASSERT_EQ(kPayload.size(), result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize),
result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kPayload.size());
}
TEST(DataFrameSourceTest, ReadFromBlockedSource) {
const int32_t kStreamId = 1;
TestVisitor visitor;
VisitorDataSource source(visitor, kStreamId);
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result =
callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags);
EXPECT_EQ(NGHTTP2_ERR_DEFERRED, result);
}
TEST(VisitorTest, ReadFromBlockedSource) {
const int32_t kStreamId = 1;
TestVisitor visitor;
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId,
kReadLength, &data_flags);
EXPECT_EQ(NGHTTP2_ERR_DEFERRED, result);
}
TEST(DataFrameSourceTest, ReadFromZeroLengthSource) {
const int32_t kStreamId = 1;
TestVisitor visitor;
visitor.SetEndData(kStreamId, true);
VisitorDataSource source(visitor, kStreamId);
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result =
callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags);
ASSERT_EQ(0, result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
source.Send(ToStringView(framehd, kFrameHeaderSize), result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize);
}
TEST(VisitorTest, ReadFromZeroLengthSource) {
const int32_t kStreamId = 1;
TestVisitor visitor;
visitor.SetEndData(kStreamId, true);
uint32_t data_flags = 0;
const size_t kReadLength = 10;
ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId,
kReadLength, &data_flags);
ASSERT_EQ(0, result);
EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags);
const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize),
result);
EXPECT_EQ(visitor.data().size(), kFrameHeaderSize);
}
}
}
} |
401 | cpp | google/quiche | nghttp2_session | quiche/http2/adapter/nghttp2_session.cc | quiche/http2/adapter/nghttp2_session_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_NGHTTP2_SESSION_H_
#define QUICHE_HTTP2_ADAPTER_NGHTTP2_SESSION_H_
#include <cstdint>
#include "quiche/http2/adapter/http2_session.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT NgHttp2Session : public Http2Session {
public:
NgHttp2Session(Perspective perspective,
nghttp2_session_callbacks_unique_ptr callbacks,
const nghttp2_option* options, void* userdata);
~NgHttp2Session() override;
int64_t ProcessBytes(absl::string_view bytes) override;
int Consume(Http2StreamId stream_id, size_t num_bytes) override;
bool want_read() const override;
bool want_write() const override;
int GetRemoteWindowSize() const override;
nghttp2_session* raw_ptr() const { return session_.get(); }
private:
nghttp2_session_unique_ptr session_;
Perspective perspective_;
};
}
}
#endif
#include "quiche/http2/adapter/nghttp2_session.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace adapter {
NgHttp2Session::NgHttp2Session(Perspective perspective,
nghttp2_session_callbacks_unique_ptr callbacks,
const nghttp2_option* options, void* userdata)
: session_(MakeSessionPtr(nullptr)), perspective_(perspective) {
nghttp2_session* session;
switch (perspective_) {
case Perspective::kClient:
nghttp2_session_client_new2(&session, callbacks.get(), userdata, options);
break;
case Perspective::kServer:
nghttp2_session_server_new2(&session, callbacks.get(), userdata, options);
break;
}
session_ = MakeSessionPtr(session);
}
NgHttp2Session::~NgHttp2Session() {
const bool pending_reads = nghttp2_session_want_read(session_.get()) != 0;
const bool pending_writes = nghttp2_session_want_write(session_.get()) != 0;
if (pending_reads || pending_writes) {
QUICHE_VLOG(1) << "Shutting down connection with pending reads: "
<< pending_reads << " or pending writes: " << pending_writes;
}
}
int64_t NgHttp2Session::ProcessBytes(absl::string_view bytes) {
return nghttp2_session_mem_recv(
session_.get(), reinterpret_cast<const uint8_t*>(bytes.data()),
bytes.size());
}
int NgHttp2Session::Consume(Http2StreamId stream_id, size_t num_bytes) {
return nghttp2_session_consume(session_.get(), stream_id, num_bytes);
}
bool NgHttp2Session::want_read() const {
return nghttp2_session_want_read(session_.get()) != 0;
}
bool NgHttp2Session::want_write() const {
return nghttp2_session_want_write(session_.get()) != 0;
}
int NgHttp2Session::GetRemoteWindowSize() const {
return nghttp2_session_get_remote_window_size(session_.get());
}
}
} | #include "quiche/http2/adapter/nghttp2_session.h"
#include <string>
#include <vector>
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/http2/adapter/nghttp2_callbacks.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using testing::_;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
};
class NgHttp2SessionTest : public quiche::test::QuicheTest {
public:
void SetUp() override {
nghttp2_option_new(&options_);
nghttp2_option_set_no_auto_window_update(options_, 1);
}
void TearDown() override { nghttp2_option_del(options_); }
nghttp2_session_callbacks_unique_ptr CreateCallbacks() {
nghttp2_session_callbacks_unique_ptr callbacks = callbacks::Create(nullptr);
return callbacks;
}
TestVisitor visitor_;
nghttp2_option* options_ = nullptr;
};
TEST_F(NgHttp2SessionTest, ClientConstruction) {
NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_,
&visitor_);
EXPECT_TRUE(session.want_read());
EXPECT_FALSE(session.want_write());
EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize);
EXPECT_NE(session.raw_ptr(), nullptr);
}
TEST_F(NgHttp2SessionTest, ClientHandlesFrames) {
NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_,
&visitor_);
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
ASSERT_GT(visitor_.data().size(), 0);
const std::string initial_frames = TestFrameSequence()
.ServerPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor_, OnSettingsStart());
EXPECT_CALL(visitor_, OnSettingsEnd());
EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor_, OnPing(42, false));
EXPECT_CALL(visitor_, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor_, OnWindowUpdate(0, 1000));
const int64_t initial_result = session.ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_EQ(session.GetRemoteWindowSize(),
kInitialFlowControlWindowSize + 1000);
EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0));
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
absl::string_view serialized = visitor_.data();
ASSERT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::SETTINGS,
spdy::SpdyFrameType::PING}));
visitor_.Clear();
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const auto nvs1 = GetNghttp2Nvs(headers1);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const auto nvs2 = GetNghttp2Nvs(headers2);
const std::vector<Header> headers3 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/three"}});
const auto nvs3 = GetNghttp2Nvs(headers3);
const int32_t stream_id1 = nghttp2_submit_request(
session.raw_ptr(), nullptr, nvs1.data(), nvs1.size(), nullptr, nullptr);
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
const int32_t stream_id2 = nghttp2_submit_request(
session.raw_ptr(), nullptr, nvs2.data(), nvs2.size(), nullptr, nullptr);
ASSERT_GT(stream_id2, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id2;
const int32_t stream_id3 = nghttp2_submit_request(
session.raw_ptr(), nullptr, nvs3.data(), nvs3.size(), nullptr, nullptr);
ASSERT_GT(stream_id3, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id3;
EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 1, _, 0x5));
EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 1, _, 0x5, 0));
EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 3, _, 0x5));
EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 3, _, 0x5, 0));
EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 5, _, 0x5));
EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 5, _, 0x5, 0));
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
serialized = visitor_.data();
EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::HEADERS,
spdy::SpdyFrameType::HEADERS,
spdy::SpdyFrameType::HEADERS}));
visitor_.Clear();
const std::string stream_frames =
TestFrameSequence()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.RstStream(3, Http2ErrorCode::INTERNAL_ERROR)
.GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")
.Serialize();
EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor_, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor_,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor_, OnEndHeadersForStream(1));
EXPECT_CALL(visitor_, OnFrameHeader(1, 26, DATA, 0));
EXPECT_CALL(visitor_, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor_, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor_, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor_, OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor_, OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor_, OnFrameHeader(0, 19, GOAWAY, 0));
EXPECT_CALL(visitor_,
OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!"));
const int64_t stream_result = session.ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_TRUE(session.want_read());
EXPECT_CALL(visitor_, OnFrameHeader(1, 0, DATA, 1));
EXPECT_CALL(visitor_, OnBeginDataForStream(1, 0));
EXPECT_CALL(visitor_, OnEndStream(1));
EXPECT_CALL(visitor_, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
EXPECT_CALL(visitor_, OnFrameHeader(5, 4, RST_STREAM, 0));
EXPECT_CALL(visitor_, OnRstStream(5, Http2ErrorCode::REFUSED_STREAM));
EXPECT_CALL(visitor_, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM));
session.ProcessBytes(TestFrameSequence()
.Data(1, "", true)
.RstStream(5, Http2ErrorCode::REFUSED_STREAM)
.Serialize());
EXPECT_FALSE(session.want_read());
EXPECT_FALSE(session.want_write());
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
serialized = visitor_.data();
EXPECT_EQ(serialized.size(), 0);
}
TEST_F(NgHttp2SessionTest, ServerConstruction) {
NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_,
&visitor_);
EXPECT_TRUE(session.want_read());
EXPECT_FALSE(session.want_write());
EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize);
EXPECT_NE(session.raw_ptr(), nullptr);
}
TEST_F(NgHttp2SessionTest, ServerHandlesFrames) {
NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_,
&visitor_);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.RstStream(3, Http2ErrorCode::CANCEL)
.Ping(47)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor_, OnSettingsStart());
EXPECT_CALL(visitor_, OnSettingsEnd());
EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor_, OnPing(42, false));
EXPECT_CALL(visitor_, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor_, OnWindowUpdate(0, 1000));
EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor_, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor_, OnEndHeadersForStream(1));
EXPECT_CALL(visitor_, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor_, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor_, OnFrameHeader(1, 25, DATA, 0));
EXPECT_CALL(visitor_, OnBeginDataForStream(1, 25));
EXPECT_CALL(visitor_, OnDataForStream(1, "This is the request body."));
EXPECT_CALL(visitor_, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor_, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor_, OnHeaderForStream(3, ":method", "GET"));
EXPECT_CALL(visitor_, OnHeaderForStream(3, ":scheme", "http"));
EXPECT_CALL(visitor_, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor_, OnHeaderForStream(3, ":path", "/this/is/request/two"));
EXPECT_CALL(visitor_, OnEndHeadersForStream(3));
EXPECT_CALL(visitor_, OnEndStream(3));
EXPECT_CALL(visitor_, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor_, OnRstStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor_, OnCloseStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor_, OnPing(47, false));
const int64_t result = session.ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
EXPECT_EQ(session.GetRemoteWindowSize(),
kInitialFlowControlWindowSize + 1000);
EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0));
EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0));
EXPECT_TRUE(session.want_write());
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
absl::string_view serialized = visitor_.data();
EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::SETTINGS,
spdy::SpdyFrameType::PING,
spdy::SpdyFrameType::PING}));
}
TEST_F(NgHttp2SessionTest, NullPayload) {
NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_,
&visitor_);
void* payload = nullptr;
const int result = nghttp2_submit_extension(
session.raw_ptr(), kMetadataFrameType, 0, 1, payload);
ASSERT_EQ(0, result);
EXPECT_TRUE(session.want_write());
int send_result = -1;
EXPECT_QUICHE_BUG(
{
send_result = nghttp2_session_send(session.raw_ptr());
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, send_result);
},
"Extension frame payload for stream 1 is null!");
}
TEST_F(NgHttp2SessionTest, ServerSeesErrorOnEndStream) {
NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_,
&visitor_);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"}},
false)
.Data(1, "Request body", true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor_, OnSettingsStart());
EXPECT_CALL(visitor_, OnSettingsEnd());
EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 0x4));
EXPECT_CALL(visitor_, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor_, OnHeaderForStream(1, ":path", "/"));
EXPECT_CALL(visitor_, OnEndHeadersForStream(1));
EXPECT_CALL(visitor_, OnFrameHeader(1, _, DATA, 0x1));
EXPECT_CALL(visitor_, OnBeginDataForStream(1, _));
EXPECT_CALL(visitor_, OnDataForStream(1, "Request body"));
EXPECT_CALL(visitor_, OnEndStream(1)).WillOnce(testing::Return(false));
const int64_t result = session.ProcessBytes(frames);
EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result);
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr()));
EXPECT_THAT(visitor_.data(), EqualsFrames({spdy::SpdyFrameType::SETTINGS}));
visitor_.Clear();
EXPECT_FALSE(session.want_write());
}
}
}
}
} |
402 | cpp | google/quiche | window_manager | quiche/http2/adapter/window_manager.cc | quiche/http2/adapter/window_manager_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_WINDOW_MANAGER_H_
#define QUICHE_HTTP2_ADAPTER_WINDOW_MANAGER_H_
#include <stddef.h>
#include <stdint.h>
#include <functional>
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_callbacks.h"
namespace http2 {
namespace adapter {
namespace test {
class WindowManagerPeer;
}
class QUICHE_EXPORT WindowManager {
public:
using WindowUpdateListener = quiche::MultiUseCallback<void(int64_t)>;
using ShouldWindowUpdateFn = bool (*)(int64_t limit, int64_t size,
int64_t delta);
WindowManager(int64_t window_size_limit, WindowUpdateListener listener,
ShouldWindowUpdateFn should_window_update_fn = {},
bool update_window_on_notify = true);
int64_t CurrentWindowSize() const { return window_; }
int64_t WindowSizeLimit() const { return limit_; }
void OnWindowSizeLimitChange(int64_t new_limit);
void SetWindowSizeLimit(int64_t new_limit);
bool MarkDataBuffered(int64_t bytes);
void MarkDataFlushed(int64_t bytes);
void MarkWindowConsumed(int64_t bytes) {
MarkDataBuffered(bytes);
MarkDataFlushed(bytes);
}
void IncreaseWindow(int64_t delta) { window_ += delta; }
private:
friend class test::WindowManagerPeer;
void MaybeNotifyListener();
int64_t limit_;
int64_t window_;
int64_t buffered_;
WindowUpdateListener listener_;
ShouldWindowUpdateFn should_window_update_fn_;
bool update_window_on_notify_;
};
}
}
#endif
#include "quiche/http2/adapter/window_manager.h"
#include <utility>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace adapter {
bool DefaultShouldWindowUpdateFn(int64_t limit, int64_t window, int64_t delta) {
const int64_t kDesiredMinWindow = limit / 2;
const int64_t kDesiredMinDelta = limit / 3;
if (delta >= kDesiredMinDelta) {
return true;
} else if (window < kDesiredMinWindow) {
return true;
}
return false;
}
WindowManager::WindowManager(int64_t window_size_limit,
WindowUpdateListener listener,
ShouldWindowUpdateFn should_window_update_fn,
bool update_window_on_notify)
: limit_(window_size_limit),
window_(window_size_limit),
buffered_(0),
listener_(std::move(listener)),
should_window_update_fn_(std::move(should_window_update_fn)),
update_window_on_notify_(update_window_on_notify) {
if (!should_window_update_fn_) {
should_window_update_fn_ = DefaultShouldWindowUpdateFn;
}
}
void WindowManager::OnWindowSizeLimitChange(const int64_t new_limit) {
QUICHE_VLOG(2) << "WindowManager@" << this
<< " OnWindowSizeLimitChange from old limit of " << limit_
<< " to new limit of " << new_limit;
window_ += (new_limit - limit_);
limit_ = new_limit;
}
void WindowManager::SetWindowSizeLimit(int64_t new_limit) {
QUICHE_VLOG(2) << "WindowManager@" << this
<< " SetWindowSizeLimit from old limit of " << limit_
<< " to new limit of " << new_limit;
limit_ = new_limit;
MaybeNotifyListener();
}
bool WindowManager::MarkDataBuffered(int64_t bytes) {
QUICHE_VLOG(2) << "WindowManager@" << this << " window: " << window_
<< " bytes: " << bytes;
if (window_ < bytes) {
QUICHE_VLOG(2) << "WindowManager@" << this << " window underflow "
<< "window: " << window_ << " bytes: " << bytes;
window_ = 0;
} else {
window_ -= bytes;
}
buffered_ += bytes;
if (window_ == 0) {
MaybeNotifyListener();
}
return window_ > 0;
}
void WindowManager::MarkDataFlushed(int64_t bytes) {
QUICHE_VLOG(2) << "WindowManager@" << this << " buffered: " << buffered_
<< " bytes: " << bytes;
if (buffered_ < bytes) {
QUICHE_BUG(bug_2816_1) << "WindowManager@" << this << " buffered underflow "
<< "buffered_: " << buffered_ << " bytes: " << bytes;
buffered_ = 0;
} else {
buffered_ -= bytes;
}
MaybeNotifyListener();
}
void WindowManager::MaybeNotifyListener() {
const int64_t delta = limit_ - (buffered_ + window_);
if (should_window_update_fn_(limit_, window_, delta) && delta > 0) {
QUICHE_VLOG(2) << "WindowManager@" << this
<< " Informing listener of delta: " << delta;
listener_(delta);
if (update_window_on_notify_) {
window_ += delta;
}
}
}
}
} | #include "quiche/http2/adapter/window_manager.h"
#include <algorithm>
#include <list>
#include "absl/functional/bind_front.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
class WindowManagerPeer {
public:
explicit WindowManagerPeer(const WindowManager& wm) : wm_(wm) {}
int64_t buffered() { return wm_.buffered_; }
private:
const WindowManager& wm_;
};
namespace {
class WindowManagerTest : public quiche::test::QuicheTest {
protected:
WindowManagerTest()
: wm_(kDefaultLimit, absl::bind_front(&WindowManagerTest::OnCall, this)),
peer_(wm_) {}
void OnCall(int64_t s) { call_sequence_.push_back(s); }
const int64_t kDefaultLimit = 32 * 1024 * 3;
std::list<int64_t> call_sequence_;
WindowManager wm_;
WindowManagerPeer peer_;
::http2::test::Http2Random random_;
};
TEST_F(WindowManagerTest, NoOps) {
wm_.SetWindowSizeLimit(kDefaultLimit);
wm_.SetWindowSizeLimit(0);
wm_.SetWindowSizeLimit(kDefaultLimit);
wm_.MarkDataBuffered(0);
wm_.MarkDataFlushed(0);
EXPECT_TRUE(call_sequence_.empty());
}
TEST_F(WindowManagerTest, DataOnlyBuffered) {
int64_t total = 0;
while (total < kDefaultLimit) {
int64_t s = std::min<int64_t>(kDefaultLimit - total, random_.Uniform(1024));
total += s;
wm_.MarkDataBuffered(s);
}
EXPECT_THAT(call_sequence_, ::testing::IsEmpty());
}
TEST_F(WindowManagerTest, DataBufferedAndFlushed) {
int64_t total_buffered = 0;
int64_t total_flushed = 0;
while (call_sequence_.empty()) {
int64_t buffered = std::min<int64_t>(kDefaultLimit - total_buffered,
random_.Uniform(1024));
wm_.MarkDataBuffered(buffered);
total_buffered += buffered;
EXPECT_TRUE(call_sequence_.empty());
int64_t flushed = (total_buffered - total_flushed) > 0
? random_.Uniform(total_buffered - total_flushed)
: 0;
wm_.MarkDataFlushed(flushed);
total_flushed += flushed;
}
EXPECT_GE(total_buffered, kDefaultLimit / 3);
}
TEST_F(WindowManagerTest, AvoidWindowUnderflow) {
EXPECT_EQ(wm_.CurrentWindowSize(), wm_.WindowSizeLimit());
wm_.MarkDataBuffered(wm_.WindowSizeLimit() + 1);
EXPECT_EQ(wm_.CurrentWindowSize(), 0u);
}
TEST_F(WindowManagerTest, AvoidBufferedUnderflow) {
EXPECT_EQ(peer_.buffered(), 0u);
EXPECT_QUICHE_BUG(wm_.MarkDataFlushed(1), "buffered underflow");
EXPECT_EQ(peer_.buffered(), 0u);
wm_.MarkDataBuffered(42);
EXPECT_EQ(peer_.buffered(), 42u);
EXPECT_QUICHE_BUG(
{
wm_.MarkDataFlushed(43);
EXPECT_EQ(peer_.buffered(), 0u);
},
"buffered underflow");
}
TEST_F(WindowManagerTest, WindowConsumed) {
int64_t consumed = kDefaultLimit / 3 - 1;
wm_.MarkWindowConsumed(consumed);
EXPECT_TRUE(call_sequence_.empty());
const int64_t extra = 1;
wm_.MarkWindowConsumed(extra);
EXPECT_THAT(call_sequence_, testing::ElementsAre(consumed + extra));
}
TEST_F(WindowManagerTest, ListenerCalledOnSizeUpdate) {
wm_.SetWindowSizeLimit(kDefaultLimit - 1024);
EXPECT_TRUE(call_sequence_.empty());
wm_.SetWindowSizeLimit(kDefaultLimit * 5);
EXPECT_THAT(call_sequence_, testing::ElementsAre(kDefaultLimit * 4));
}
TEST_F(WindowManagerTest, WindowUpdateAfterLimitDecreased) {
wm_.MarkDataBuffered(kDefaultLimit - 1024);
wm_.SetWindowSizeLimit(kDefaultLimit - 2048);
wm_.MarkDataFlushed(512);
EXPECT_TRUE(call_sequence_.empty());
wm_.MarkDataFlushed(512);
EXPECT_TRUE(call_sequence_.empty());
wm_.MarkDataFlushed(512);
EXPECT_TRUE(call_sequence_.empty());
wm_.MarkDataFlushed(1024);
EXPECT_THAT(call_sequence_, testing::ElementsAre(512));
}
TEST_F(WindowManagerTest, ZeroWindowNotification) {
wm_.MarkWindowConsumed(1);
wm_.MarkDataBuffered(kDefaultLimit - 1);
EXPECT_THAT(call_sequence_, testing::ElementsAre(1));
}
TEST_F(WindowManagerTest, OnWindowSizeLimitChange) {
wm_.MarkDataBuffered(10000);
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 10000);
EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit);
wm_.OnWindowSizeLimitChange(kDefaultLimit + 1000);
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 9000);
EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit + 1000);
wm_.OnWindowSizeLimitChange(kDefaultLimit - 1000);
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 11000);
EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit - 1000);
}
TEST_F(WindowManagerTest, NegativeWindowSize) {
wm_.MarkDataBuffered(80000);
EXPECT_EQ(wm_.CurrentWindowSize(), 18304);
wm_.OnWindowSizeLimitChange(65535);
EXPECT_EQ(wm_.CurrentWindowSize(), -14465);
wm_.MarkDataFlushed(70000);
EXPECT_EQ(wm_.CurrentWindowSize(), 55535);
EXPECT_THAT(call_sequence_, testing::ElementsAre(70000));
}
TEST_F(WindowManagerTest, IncreaseWindow) {
wm_.MarkDataBuffered(1000);
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 1000);
EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit);
wm_.IncreaseWindow(5000);
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit + 4000);
EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit);
wm_.MarkWindowConsumed(80000);
EXPECT_THAT(call_sequence_, testing::ElementsAre(75000));
EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 1000);
}
TEST(WindowManagerNoUpdateTest, NoWindowUpdateOnListener) {
const int64_t kDefaultLimit = 65535;
std::list<int64_t> call_sequence1;
WindowManager wm1(
kDefaultLimit,
[&call_sequence1](int64_t delta) { call_sequence1.push_back(delta); },
{},
true);
std::list<int64_t> call_sequence2;
WindowManager wm2(
kDefaultLimit,
[&call_sequence2](int64_t delta) { call_sequence2.push_back(delta); },
{},
false);
const int64_t consumed = kDefaultLimit / 3 - 1;
wm1.MarkWindowConsumed(consumed);
EXPECT_TRUE(call_sequence1.empty());
wm2.MarkWindowConsumed(consumed);
EXPECT_TRUE(call_sequence2.empty());
EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit - consumed);
EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit - consumed);
const int64_t extra = 1;
wm1.MarkWindowConsumed(extra);
EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed + extra));
EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit);
call_sequence1.clear();
wm2.MarkWindowConsumed(extra);
EXPECT_THAT(call_sequence2, testing::ElementsAre(consumed + extra));
EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit - (consumed + extra));
call_sequence2.clear();
wm2.IncreaseWindow(consumed + extra);
EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit);
wm1.SetWindowSizeLimit(kDefaultLimit * 5);
EXPECT_THAT(call_sequence1, testing::ElementsAre(kDefaultLimit * 4));
EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit * 5);
wm2.SetWindowSizeLimit(kDefaultLimit * 5);
EXPECT_THAT(call_sequence2, testing::ElementsAre(kDefaultLimit * 4));
EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit);
}
TEST(WindowManagerShouldUpdateTest, CustomShouldWindowUpdateFn) {
const int64_t kDefaultLimit = 65535;
std::list<int64_t> call_sequence1;
WindowManager wm1(
kDefaultLimit,
[&call_sequence1](int64_t delta) { call_sequence1.push_back(delta); },
[](int64_t , int64_t , int64_t ) {
return true;
});
std::list<int64_t> call_sequence2;
WindowManager wm2(
kDefaultLimit,
[&call_sequence2](int64_t delta) { call_sequence2.push_back(delta); },
[](int64_t , int64_t , int64_t ) {
return false;
});
std::list<int64_t> call_sequence3;
WindowManager wm3(
kDefaultLimit,
[&call_sequence3](int64_t delta) { call_sequence3.push_back(delta); },
[](int64_t limit, int64_t window, int64_t delta) {
return delta == limit - window;
});
const int64_t consumed = kDefaultLimit / 4;
wm1.MarkWindowConsumed(consumed);
EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed));
wm2.MarkWindowConsumed(consumed);
EXPECT_TRUE(call_sequence2.empty());
wm3.MarkWindowConsumed(consumed);
EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed));
const int64_t buffered = 42;
wm1.MarkDataBuffered(buffered);
EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed));
wm2.MarkDataBuffered(buffered);
EXPECT_TRUE(call_sequence2.empty());
wm3.MarkDataBuffered(buffered);
EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed));
wm1.MarkDataFlushed(buffered / 3);
EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed, buffered / 3));
wm2.MarkDataFlushed(buffered / 3);
EXPECT_TRUE(call_sequence2.empty());
wm3.MarkDataFlushed(buffered / 3);
EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed));
wm1.MarkDataFlushed(2 * buffered / 3);
EXPECT_THAT(call_sequence1,
testing::ElementsAre(consumed, buffered / 3, 2 * buffered / 3));
wm2.MarkDataFlushed(2 * buffered / 3);
EXPECT_TRUE(call_sequence2.empty());
wm3.MarkDataFlushed(2 * buffered / 3);
EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed, buffered));
}
}
}
}
} |
403 | cpp | google/quiche | callback_visitor | quiche/http2/adapter/callback_visitor.cc | quiche/http2/adapter/callback_visitor_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_CALLBACK_VISITOR_H_
#define QUICHE_HTTP2_ADAPTER_CALLBACK_VISITOR_H_
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_callbacks.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT CallbackVisitor : public Http2VisitorInterface {
public:
using StreamCloseListener =
quiche::MultiUseCallback<void(Http2StreamId stream_id)>;
explicit CallbackVisitor(Perspective perspective,
const nghttp2_session_callbacks& callbacks,
void* user_data);
int64_t OnReadyToSend(absl::string_view serialized) override;
DataFrameHeaderInfo OnReadyToSendDataForStream(Http2StreamId stream_id,
size_t max_length) override;
bool SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header,
size_t payload_bytes) override;
void OnConnectionError(ConnectionError error) override;
bool OnFrameHeader(Http2StreamId stream_id, size_t length, uint8_t type,
uint8_t flags) override;
void OnSettingsStart() override;
void OnSetting(Http2Setting setting) override;
void OnSettingsEnd() override;
void OnSettingsAck() override;
bool OnBeginHeadersForStream(Http2StreamId stream_id) override;
OnHeaderResult OnHeaderForStream(Http2StreamId stream_id,
absl::string_view name,
absl::string_view value) override;
bool OnEndHeadersForStream(Http2StreamId stream_id) override;
bool OnDataPaddingLength(Http2StreamId stream_id,
size_t padding_length) override;
bool OnBeginDataForStream(Http2StreamId stream_id,
size_t payload_length) override;
bool OnDataForStream(Http2StreamId stream_id,
absl::string_view data) override;
bool OnEndStream(Http2StreamId stream_id) override;
void OnRstStream(Http2StreamId stream_id, Http2ErrorCode error_code) override;
bool OnCloseStream(Http2StreamId stream_id,
Http2ErrorCode error_code) override;
void OnPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id, int weight,
bool exclusive) override;
void OnPing(Http2PingId ping_id, bool is_ack) override;
void OnPushPromiseForStream(Http2StreamId stream_id,
Http2StreamId promised_stream_id) override;
bool OnGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) override;
void OnWindowUpdate(Http2StreamId stream_id, int window_increment) override;
int OnBeforeFrameSent(uint8_t frame_type, Http2StreamId stream_id,
size_t length, uint8_t flags) override;
int OnFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length,
uint8_t flags, uint32_t error_code) override;
bool OnInvalidFrame(Http2StreamId stream_id,
InvalidFrameError error) override;
void OnBeginMetadataForStream(Http2StreamId stream_id,
size_t payload_length) override;
bool OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) override;
bool OnMetadataEndForStream(Http2StreamId stream_id) override;
std::pair<int64_t, bool> PackMetadataForStream(Http2StreamId stream_id,
uint8_t* dest,
size_t dest_len) override;
void OnErrorDebug(absl::string_view message) override;
size_t stream_map_size() const { return stream_map_.size(); }
void set_stream_close_listener(StreamCloseListener stream_close_listener) {
stream_close_listener_ = std::move(stream_close_listener);
}
private:
struct QUICHE_EXPORT StreamInfo {
bool before_sent_headers = false;
bool sent_headers = false;
bool received_headers = false;
};
using StreamInfoMap = absl::flat_hash_map<Http2StreamId, StreamInfo>;
void PopulateFrame(nghttp2_frame& frame, uint8_t frame_type,
Http2StreamId stream_id, size_t length, uint8_t flags,
uint32_t error_code, bool sent_headers);
StreamInfoMap::iterator GetStreamInfo(Http2StreamId stream_id);
StreamInfoMap stream_map_;
StreamCloseListener stream_close_listener_;
Perspective perspective_;
nghttp2_session_callbacks_unique_ptr callbacks_;
void* user_data_;
nghttp2_frame current_frame_;
std::vector<nghttp2_settings_entry> settings_;
size_t remaining_data_ = 0;
Http2StreamId stream_id_watermark_ = 0;
};
}
}
#endif
#include "quiche/http2/adapter/callback_visitor.h"
#include <cstring>
#include "absl/strings/escaping.h"
#include "quiche/http2/adapter/http2_util.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/common/quiche_endian.h"
#ifdef NGHTTP2_16
namespace {
using FunctionPtr = void (*)(void);
}
struct nghttp2_session_callbacks {
nghttp2_send_callback send_callback;
FunctionPtr send_callback2;
nghttp2_recv_callback recv_callback;
FunctionPtr recv_callback2;
nghttp2_on_frame_recv_callback on_frame_recv_callback;
nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback;
nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback;
nghttp2_before_frame_send_callback before_frame_send_callback;
nghttp2_on_frame_send_callback on_frame_send_callback;
nghttp2_on_frame_not_send_callback on_frame_not_send_callback;
nghttp2_on_stream_close_callback on_stream_close_callback;
nghttp2_on_begin_headers_callback on_begin_headers_callback;
nghttp2_on_header_callback on_header_callback;
nghttp2_on_header_callback2 on_header_callback2;
nghttp2_on_invalid_header_callback on_invalid_header_callback;
nghttp2_on_invalid_header_callback2 on_invalid_header_callback2;
nghttp2_select_padding_callback select_padding_callback;
FunctionPtr select_padding_callback2;
nghttp2_data_source_read_length_callback read_length_callback;
FunctionPtr read_length_callback2;
nghttp2_on_begin_frame_callback on_begin_frame_callback;
nghttp2_send_data_callback send_data_callback;
nghttp2_pack_extension_callback pack_extension_callback;
FunctionPtr pack_extension_callback2;
nghttp2_unpack_extension_callback unpack_extension_callback;
nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback;
nghttp2_error_callback error_callback;
nghttp2_error_callback2 error_callback2;
};
#else
struct nghttp2_session_callbacks {
nghttp2_send_callback send_callback;
nghttp2_recv_callback recv_callback;
nghttp2_on_frame_recv_callback on_frame_recv_callback;
nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback;
nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback;
nghttp2_before_frame_send_callback before_frame_send_callback;
nghttp2_on_frame_send_callback on_frame_send_callback;
nghttp2_on_frame_not_send_callback on_frame_not_send_callback;
nghttp2_on_stream_close_callback on_stream_close_callback;
nghttp2_on_begin_headers_callback on_begin_headers_callback;
nghttp2_on_header_callback on_header_callback;
nghttp2_on_header_callback2 on_header_callback2;
nghttp2_on_invalid_header_callback on_invalid_header_callback;
nghttp2_on_invalid_header_callback2 on_invalid_header_callback2;
nghttp2_select_padding_callback select_padding_callback;
nghttp2_data_source_read_length_callback read_length_callback;
nghttp2_on_begin_frame_callback on_begin_frame_callback;
nghttp2_send_data_callback send_data_callback;
nghttp2_pack_extension_callback pack_extension_callback;
nghttp2_unpack_extension_callback unpack_extension_callback;
nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback;
nghttp2_error_callback error_callback;
nghttp2_error_callback2 error_callback2;
};
#endif
namespace http2 {
namespace adapter {
CallbackVisitor::CallbackVisitor(Perspective perspective,
const nghttp2_session_callbacks& callbacks,
void* user_data)
: perspective_(perspective),
callbacks_(MakeCallbacksPtr(nullptr)),
user_data_(user_data) {
nghttp2_session_callbacks* c;
nghttp2_session_callbacks_new(&c);
*c = callbacks;
callbacks_ = MakeCallbacksPtr(c);
memset(¤t_frame_, 0, sizeof(current_frame_));
}
int64_t CallbackVisitor::OnReadyToSend(absl::string_view serialized) {
if (!callbacks_->send_callback) {
return kSendError;
}
int64_t result = callbacks_->send_callback(
nullptr, ToUint8Ptr(serialized.data()), serialized.size(), 0, user_data_);
QUICHE_VLOG(1) << "CallbackVisitor::OnReadyToSend called with "
<< serialized.size() << " bytes, returning " << result;
QUICHE_VLOG(2) << (perspective_ == Perspective::kClient ? "Client" : "Server")
<< " sending: [" << absl::CEscape(serialized) << "]";
if (result > 0) {
return result;
} else if (result == NGHTTP2_ERR_WOULDBLOCK) {
return kSendBlocked;
} else {
return kSendError;
}
}
Http2VisitorInterface::DataFrameHeaderInfo
CallbackVisitor::OnReadyToSendDataForStream(Http2StreamId ,
size_t ) {
QUICHE_LOG(FATAL)
<< "Not implemented; should not be used with nghttp2 callbacks.";
return {};
}
bool CallbackVisitor::SendDataFrame(Http2StreamId ,
absl::string_view ,
size_t ) {
QUICHE_LOG(FATAL)
<< "Not implemented; should not be used with nghttp2 callbacks.";
return false;
}
void CallbackVisitor::OnConnectionError(ConnectionError ) {
QUICHE_VLOG(1) << "OnConnectionError not implemented";
}
bool CallbackVisitor::OnFrameHeader(Http2StreamId stream_id, size_t length,
uint8_t type, uint8_t flags) {
QUICHE_VLOG(1) << "CallbackVisitor::OnFrameHeader(stream_id=" << stream_id
<< ", type=" << int(type) << ", length=" << length
<< ", flags=" << int(flags) << ")";
if (static_cast<FrameType>(type) == FrameType::CONTINUATION) {
if (static_cast<FrameType>(current_frame_.hd.type) != FrameType::HEADERS ||
current_frame_.hd.stream_id == 0 ||
current_frame_.hd.stream_id != stream_id) {
return false;
}
current_frame_.hd.length += length;
current_frame_.hd.flags |= flags;
QUICHE_DLOG_IF(ERROR, length == 0) << "Empty CONTINUATION!";
nghttp2_frame_hd hd;
memset(&hd, 0, sizeof(hd));
hd.stream_id = stream_id;
hd.length = length;
hd.type = type;
hd.flags = flags;
if (callbacks_->on_begin_frame_callback) {
const int result =
callbacks_->on_begin_frame_callback(nullptr, &hd, user_data_);
return result == 0;
}
return true;
}
memset(¤t_frame_, 0, sizeof(current_frame_));
current_frame_.hd.stream_id = stream_id;
current_frame_.hd.length = length;
current_frame_.hd.type = type;
current_frame_.hd.flags = flags;
if (callbacks_->on_begin_frame_callback) {
const int result = callbacks_->on_begin_frame_callback(
nullptr, ¤t_frame_.hd, user_data_);
return result == 0;
}
return true;
}
void CallbackVisitor::OnSettingsStart() {}
void CallbackVisitor::OnSetting(Http2Setting setting) {
settings_.push_back({setting.id, setting.value});
}
void CallbackVisitor::OnSettingsEnd() {
current_frame_.settings.niv = settings_.size();
current_frame_.settings.iv = settings_.data();
QUICHE_VLOG(1) << "OnSettingsEnd, received settings of size "
<< current_frame_.settings.niv;
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
settings_.clear();
}
void CallbackVisitor::OnSettingsAck() {
QUICHE_VLOG(1) << "OnSettingsAck()";
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
}
bool CallbackVisitor::OnBeginHeadersForStream(Http2StreamId stream_id) {
auto it = GetStreamInfo(stream_id);
if (it == stream_map_.end()) {
current_frame_.headers.cat = NGHTTP2_HCAT_HEADERS;
} else {
if (it->second.received_headers) {
QUICHE_VLOG(1)
<< "Headers already received for stream " << stream_id
<< ", these are trailers or headers following a 100 response";
current_frame_.headers.cat = NGHTTP2_HCAT_HEADERS;
} else {
switch (perspective_) {
case Perspective::kClient:
QUICHE_VLOG(1) << "First headers at the client for stream "
<< stream_id << "; these are response headers";
current_frame_.headers.cat = NGHTTP2_HCAT_RESPONSE;
break;
case Perspective::kServer:
QUICHE_VLOG(1) << "First headers at the server for stream "
<< stream_id << "; these are request headers";
current_frame_.headers.cat = NGHTTP2_HCAT_REQUEST;
break;
}
}
it->second.received_headers = true;
}
if (callbacks_->on_begin_headers_callback) {
const int result = callbacks_->on_begin_headers_callback(
nullptr, ¤t_frame_, user_data_);
return result == 0;
}
return true;
}
Http2VisitorInterface::OnHeaderResult CallbackVisitor::OnHeaderForStream(
Http2StreamId stream_id, absl::string_view name, absl::string_view value) {
QUICHE_VLOG(2) << "OnHeaderForStream(stream_id=" << stream_id << ", name=["
<< absl::CEscape(name) << "], value=[" << absl::CEscape(value)
<< "])";
if (callbacks_->on_header_callback) {
const int result = callbacks_->on_header_callback(
nullptr, ¤t_frame_, ToUint8Ptr(name.data()), name.size(),
ToUint8Ptr(value.data()), value.size(), NGHTTP2_NV_FLAG_NONE,
user_data_);
if (result == 0) {
return HEADER_OK;
} else if (result == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) {
return HEADER_RST_STREAM;
} else {
return HEADER_CONNECTION_ERROR;
}
}
return HEADER_OK;
}
bool CallbackVisitor::OnEndHeadersForStream(Http2StreamId stream_id) {
QUICHE_VLOG(1) << "OnEndHeadersForStream(stream_id=" << stream_id << ")";
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
return result == 0;
}
return true;
}
bool CallbackVisitor::OnDataPaddingLength(Http2StreamId ,
size_t padding_length) {
current_frame_.data.padlen = padding_length;
remaining_data_ -= padding_length;
if (remaining_data_ == 0 &&
(current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 &&
callbacks_->on_frame_recv_callback != nullptr) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
return result == 0;
}
return true;
}
bool CallbackVisitor::OnBeginDataForStream(Http2StreamId ,
size_t payload_length) {
remaining_data_ = payload_length;
if (remaining_data_ == 0 &&
(current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 &&
callbacks_->on_frame_recv_callback != nullptr) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
return result == 0;
}
return true;
}
bool CallbackVisitor::OnDataForStream(Http2StreamId stream_id,
absl::string_view data) {
QUICHE_VLOG(1) << "OnDataForStream(stream_id=" << stream_id
<< ", data.size()=" << data.size() << ")";
int result = 0;
if (callbacks_->on_data_chunk_recv_callback) {
result = callbacks_->on_data_chunk_recv_callback(
nullptr, current_frame_.hd.flags, stream_id, ToUint8Ptr(data.data()),
data.size(), user_data_);
}
remaining_data_ -= data.size();
if (result == 0 && remaining_data_ == 0 &&
(current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 &&
callbacks_->on_frame_recv_callback) {
result = callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_,
user_data_);
}
return result == 0;
}
bool CallbackVisitor::OnEndStream(Http2StreamId stream_id) {
QUICHE_VLOG(1) << "OnEndStream(stream_id=" << stream_id << ")";
int result = 0;
if (static_cast<FrameType>(current_frame_.hd.type) == FrameType::DATA &&
(current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) != 0 &&
callbacks_->on_frame_recv_callback) {
result = callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_,
user_data_);
}
return result == 0;
}
void CallbackVisitor::OnRstStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
QUICHE_VLOG(1) << "OnRstStream(stream_id=" << stream_id
<< ", error_code=" << static_cast<int>(error_code) << ")";
current_frame_.rst_stream.error_code = static_cast<uint32_t>(error_code);
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
}
bool CallbackVisitor::OnCloseStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
QUICHE_VLOG(1) << "OnCloseStream(stream_id=" << stream_id
<< ", error_code=" << static_cast<int>(error_code) << ")";
int result = 0;
if (callbacks_->on_stream_close_callback) {
result = callbacks_->on_stream_close_callback(
nullptr, stream_id, static_cast<uint32_t>(error_code), user_data_);
}
stream_map_.erase(stream_id);
if (stream_close_listener_) {
stream_close_listener_(stream_id);
}
return result == 0;
}
void CallbackVisitor::OnPriorityForStream(Http2StreamId ,
Http2StreamId parent_stream_id,
int weight, bool exclusive) {
current_frame_.priority.pri_spec.stream_id = parent_stream_id;
current_frame_.priority.pri_spec.weight = weight;
current_frame_.priority.pri_spec.exclusive = exclusive;
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
}
void CallbackVisitor::OnPing(Http2PingId ping_id, bool is_ack) {
QUICHE_VLOG(1) << "OnPing(ping_id=" << static_cast<int64_t>(ping_id)
<< ", is_ack=" << is_ack << ")";
uint64_t network_order_opaque_data =
quiche::QuicheEndian::HostToNet64(ping_id);
std::memcpy(current_frame_.ping.opaque_data, &network_order_opaque_data,
sizeof(network_order_opaque_data));
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
}
void CallbackVisitor::OnPushPromiseForStream(
Http2StreamId , Http2StreamId ) {
QUICHE_LOG(DFATAL) << "Not implemented";
}
bool CallbackVisitor::OnGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
QUICHE_VLOG(1) << "OnGoAway(last_accepted_stream_id="
<< last_accepted_stream_id
<< ", error_code=" << static_cast<int>(error_code)
<< ", opaque_data=[" << absl::CEscape(opaque_data) << "])";
current_frame_.goaway.last_stream_id = last_accepted_stream_id;
current_frame_.goaway.error_code = static_cast<uint32_t>(error_code);
current_frame_.goaway.opaque_data = ToUint8Ptr(opaque_data.data());
current_frame_.goaway.opaque_data_len = opaque_data.size();
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
return result == 0;
}
return true;
}
void CallbackVisitor::OnWindowUpdate(Http2StreamId stream_id,
int window_increment) {
QUICHE_VLOG(1) << "OnWindowUpdate(stream_id=" << stream_id
<< ", delta=" << window_increment << ")";
current_frame_.window_update.window_size_increment = window_increment;
if (callbacks_->on_frame_recv_callback) {
const int result = callbacks_->on_frame_recv_callback(
nullptr, ¤t_frame_, user_data_);
QUICHE_DCHECK_EQ(0, result);
}
}
void CallbackVisitor::PopulateFrame(nghttp2_frame& frame, uint8_t frame_type,
Http2StreamId stream_id, size_t length,
uint8_t flags, uint32_t error_code,
bool sent_headers) {
frame.hd.type = frame_type;
frame.hd.stream_id = stream_id;
frame.hd.length = length;
frame.hd.flags = flags;
const FrameType frame_type_enum = static_cast<FrameType>(frame_type);
if (frame_type_enum == FrameType::HEADERS) {
if (sent_headers) {
frame.headers.cat = NGHTTP2_HCAT_HEADERS;
} else {
switch (perspective_) {
case Perspective::kClient:
QUICHE_VLOG(1) << "First headers sent by the client for stream "
<< stream_id << "; these are request headers";
frame.headers.cat = NGHTTP2_HCAT_REQUEST;
break;
case Perspective::kServer:
QUICHE_VLOG(1) << "First headers sent by the server for stream "
<< stream_id << "; these are response headers";
frame.headers.cat = NGHTTP2_HCAT_RESPONSE;
break;
}
}
} else if (frame_type_enum == FrameType::RST_STREAM) {
frame.rst_stream.error_code = error_code;
} else if (frame_type_enum == FrameType::GOAWAY) {
frame.goaway.error_code = error_code;
}
}
int CallbackVisitor::OnBeforeFrameSent(uint8_t frame_type,
Http2StreamId stream_id, size_t length,
uint8_t flags) {
QUICHE_VLOG(1) << "OnBeforeFrameSent(stream_id=" << stream_id
<< ", type=" << int(frame_type) << ", length=" << length
<< ", flags=" << int(flags) << ")";
if (callbacks_->before_frame_send_callback) {
nghttp2_frame frame;
bool before_sent_headers = true;
auto it = GetStreamInfo(stream_id);
if (it != stream_map_.end()) {
before_sent_headers = it->second.before_sent_headers;
it->second.before_sent_headers = true;
}
PopulateFrame(frame, frame_type, stream_id, length, flags, 0,
before_sent_headers);
return callbacks_->before_frame_send_callback(nullptr, &frame, user_data_);
}
return 0;
}
int CallbackVisitor::OnFrameSent(uint8_t frame_type, Http2StreamId stream_id,
size_t length, uint8_t flags,
uint32_t error_code) {
QUICHE_VLOG(1) << "OnFrameSent(stream_id=" << stream_id
<< ", type=" << int(frame_type) << ", length=" << length
<< ", flags=" << int(flags) << ", error_code=" << error_code
<< ")";
if (callbacks_->on_frame_send_callback) {
nghttp2_frame frame;
bool sent_headers = true;
auto it = GetStreamInfo(stream_id);
if (it != stream_map_.end()) {
sent_headers = it->second.sent_headers;
it->second.sent_headers = true;
}
PopulateFrame(frame, frame_type, stream_id, length, flags, error_code,
sent_headers);
return callbacks_->on_frame_send_callback(nullptr, &frame, user_data_);
}
return 0;
}
bool CallbackVisitor::OnInvalidFrame(Http2StreamId stream_id,
InvalidFrameError error) {
QUICHE_VLOG(1) << "OnInvalidFrame(" << stream_id << ", "
<< InvalidFrameErrorToString(error) << ")";
QUICHE_DCHECK_EQ(stream_id, current_frame_.hd.stream_id);
if (callbacks_->on_invalid_frame_recv_callback) {
return 0 ==
callbacks_->on_invalid_frame_recv_callback(
nullptr, ¤t_frame_, ToNgHttp2ErrorCode(error), user_data_);
}
return true;
}
void CallbackVisitor::OnBeginMetadataForStream(Http2StreamId stream_id,
size_t payload_length) {
QUICHE_VLOG(1) << "OnBeginMetadataForStream(stream_id=" << stream_id
<< ", payload_length=" << payload_length << ")";
}
bool CallbackVisitor::OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) {
QUICHE_VLOG(1) << "OnMetadataForStream(stream_id=" << stream_id
<< ", len=" << metadata.size() << ")";
if (callbacks_->on_extension_chunk_recv_callback) {
int result = callbacks_->on_extension_chunk_recv_callback(
nullptr, ¤t_frame_.hd, ToUint8Ptr(metadata.data()),
metadata.size(), user_data_);
return result == 0;
}
return true;
}
bool CallbackVisitor::OnMetadataEndForStream(Http2StreamId stream_id) {
if ((current_frame_.hd.flags & kMetadataEndFlag) == 0) {
QUICHE_VLOG(1) << "Expected kMetadataEndFlag during call to "
<< "OnMetadataEndForStream!";
return true;
}
QUICHE_VLOG(1) << "OnMetadataEndForStream(stream_id=" << stream_id << ")";
if (callbacks_->unpack_extension_callback) {
void* payload;
int result = callbacks_->unpack_extension_callback(
nullptr, &payload, ¤t_frame_.hd, user_data_);
if (result == 0 && callbacks_->on_frame_recv_callback) {
current_frame_.ext.payload = payload;
result = callbacks_->on_frame_recv_callback(nullptr, ¤t_frame_,
user_data_);
}
return (result == 0);
}
return true;
}
std::pair<int64_t, bool> CallbackVisitor::PackMetadataForStream(
Http2StreamId , uint8_t* , size_t ) {
QUICHE_LOG(DFATAL) << "Unimplemented.";
return {-1, false};
}
void CallbackVisitor::OnErrorDebug(absl::string_view message) {
QUICHE_VLOG(1) << "OnErrorDebug(message=[" << absl::CEscape(message) << "])";
if (callbacks_->error_callback2) {
callbacks_->error_callback2(nullptr, -1, message.data(), message.size(),
user_data_);
}
}
CallbackVisitor::StreamInfoMap::iterator CallbackVisitor::GetStreamInfo(
Http2StreamId stream_id) {
auto it = stream_map_.find(stream_id);
if (it == stream_map_.end() && stream_id > stream_id_watermark_) {
auto p = stream_map_.insert({stream_id, {}});
it = p.first;
stream_id_watermark_ = stream_id;
}
return it;
}
}
} | #include "quiche/http2/adapter/callback_visitor.h"
#include <string>
#include "absl/container/flat_hash_map.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/mock_nghttp2_callbacks.h"
#include "quiche/http2/adapter/nghttp2_adapter.h"
#include "quiche/http2/adapter/nghttp2_test_utils.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using testing::_;
using testing::IsEmpty;
using testing::Pair;
using testing::UnorderedElementsAre;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
CONTINUATION,
};
TEST(ClientCallbackVisitorUnitTest, ConnectionFrames) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _)));
visitor.OnFrameHeader(0, 0, SETTINGS, 0);
visitor.OnSettingsStart();
EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty())));
visitor.OnSettingsEnd();
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, _)));
visitor.OnFrameHeader(0, 8, PING, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsPing(42)));
visitor.OnPing(42, false);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, _)));
visitor.OnFrameHeader(0, 4, WINDOW_UPDATE, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsWindowUpdate(1000)));
visitor.OnWindowUpdate(0, 1000);
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(0, PING, NGHTTP2_FLAG_ACK)));
visitor.OnFrameHeader(0, 8, PING, 1);
EXPECT_CALL(callbacks, OnFrameRecv(IsPingAck(247)));
visitor.OnPing(247, true);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, GOAWAY, 0)));
visitor.OnFrameHeader(0, 19, GOAWAY, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsGoAway(5, NGHTTP2_ENHANCE_YOUR_CALM,
"calm down!!")));
visitor.OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!");
EXPECT_EQ(visitor.stream_map_size(), 0);
}
TEST(ClientCallbackVisitorUnitTest, StreamFrames) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
absl::flat_hash_map<Http2StreamId, int> stream_close_counts;
visitor.set_stream_close_listener(
[&stream_close_counts](Http2StreamId stream_id) {
++stream_close_counts[stream_id];
});
testing::InSequence seq;
EXPECT_EQ(visitor.stream_map_size(), 0);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, _)));
visitor.OnFrameHeader(1, 23, HEADERS, 4);
EXPECT_CALL(callbacks,
OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE)));
visitor.OnBeginHeadersForStream(1);
EXPECT_EQ(visitor.stream_map_size(), 1);
EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _));
visitor.OnHeaderForStream(1, ":status", "200");
EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _));
visitor.OnHeaderForStream(1, "server", "my-fake-server");
EXPECT_CALL(callbacks,
OnHeader(_, "date", "Tue, 6 Apr 2021 12:54:01 GMT", _));
visitor.OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT");
EXPECT_CALL(callbacks, OnHeader(_, "trailer", "x-server-status", _));
visitor.OnHeaderForStream(1, "trailer", "x-server-status");
EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE)));
visitor.OnEndHeadersForStream(1);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, 0)));
visitor.OnFrameHeader(1, 26, DATA, 0);
visitor.OnBeginDataForStream(1, 26);
EXPECT_CALL(callbacks, OnDataChunkRecv(0, 1, "This is the response body."));
EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, 0)));
visitor.OnDataForStream(1, "This is the response body.");
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, _)));
visitor.OnFrameHeader(1, 23, HEADERS, 4);
EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_HEADERS)));
visitor.OnBeginHeadersForStream(1);
EXPECT_CALL(callbacks, OnHeader(_, "x-server-status", "OK", _));
visitor.OnHeaderForStream(1, "x-server-status", "OK");
EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_HEADERS)));
visitor.OnEndHeadersForStream(1);
EXPECT_THAT(stream_close_counts, IsEmpty());
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, RST_STREAM, 0)));
visitor.OnFrameHeader(3, 4, RST_STREAM, 0);
EXPECT_EQ(visitor.stream_map_size(), 1);
EXPECT_THAT(stream_close_counts, IsEmpty());
EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(3, NGHTTP2_INTERNAL_ERROR)));
visitor.OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_INTERNAL_ERROR));
visitor.OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_THAT(stream_close_counts, UnorderedElementsAre(Pair(3, 1)));
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM)));
visitor.OnFrameHeader(1, 0, DATA, 1);
EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, NGHTTP2_FLAG_END_STREAM)));
visitor.OnBeginDataForStream(1, 0);
EXPECT_TRUE(visitor.OnEndStream(1));
EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR);
EXPECT_EQ(visitor.stream_map_size(), 0);
EXPECT_THAT(stream_close_counts,
UnorderedElementsAre(Pair(3, 1), Pair(1, 1)));
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(5, RST_STREAM, _)));
visitor.OnFrameHeader(5, 4, RST_STREAM, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(5, NGHTTP2_REFUSED_STREAM)));
visitor.OnRstStream(5, Http2ErrorCode::REFUSED_STREAM);
EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_REFUSED_STREAM));
visitor.OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM);
EXPECT_EQ(visitor.stream_map_size(), 0);
EXPECT_THAT(stream_close_counts,
UnorderedElementsAre(Pair(3, 1), Pair(1, 1), Pair(5, 1)));
}
TEST(ClientCallbackVisitorUnitTest, HeadersWithContinuation) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, 0x0)));
ASSERT_TRUE(visitor.OnFrameHeader(1, 23, HEADERS, 0x0));
EXPECT_CALL(callbacks,
OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE)));
visitor.OnBeginHeadersForStream(1);
EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _));
visitor.OnHeaderForStream(1, ":status", "200");
EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _));
visitor.OnHeaderForStream(1, "server", "my-fake-server");
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(1, CONTINUATION, END_HEADERS_FLAG)));
ASSERT_TRUE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG));
EXPECT_CALL(callbacks,
OnHeader(_, "date", "Tue, 6 Apr 2021 12:54:01 GMT", _));
visitor.OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT");
EXPECT_CALL(callbacks, OnHeader(_, "trailer", "x-server-status", _));
visitor.OnHeaderForStream(1, "trailer", "x-server-status");
EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE)));
visitor.OnEndHeadersForStream(1);
}
TEST(ClientCallbackVisitorUnitTest, ContinuationNoHeaders) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
EXPECT_FALSE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG));
}
TEST(ClientCallbackVisitorUnitTest, ContinuationWrongPrecedingType) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, WINDOW_UPDATE, _)));
visitor.OnFrameHeader(1, 4, WINDOW_UPDATE, 0);
EXPECT_FALSE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG));
}
TEST(ClientCallbackVisitorUnitTest, ContinuationWrongStream) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, 0x0)));
ASSERT_TRUE(visitor.OnFrameHeader(1, 23, HEADERS, 0x0));
EXPECT_CALL(callbacks,
OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE)));
visitor.OnBeginHeadersForStream(1);
EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _));
visitor.OnHeaderForStream(1, ":status", "200");
EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _));
visitor.OnHeaderForStream(1, "server", "my-fake-server");
EXPECT_FALSE(visitor.OnFrameHeader(3, 23, CONTINUATION, END_HEADERS_FLAG));
}
TEST(ClientCallbackVisitorUnitTest, ResetAndGoaway) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kClient,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, RST_STREAM, 0x0)));
EXPECT_TRUE(visitor.OnFrameHeader(1, 13, RST_STREAM, 0x0));
EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(1, NGHTTP2_INTERNAL_ERROR)));
visitor.OnRstStream(1, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_INTERNAL_ERROR));
EXPECT_TRUE(visitor.OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, GOAWAY, 0x0)));
EXPECT_TRUE(visitor.OnFrameHeader(0, 13, GOAWAY, 0x0));
EXPECT_CALL(callbacks,
OnFrameRecv(IsGoAway(3, NGHTTP2_ENHANCE_YOUR_CALM, "calma te")));
EXPECT_TRUE(
visitor.OnGoAway(3, Http2ErrorCode::ENHANCE_YOUR_CALM, "calma te"));
EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_STREAM_CLOSED))
.WillOnce(testing::Return(NGHTTP2_ERR_CALLBACK_FAILURE));
EXPECT_FALSE(visitor.OnCloseStream(5, Http2ErrorCode::STREAM_CLOSED));
}
TEST(ServerCallbackVisitorUnitTest, ConnectionFrames) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kServer,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _)));
visitor.OnFrameHeader(0, 0, SETTINGS, 0);
visitor.OnSettingsStart();
EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty())));
visitor.OnSettingsEnd();
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, _)));
visitor.OnFrameHeader(0, 8, PING, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsPing(42)));
visitor.OnPing(42, false);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, _)));
visitor.OnFrameHeader(0, 4, WINDOW_UPDATE, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsWindowUpdate(1000)));
visitor.OnWindowUpdate(0, 1000);
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(0, PING, NGHTTP2_FLAG_ACK)));
visitor.OnFrameHeader(0, 8, PING, 1);
EXPECT_CALL(callbacks, OnFrameRecv(IsPingAck(247)));
visitor.OnPing(247, true);
EXPECT_EQ(visitor.stream_map_size(), 0);
}
TEST(ServerCallbackVisitorUnitTest, StreamFrames) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kServer,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(
1, HEADERS, NGHTTP2_FLAG_END_HEADERS)));
visitor.OnFrameHeader(1, 23, HEADERS, 4);
EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS,
NGHTTP2_HCAT_REQUEST)));
visitor.OnBeginHeadersForStream(1);
EXPECT_EQ(visitor.stream_map_size(), 1);
EXPECT_CALL(callbacks, OnHeader(_, ":method", "POST", _));
visitor.OnHeaderForStream(1, ":method", "POST");
EXPECT_CALL(callbacks, OnHeader(_, ":path", "/example/path", _));
visitor.OnHeaderForStream(1, ":path", "/example/path");
EXPECT_CALL(callbacks, OnHeader(_, ":scheme", "https", _));
visitor.OnHeaderForStream(1, ":scheme", "https");
EXPECT_CALL(callbacks, OnHeader(_, ":authority", "example.com", _));
visitor.OnHeaderForStream(1, ":authority", "example.com");
EXPECT_CALL(callbacks, OnHeader(_, "accept", "text/html", _));
visitor.OnHeaderForStream(1, "accept", "text/html");
EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS,
NGHTTP2_HCAT_REQUEST)));
visitor.OnEndHeadersForStream(1);
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM)));
visitor.OnFrameHeader(1, 25, DATA, NGHTTP2_FLAG_END_STREAM);
visitor.OnBeginDataForStream(1, 25);
EXPECT_CALL(callbacks, OnDataChunkRecv(NGHTTP2_FLAG_END_STREAM, 1,
"This is the request body."));
EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, NGHTTP2_FLAG_END_STREAM)));
visitor.OnDataForStream(1, "This is the request body.");
EXPECT_TRUE(visitor.OnEndStream(1));
EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR);
EXPECT_EQ(visitor.stream_map_size(), 0);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, RST_STREAM, 0)));
visitor.OnFrameHeader(3, 4, RST_STREAM, 0);
EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(3, NGHTTP2_INTERNAL_ERROR)));
visitor.OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_INTERNAL_ERROR));
visitor.OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR);
EXPECT_EQ(visitor.stream_map_size(), 0);
}
TEST(ServerCallbackVisitorUnitTest, DataWithPadding) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kServer,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
const size_t kPaddingLength = 39;
const uint8_t kFlags = NGHTTP2_FLAG_PADDED | NGHTTP2_FLAG_END_STREAM;
testing::InSequence seq;
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, kFlags)));
EXPECT_TRUE(visitor.OnFrameHeader(1, 25 + kPaddingLength, DATA, kFlags));
EXPECT_TRUE(visitor.OnBeginDataForStream(1, 25 + kPaddingLength));
EXPECT_TRUE(visitor.OnDataPaddingLength(1, kPaddingLength));
EXPECT_CALL(callbacks,
OnDataChunkRecv(kFlags, 1, "This is the request body."));
EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, kFlags, kPaddingLength)));
EXPECT_TRUE(visitor.OnDataForStream(1, "This is the request body."));
EXPECT_TRUE(visitor.OnEndStream(1));
EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, DATA, kFlags)));
EXPECT_TRUE(visitor.OnFrameHeader(3, 25 + kPaddingLength, DATA, kFlags));
EXPECT_TRUE(visitor.OnBeginDataForStream(3, 25 + kPaddingLength));
EXPECT_CALL(callbacks,
OnDataChunkRecv(kFlags, 3, "This is the request body."));
EXPECT_TRUE(visitor.OnDataForStream(3, "This is the request body."));
EXPECT_CALL(callbacks, OnFrameRecv(IsData(3, _, kFlags, kPaddingLength)));
EXPECT_TRUE(visitor.OnDataPaddingLength(3, kPaddingLength));
EXPECT_TRUE(visitor.OnEndStream(3));
EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(5, DATA, kFlags)));
EXPECT_TRUE(visitor.OnFrameHeader(5, 25 + kPaddingLength, DATA, kFlags));
EXPECT_TRUE(visitor.OnBeginDataForStream(5, 25 + kPaddingLength));
EXPECT_CALL(callbacks,
OnDataChunkRecv(kFlags, 5, "This is the request body."));
EXPECT_TRUE(visitor.OnDataForStream(5, "This is the request body."));
EXPECT_CALL(callbacks, OnFrameRecv(IsData(5, _, kFlags, kPaddingLength)))
.WillOnce(testing::Return(NGHTTP2_ERR_CALLBACK_FAILURE));
EXPECT_TRUE(visitor.OnDataPaddingLength(5, kPaddingLength));
EXPECT_FALSE(visitor.OnEndStream(3));
EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR);
}
TEST(ServerCallbackVisitorUnitTest, MismatchedContentLengthCallbacks) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kServer,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{"content-length", "50"}},
false)
.Data(1, "Less than 50 bytes.", true)
.Serialize();
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _)));
EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty())));
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(
1, HEADERS, NGHTTP2_FLAG_END_HEADERS)));
EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS,
NGHTTP2_HCAT_REQUEST)));
EXPECT_CALL(callbacks, OnHeader(_, ":method", "POST", _));
EXPECT_CALL(callbacks, OnHeader(_, ":path", "/", _));
EXPECT_CALL(callbacks, OnHeader(_, ":scheme", "https", _));
EXPECT_CALL(callbacks, OnHeader(_, ":authority", "example.com", _));
EXPECT_CALL(callbacks, OnHeader(_, "content-length", "50", _));
EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS,
NGHTTP2_HCAT_REQUEST)));
EXPECT_CALL(callbacks,
OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM)));
EXPECT_CALL(callbacks, OnDataChunkRecv(NGHTTP2_FLAG_END_STREAM, 1,
"Less than 50 bytes."));
int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), result);
}
TEST(ServerCallbackVisitorUnitTest, HeadersAfterFin) {
testing::StrictMock<MockNghttp2Callbacks> callbacks;
CallbackVisitor visitor(Perspective::kServer,
*MockNghttp2Callbacks::GetCallbacks(), &callbacks);
testing::InSequence seq;
EXPECT_CALL(
callbacks,
OnBeginFrame(HasFrameHeader(
1, HEADERS, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM)));
visitor.OnFrameHeader(1, 23, HEADERS, 5);
EXPECT_CALL(callbacks,
OnBeginHeaders(IsHeaders(
1, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM,
NGHTTP2_HCAT_REQUEST)));
EXPECT_TRUE(visitor.OnBeginHeadersForStream(1));
EXPECT_EQ(visitor.stream_map_size(), 1);
EXPECT_CALL(callbacks, OnHeader).Times(5);
visitor.OnHeaderForStream(1, ":method", "POST");
visitor.OnHeaderForStream(1, ":path", "/example/path");
visitor.OnHeaderForStream(1, ":scheme", "https");
visitor.OnHeaderForStream(1, ":authority", "example.com");
visitor.OnHeaderForStream(1, "accept", "text/html");
EXPECT_CALL(callbacks,
OnFrameRecv(IsHeaders(
1, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM,
NGHTTP2_HCAT_REQUEST)));
visitor.OnEndHeadersForStream(1);
EXPECT_TRUE(visitor.OnEndStream(1));
EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR));
visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR);
EXPECT_EQ(visitor.stream_map_size(), 0);
EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(
1, HEADERS, NGHTTP2_FLAG_END_HEADERS)));
visitor.OnFrameHeader(1, 23, HEADERS, 4);
EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS,
NGHTTP2_HCAT_HEADERS)));
EXPECT_TRUE(visitor.OnBeginHeadersForStream(1));
EXPECT_EQ(visitor.stream_map_size(), 0);
}
}
}
}
} |
404 | cpp | google/quiche | test_utils | quiche/http2/adapter/test_utils.cc | quiche/http2/adapter/test_utils_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_TEST_UTILS_H_
#define QUICHE_HTTP2_ADAPTER_TEST_UTILS_H_
#include <cstdint>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/chunked_buffer.h"
#include "quiche/http2/adapter/data_source.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/spdy/core/http2_header_block.h"
#include "quiche/spdy/core/spdy_protocol.h"
namespace http2 {
namespace adapter {
namespace test {
class QUICHE_NO_EXPORT TestVisitor
: public testing::StrictMock<MockHttp2Visitor> {
public:
int64_t OnReadyToSend(absl::string_view data) override {
if (has_write_error_) {
return kSendError;
}
if (is_write_blocked_) {
return kSendBlocked;
}
const size_t to_accept = std::min(send_limit_, data.size());
if (to_accept == 0) {
return kSendBlocked;
}
absl::StrAppend(&data_, data.substr(0, to_accept));
return to_accept;
}
bool OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) override {
const bool ret = testing::StrictMock<MockHttp2Visitor>::OnMetadataForStream(
stream_id, metadata);
if (ret) {
auto result =
metadata_map_.try_emplace(stream_id, std::vector<std::string>());
result.first->second.push_back(std::string(metadata));
}
return ret;
}
const std::vector<std::string> GetMetadata(Http2StreamId stream_id) {
auto it = metadata_map_.find(stream_id);
if (it == metadata_map_.end()) {
return {};
} else {
return it->second;
}
}
DataFrameHeaderInfo OnReadyToSendDataForStream(Http2StreamId stream_id,
size_t max_length) override;
bool SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header,
size_t payload_bytes) override;
void AppendPayloadForStream(Http2StreamId stream_id,
absl::string_view payload);
void SetEndData(Http2StreamId stream_id, bool end_stream);
void SimulateError(Http2StreamId stream_id);
std::pair<int64_t, bool> PackMetadataForStream(Http2StreamId stream_id,
uint8_t* dest,
size_t dest_len) override;
void AppendMetadataForStream(Http2StreamId stream_id,
const spdy::Http2HeaderBlock& payload);
const std::string& data() { return data_; }
void Clear() { data_.clear(); }
void set_send_limit(size_t limit) { send_limit_ = limit; }
bool is_write_blocked() const { return is_write_blocked_; }
void set_is_write_blocked(bool value) { is_write_blocked_ = value; }
void set_has_write_error() { has_write_error_ = true; }
private:
struct DataPayload {
ChunkedBuffer data;
bool end_data = false;
bool end_stream = false;
bool return_error = false;
};
std::string data_;
absl::flat_hash_map<Http2StreamId, std::vector<std::string>> metadata_map_;
absl::flat_hash_map<Http2StreamId, DataPayload> data_map_;
absl::flat_hash_map<Http2StreamId, std::string> outbound_metadata_map_;
size_t send_limit_ = std::numeric_limits<size_t>::max();
bool is_write_blocked_ = false;
bool has_write_error_ = false;
};
class QUICHE_NO_EXPORT VisitorDataSource : public DataFrameSource {
public:
VisitorDataSource(Http2VisitorInterface& visitor, Http2StreamId stream_id);
std::pair<int64_t, bool> SelectPayloadLength(size_t max_length) override;
bool Send(absl::string_view frame_header, size_t payload_length) override;
bool send_fin() const override;
private:
Http2VisitorInterface& visitor_;
const Http2StreamId stream_id_;
bool has_fin_ = false;
};
class QUICHE_NO_EXPORT TestMetadataSource : public MetadataSource {
public:
explicit TestMetadataSource(const spdy::Http2HeaderBlock& entries);
size_t NumFrames(size_t max_frame_size) const override {
return (encoded_entries_.size() + max_frame_size - 1) / max_frame_size;
}
std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override;
void OnFailure() override {}
void InjectFailure() { fail_when_packing_ = true; }
private:
const std::string encoded_entries_;
absl::string_view remaining_;
bool fail_when_packing_ = false;
};
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<std::pair<spdy::SpdyFrameType, std::optional<size_t>>>
types_and_lengths);
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<spdy::SpdyFrameType> types);
}
}
}
#endif
#include "quiche/http2/adapter/test_utils.h"
#include <cstring>
#include <optional>
#include <ostream>
#include <vector>
#include "absl/strings/str_format.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/common/quiche_data_reader.h"
#include "quiche/spdy/core/hpack/hpack_encoder.h"
#include "quiche/spdy/core/spdy_protocol.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
std::string EncodeHeaders(const spdy::Http2HeaderBlock& entries) {
spdy::HpackEncoder encoder;
encoder.DisableCompression();
return encoder.EncodeHeaderBlock(entries);
}
}
TestVisitor::DataFrameHeaderInfo TestVisitor::OnReadyToSendDataForStream(
Http2StreamId stream_id, size_t max_length) {
auto it = data_map_.find(stream_id);
if (it == data_map_.end()) {
QUICHE_DVLOG(1) << "Source not in map; returning blocked.";
return {0, false, false};
}
DataPayload& payload = it->second;
if (payload.return_error) {
QUICHE_DVLOG(1) << "Simulating error response for stream " << stream_id;
return {DataFrameSource::kError, false, false};
}
const absl::string_view prefix = payload.data.GetPrefix();
const size_t frame_length = std::min(max_length, prefix.size());
const bool is_final_fragment = payload.data.Read().size() <= 1;
const bool end_data =
payload.end_data && is_final_fragment && frame_length == prefix.size();
const bool end_stream = payload.end_stream && end_data;
return {static_cast<int64_t>(frame_length), end_data, end_stream};
}
bool TestVisitor::SendDataFrame(Http2StreamId stream_id,
absl::string_view frame_header,
size_t payload_bytes) {
const int64_t frame_result = OnReadyToSend(frame_header);
if (frame_result < 0 ||
static_cast<size_t>(frame_result) != frame_header.size()) {
return false;
}
auto it = data_map_.find(stream_id);
if (it == data_map_.end()) {
if (payload_bytes > 0) {
return false;
} else {
return true;
}
}
DataPayload& payload = it->second;
absl::string_view frame_payload = payload.data.GetPrefix();
if (frame_payload.size() < payload_bytes) {
return false;
}
frame_payload = frame_payload.substr(0, payload_bytes);
const int64_t payload_result = OnReadyToSend(frame_payload);
if (payload_result < 0 ||
static_cast<size_t>(payload_result) != frame_payload.size()) {
return false;
}
payload.data.RemovePrefix(payload_bytes);
return true;
}
void TestVisitor::AppendPayloadForStream(Http2StreamId stream_id,
absl::string_view payload) {
auto char_data = std::unique_ptr<char[]>(new char[payload.size()]);
std::copy(payload.begin(), payload.end(), char_data.get());
data_map_[stream_id].data.Append(std::move(char_data), payload.size());
}
void TestVisitor::SetEndData(Http2StreamId stream_id, bool end_stream) {
DataPayload& payload = data_map_[stream_id];
payload.end_data = true;
payload.end_stream = end_stream;
}
void TestVisitor::SimulateError(Http2StreamId stream_id) {
DataPayload& payload = data_map_[stream_id];
payload.return_error = true;
}
std::pair<int64_t, bool> TestVisitor::PackMetadataForStream(
Http2StreamId stream_id, uint8_t* dest, size_t dest_len) {
auto it = outbound_metadata_map_.find(stream_id);
if (it == outbound_metadata_map_.end()) {
return {-1, false};
}
const size_t to_copy = std::min(it->second.size(), dest_len);
auto* src = reinterpret_cast<uint8_t*>(it->second.data());
std::copy(src, src + to_copy, dest);
it->second = it->second.substr(to_copy);
if (it->second.empty()) {
outbound_metadata_map_.erase(it);
return {to_copy, true};
}
return {to_copy, false};
}
void TestVisitor::AppendMetadataForStream(
Http2StreamId stream_id, const spdy::Http2HeaderBlock& payload) {
outbound_metadata_map_.insert({stream_id, EncodeHeaders(payload)});
}
VisitorDataSource::VisitorDataSource(Http2VisitorInterface& visitor,
Http2StreamId stream_id)
: visitor_(visitor), stream_id_(stream_id) {}
bool VisitorDataSource::send_fin() const { return has_fin_; }
std::pair<int64_t, bool> VisitorDataSource::SelectPayloadLength(
size_t max_length) {
auto [payload_length, end_data, end_stream] =
visitor_.OnReadyToSendDataForStream(stream_id_, max_length);
has_fin_ = end_stream;
return {payload_length, end_data};
}
bool VisitorDataSource::Send(absl::string_view frame_header,
size_t payload_length) {
return visitor_.SendDataFrame(stream_id_, frame_header, payload_length);
}
TestMetadataSource::TestMetadataSource(const spdy::Http2HeaderBlock& entries)
: encoded_entries_(EncodeHeaders(entries)) {
remaining_ = encoded_entries_;
}
std::pair<int64_t, bool> TestMetadataSource::Pack(uint8_t* dest,
size_t dest_len) {
if (fail_when_packing_) {
return {-1, false};
}
const size_t copied = std::min(dest_len, remaining_.size());
std::memcpy(dest, remaining_.data(), copied);
remaining_.remove_prefix(copied);
return std::make_pair(copied, remaining_.empty());
}
namespace {
using TypeAndOptionalLength =
std::pair<spdy::SpdyFrameType, std::optional<size_t>>;
std::ostream& operator<<(
std::ostream& os,
const std::vector<TypeAndOptionalLength>& types_and_lengths) {
for (const auto& type_and_length : types_and_lengths) {
os << "(" << spdy::FrameTypeToString(type_and_length.first) << ", "
<< (type_and_length.second ? absl::StrCat(type_and_length.second.value())
: "<unspecified>")
<< ") ";
}
return os;
}
std::string FrameTypeToString(uint8_t frame_type) {
if (spdy::IsDefinedFrameType(frame_type)) {
return spdy::FrameTypeToString(spdy::ParseFrameType(frame_type));
} else {
return absl::StrFormat("0x%x", static_cast<int>(frame_type));
}
}
class SpdyControlFrameMatcher
: public testing::MatcherInterface<absl::string_view> {
public:
explicit SpdyControlFrameMatcher(
std::vector<TypeAndOptionalLength> types_and_lengths)
: expected_types_and_lengths_(std::move(types_and_lengths)) {}
bool MatchAndExplain(absl::string_view s,
testing::MatchResultListener* listener) const override {
quiche::QuicheDataReader reader(s.data(), s.size());
for (TypeAndOptionalLength expected : expected_types_and_lengths_) {
if (!MatchAndExplainOneFrame(expected.first, expected.second, &reader,
listener)) {
return false;
}
}
if (!reader.IsDoneReading()) {
*listener << "; " << reader.BytesRemaining() << " bytes left to read!";
return false;
}
return true;
}
bool MatchAndExplainOneFrame(spdy::SpdyFrameType expected_type,
std::optional<size_t> expected_length,
quiche::QuicheDataReader* reader,
testing::MatchResultListener* listener) const {
uint32_t payload_length;
if (!reader->ReadUInt24(&payload_length)) {
*listener << "; unable to read length field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (expected_length && payload_length != expected_length.value()) {
*listener << "; actual length: " << payload_length
<< " but expected length: " << expected_length.value();
return false;
}
uint8_t raw_type;
if (!reader->ReadUInt8(&raw_type)) {
*listener << "; unable to read type field for expected_type "
<< FrameTypeToString(expected_type) << ". data too short!";
return false;
}
if (raw_type != static_cast<uint8_t>(expected_type)) {
*listener << "; actual type: " << FrameTypeToString(raw_type)
<< " but expected type: " << FrameTypeToString(expected_type);
return false;
}
reader->Seek(5 + payload_length);
return true;
}
void DescribeTo(std::ostream* os) const override {
*os << "Data contains frames of types in sequence "
<< expected_types_and_lengths_;
}
void DescribeNegationTo(std::ostream* os) const override {
*os << "Data does not contain frames of types in sequence "
<< expected_types_and_lengths_;
}
private:
const std::vector<TypeAndOptionalLength> expected_types_and_lengths_;
};
}
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<std::pair<spdy::SpdyFrameType, std::optional<size_t>>>
types_and_lengths) {
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
testing::Matcher<absl::string_view> EqualsFrames(
std::vector<spdy::SpdyFrameType> types) {
std::vector<std::pair<spdy::SpdyFrameType, std::optional<size_t>>>
types_and_lengths;
types_and_lengths.reserve(types.size());
for (spdy::SpdyFrameType type : types) {
types_and_lengths.push_back({type, std::nullopt});
}
return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths)));
}
}
}
} | #include "quiche/http2/adapter/test_utils.h"
#include <optional>
#include <string>
#include <utility>
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/spdy/core/spdy_framer.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using spdy::SpdyFramer;
TEST(EqualsFrames, Empty) {
EXPECT_THAT("", EqualsFrames(std::vector<spdy::SpdyFrameType>{}));
}
TEST(EqualsFrames, SingleFrameWithLength) {
SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION};
spdy::SpdyPingIR ping{511};
EXPECT_THAT(framer.SerializeFrame(ping),
EqualsFrames({{spdy::SpdyFrameType::PING, 8}}));
spdy::SpdyWindowUpdateIR window_update{1, 101};
EXPECT_THAT(framer.SerializeFrame(window_update),
EqualsFrames({{spdy::SpdyFrameType::WINDOW_UPDATE, 4}}));
spdy::SpdyDataIR data{3, "Some example data, ha ha!"};
EXPECT_THAT(framer.SerializeFrame(data),
EqualsFrames({{spdy::SpdyFrameType::DATA, 25}}));
}
TEST(EqualsFrames, SingleFrameWithoutLength) {
SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION};
spdy::SpdyRstStreamIR rst_stream{7, spdy::ERROR_CODE_REFUSED_STREAM};
EXPECT_THAT(framer.SerializeFrame(rst_stream),
EqualsFrames({{spdy::SpdyFrameType::RST_STREAM, std::nullopt}}));
spdy::SpdyGoAwayIR goaway{13, spdy::ERROR_CODE_ENHANCE_YOUR_CALM,
"Consider taking some deep breaths."};
EXPECT_THAT(framer.SerializeFrame(goaway),
EqualsFrames({{spdy::SpdyFrameType::GOAWAY, std::nullopt}}));
spdy::Http2HeaderBlock block;
block[":method"] = "GET";
block[":path"] = "/example";
block[":authority"] = "example.com";
spdy::SpdyHeadersIR headers{17, std::move(block)};
EXPECT_THAT(framer.SerializeFrame(headers),
EqualsFrames({{spdy::SpdyFrameType::HEADERS, std::nullopt}}));
}
TEST(EqualsFrames, MultipleFrames) {
SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION};
spdy::SpdyPingIR ping{511};
spdy::SpdyWindowUpdateIR window_update{1, 101};
spdy::SpdyDataIR data{3, "Some example data, ha ha!"};
spdy::SpdyRstStreamIR rst_stream{7, spdy::ERROR_CODE_REFUSED_STREAM};
spdy::SpdyGoAwayIR goaway{13, spdy::ERROR_CODE_ENHANCE_YOUR_CALM,
"Consider taking some deep breaths."};
spdy::Http2HeaderBlock block;
block[":method"] = "GET";
block[":path"] = "/example";
block[":authority"] = "example.com";
spdy::SpdyHeadersIR headers{17, std::move(block)};
const std::string frame_sequence =
absl::StrCat(absl::string_view(framer.SerializeFrame(ping)),
absl::string_view(framer.SerializeFrame(window_update)),
absl::string_view(framer.SerializeFrame(data)),
absl::string_view(framer.SerializeFrame(rst_stream)),
absl::string_view(framer.SerializeFrame(goaway)),
absl::string_view(framer.SerializeFrame(headers)));
absl::string_view frame_sequence_view = frame_sequence;
EXPECT_THAT(frame_sequence,
EqualsFrames({{spdy::SpdyFrameType::PING, std::nullopt},
{spdy::SpdyFrameType::WINDOW_UPDATE, std::nullopt},
{spdy::SpdyFrameType::DATA, 25},
{spdy::SpdyFrameType::RST_STREAM, std::nullopt},
{spdy::SpdyFrameType::GOAWAY, 42},
{spdy::SpdyFrameType::HEADERS, 19}}));
EXPECT_THAT(frame_sequence_view,
EqualsFrames({{spdy::SpdyFrameType::PING, std::nullopt},
{spdy::SpdyFrameType::WINDOW_UPDATE, std::nullopt},
{spdy::SpdyFrameType::DATA, 25},
{spdy::SpdyFrameType::RST_STREAM, std::nullopt},
{spdy::SpdyFrameType::GOAWAY, 42},
{spdy::SpdyFrameType::HEADERS, 19}}));
EXPECT_THAT(
frame_sequence,
EqualsFrames(
{spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE,
spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM,
spdy::SpdyFrameType::GOAWAY, spdy::SpdyFrameType::HEADERS}));
EXPECT_THAT(
frame_sequence_view,
EqualsFrames(
{spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE,
spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM,
spdy::SpdyFrameType::GOAWAY, spdy::SpdyFrameType::HEADERS}));
EXPECT_THAT(
frame_sequence,
testing::Not(EqualsFrames(
{spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE,
spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM,
spdy::SpdyFrameType::GOAWAY})));
EXPECT_THAT(
frame_sequence_view,
testing::Not(EqualsFrames(
{spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE,
spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM,
spdy::SpdyFrameType::GOAWAY})));
}
}
}
}
} |
405 | cpp | google/quiche | event_forwarder | quiche/http2/adapter/event_forwarder.cc | quiche/http2/adapter/event_forwarder_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_EVENT_FORWARDER_H_
#define QUICHE_HTTP2_ADAPTER_EVENT_FORWARDER_H_
#include <functional>
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_callbacks.h"
#include "quiche/spdy/core/http2_frame_decoder_adapter.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT EventForwarder : public spdy::SpdyFramerVisitorInterface {
public:
using ForwardPredicate = quiche::MultiUseCallback<bool()>;
EventForwarder(ForwardPredicate can_forward,
spdy::SpdyFramerVisitorInterface& receiver);
void OnError(Http2DecoderAdapter::SpdyFramerError error,
std::string detailed_error) override;
void OnCommonHeader(spdy::SpdyStreamId stream_id, size_t length, uint8_t type,
uint8_t flags) override;
void OnDataFrameHeader(spdy::SpdyStreamId stream_id, size_t length,
bool fin) override;
void OnStreamFrameData(spdy::SpdyStreamId stream_id, const char* data,
size_t len) override;
void OnStreamEnd(spdy::SpdyStreamId stream_id) override;
void OnStreamPadLength(spdy::SpdyStreamId stream_id, size_t value) override;
void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override;
spdy::SpdyHeadersHandlerInterface* OnHeaderFrameStart(
spdy::SpdyStreamId stream_id) override;
void OnHeaderFrameEnd(spdy::SpdyStreamId stream_id) override;
void OnRstStream(spdy::SpdyStreamId stream_id,
spdy::SpdyErrorCode error_code) override;
void OnSettings() override;
void OnSetting(spdy::SpdySettingsId id, uint32_t value) override;
void OnSettingsEnd() override;
void OnSettingsAck() override;
void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override;
void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
spdy::SpdyErrorCode error_code) override;
bool OnGoAwayFrameData(const char* goaway_data, size_t len) override;
void OnHeaders(spdy::SpdyStreamId stream_id, size_t payload_length,
bool has_priority, int weight,
spdy::SpdyStreamId parent_stream_id, bool exclusive, bool fin,
bool end) override;
void OnWindowUpdate(spdy::SpdyStreamId stream_id,
int delta_window_size) override;
void OnPushPromise(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId promised_stream_id, bool end) override;
void OnContinuation(spdy::SpdyStreamId stream_id, size_t payload_length,
bool end) override;
void OnAltSvc(spdy::SpdyStreamId stream_id, absl::string_view origin,
const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector&
altsvc_vector) override;
void OnPriority(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId parent_stream_id, int weight,
bool exclusive) override;
void OnPriorityUpdate(spdy::SpdyStreamId prioritized_stream_id,
absl::string_view priority_field_value) override;
bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
uint8_t frame_type) override;
void OnUnknownFrameStart(spdy::SpdyStreamId stream_id, size_t length,
uint8_t type, uint8_t flags) override;
void OnUnknownFramePayload(spdy::SpdyStreamId stream_id,
absl::string_view payload) override;
private:
ForwardPredicate can_forward_;
spdy::SpdyFramerVisitorInterface& receiver_;
};
}
}
#endif
#include "quiche/http2/adapter/event_forwarder.h"
#include <string>
#include <utility>
namespace http2 {
namespace adapter {
EventForwarder::EventForwarder(ForwardPredicate can_forward,
spdy::SpdyFramerVisitorInterface& receiver)
: can_forward_(std::move(can_forward)), receiver_(receiver) {}
void EventForwarder::OnError(Http2DecoderAdapter::SpdyFramerError error,
std::string detailed_error) {
if (can_forward_()) {
receiver_.OnError(error, std::move(detailed_error));
}
}
void EventForwarder::OnCommonHeader(spdy::SpdyStreamId stream_id, size_t length,
uint8_t type, uint8_t flags) {
if (can_forward_()) {
receiver_.OnCommonHeader(stream_id, length, type, flags);
}
}
void EventForwarder::OnDataFrameHeader(spdy::SpdyStreamId stream_id,
size_t length, bool fin) {
if (can_forward_()) {
receiver_.OnDataFrameHeader(stream_id, length, fin);
}
}
void EventForwarder::OnStreamFrameData(spdy::SpdyStreamId stream_id,
const char* data, size_t len) {
if (can_forward_()) {
receiver_.OnStreamFrameData(stream_id, data, len);
}
}
void EventForwarder::OnStreamEnd(spdy::SpdyStreamId stream_id) {
if (can_forward_()) {
receiver_.OnStreamEnd(stream_id);
}
}
void EventForwarder::OnStreamPadLength(spdy::SpdyStreamId stream_id,
size_t value) {
if (can_forward_()) {
receiver_.OnStreamPadLength(stream_id, value);
}
}
void EventForwarder::OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) {
if (can_forward_()) {
receiver_.OnStreamPadding(stream_id, len);
}
}
spdy::SpdyHeadersHandlerInterface* EventForwarder::OnHeaderFrameStart(
spdy::SpdyStreamId stream_id) {
return receiver_.OnHeaderFrameStart(stream_id);
}
void EventForwarder::OnHeaderFrameEnd(spdy::SpdyStreamId stream_id) {
if (can_forward_()) {
receiver_.OnHeaderFrameEnd(stream_id);
}
}
void EventForwarder::OnRstStream(spdy::SpdyStreamId stream_id,
spdy::SpdyErrorCode error_code) {
if (can_forward_()) {
receiver_.OnRstStream(stream_id, error_code);
}
}
void EventForwarder::OnSettings() {
if (can_forward_()) {
receiver_.OnSettings();
}
}
void EventForwarder::OnSetting(spdy::SpdySettingsId id, uint32_t value) {
if (can_forward_()) {
receiver_.OnSetting(id, value);
}
}
void EventForwarder::OnSettingsEnd() {
if (can_forward_()) {
receiver_.OnSettingsEnd();
}
}
void EventForwarder::OnSettingsAck() {
if (can_forward_()) {
receiver_.OnSettingsAck();
}
}
void EventForwarder::OnPing(spdy::SpdyPingId unique_id, bool is_ack) {
if (can_forward_()) {
receiver_.OnPing(unique_id, is_ack);
}
}
void EventForwarder::OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
spdy::SpdyErrorCode error_code) {
if (can_forward_()) {
receiver_.OnGoAway(last_accepted_stream_id, error_code);
}
}
bool EventForwarder::OnGoAwayFrameData(const char* goaway_data, size_t len) {
if (can_forward_()) {
return receiver_.OnGoAwayFrameData(goaway_data, len);
}
return false;
}
void EventForwarder::OnHeaders(spdy::SpdyStreamId stream_id,
size_t payload_length, bool has_priority,
int weight, spdy::SpdyStreamId parent_stream_id,
bool exclusive, bool fin, bool end) {
if (can_forward_()) {
receiver_.OnHeaders(stream_id, payload_length, has_priority, weight,
parent_stream_id, exclusive, fin, end);
}
}
void EventForwarder::OnWindowUpdate(spdy::SpdyStreamId stream_id,
int delta_window_size) {
if (can_forward_()) {
receiver_.OnWindowUpdate(stream_id, delta_window_size);
}
}
void EventForwarder::OnPushPromise(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId promised_stream_id,
bool end) {
if (can_forward_()) {
receiver_.OnPushPromise(stream_id, promised_stream_id, end);
}
}
void EventForwarder::OnContinuation(spdy::SpdyStreamId stream_id,
size_t payload_length, bool end) {
if (can_forward_()) {
receiver_.OnContinuation(stream_id, payload_length, end);
}
}
void EventForwarder::OnAltSvc(
spdy::SpdyStreamId stream_id, absl::string_view origin,
const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) {
if (can_forward_()) {
receiver_.OnAltSvc(stream_id, origin, altsvc_vector);
}
}
void EventForwarder::OnPriority(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId parent_stream_id, int weight,
bool exclusive) {
if (can_forward_()) {
receiver_.OnPriority(stream_id, parent_stream_id, weight, exclusive);
}
}
void EventForwarder::OnPriorityUpdate(spdy::SpdyStreamId prioritized_stream_id,
absl::string_view priority_field_value) {
if (can_forward_()) {
receiver_.OnPriorityUpdate(prioritized_stream_id, priority_field_value);
}
}
bool EventForwarder::OnUnknownFrame(spdy::SpdyStreamId stream_id,
uint8_t frame_type) {
if (can_forward_()) {
return receiver_.OnUnknownFrame(stream_id, frame_type);
}
return false;
}
void EventForwarder::OnUnknownFrameStart(spdy::SpdyStreamId stream_id,
size_t length, uint8_t type,
uint8_t flags) {
if (can_forward_()) {
receiver_.OnUnknownFrameStart(stream_id, length, type, flags);
}
}
void EventForwarder::OnUnknownFramePayload(spdy::SpdyStreamId stream_id,
absl::string_view payload) {
if (can_forward_()) {
receiver_.OnUnknownFramePayload(stream_id, payload);
}
}
}
} | #include "quiche/http2/adapter/event_forwarder.h"
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/spdy/core/spdy_protocol.h"
#include "quiche/spdy/test_tools/mock_spdy_framer_visitor.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
constexpr absl::string_view some_data = "Here is some data for events";
constexpr spdy::SpdyStreamId stream_id = 1;
constexpr spdy::SpdyErrorCode error_code =
spdy::SpdyErrorCode::ERROR_CODE_ENHANCE_YOUR_CALM;
constexpr size_t length = 42;
TEST(EventForwarderTest, ForwardsEventsWithTruePredicate) {
spdy::test::MockSpdyFramerVisitor receiver;
receiver.DelegateHeaderHandling();
EventForwarder event_forwarder([]() { return true; }, receiver);
EXPECT_CALL(
receiver,
OnError(Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING,
std::string(some_data)));
event_forwarder.OnError(
Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING,
std::string(some_data));
EXPECT_CALL(receiver,
OnCommonHeader(stream_id, length, 0x0, END_STREAM_FLAG));
event_forwarder.OnCommonHeader(stream_id, length, 0x0,
END_STREAM_FLAG);
EXPECT_CALL(receiver, OnDataFrameHeader(stream_id, length, true));
event_forwarder.OnDataFrameHeader(stream_id, length, true);
EXPECT_CALL(receiver,
OnStreamFrameData(stream_id, some_data.data(), some_data.size()));
event_forwarder.OnStreamFrameData(stream_id, some_data.data(),
some_data.size());
EXPECT_CALL(receiver, OnStreamEnd(stream_id));
event_forwarder.OnStreamEnd(stream_id);
EXPECT_CALL(receiver, OnStreamPadLength(stream_id, length));
event_forwarder.OnStreamPadLength(stream_id, length);
EXPECT_CALL(receiver, OnStreamPadding(stream_id, length));
event_forwarder.OnStreamPadding(stream_id, length);
EXPECT_CALL(receiver, OnHeaderFrameStart(stream_id));
spdy::SpdyHeadersHandlerInterface* handler =
event_forwarder.OnHeaderFrameStart(stream_id);
EXPECT_EQ(handler, receiver.ReturnTestHeadersHandler(stream_id));
EXPECT_CALL(receiver, OnHeaderFrameEnd(stream_id));
event_forwarder.OnHeaderFrameEnd(stream_id);
EXPECT_CALL(receiver, OnRstStream(stream_id, error_code));
event_forwarder.OnRstStream(stream_id, error_code);
EXPECT_CALL(receiver, OnSettings());
event_forwarder.OnSettings();
EXPECT_CALL(
receiver,
OnSetting(spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS,
100));
event_forwarder.OnSetting(
spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS, 100);
EXPECT_CALL(receiver, OnSettingsEnd());
event_forwarder.OnSettingsEnd();
EXPECT_CALL(receiver, OnSettingsAck());
event_forwarder.OnSettingsAck();
EXPECT_CALL(receiver, OnPing(42, false));
event_forwarder.OnPing(42, false);
EXPECT_CALL(receiver, OnGoAway(stream_id, error_code));
event_forwarder.OnGoAway(stream_id, error_code);
EXPECT_CALL(receiver, OnGoAwayFrameData(some_data.data(), some_data.size()));
event_forwarder.OnGoAwayFrameData(some_data.data(), some_data.size());
EXPECT_CALL(receiver,
OnHeaders(stream_id, 1234,
false, 42, stream_id + 2,
false, true, true));
event_forwarder.OnHeaders(stream_id, 1234,
false, 42,
stream_id + 2, false, true,
true);
EXPECT_CALL(receiver, OnWindowUpdate(stream_id, 42));
event_forwarder.OnWindowUpdate(stream_id, 42);
EXPECT_CALL(receiver, OnPushPromise(stream_id, stream_id + 1, true));
event_forwarder.OnPushPromise(stream_id, stream_id + 1, true);
EXPECT_CALL(receiver,
OnContinuation(stream_id, 42, true));
event_forwarder.OnContinuation(stream_id, 42,
true);
const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector;
EXPECT_CALL(receiver, OnAltSvc(stream_id, some_data, altsvc_vector));
event_forwarder.OnAltSvc(stream_id, some_data, altsvc_vector);
EXPECT_CALL(receiver, OnPriority(stream_id, stream_id + 2, 42,
false));
event_forwarder.OnPriority(stream_id, stream_id + 2, 42,
false);
EXPECT_CALL(receiver, OnPriorityUpdate(stream_id, some_data));
event_forwarder.OnPriorityUpdate(stream_id, some_data);
EXPECT_CALL(receiver, OnUnknownFrame(stream_id, 0x4D));
event_forwarder.OnUnknownFrame(stream_id, 0x4D);
EXPECT_CALL(receiver, OnUnknownFrameStart(stream_id, 42,
0x4D, 0x0));
event_forwarder.OnUnknownFrameStart(stream_id, 42, 0x4D,
0x0);
}
TEST(EventForwarderTest, DoesNotForwardEventsWithFalsePredicate) {
spdy::test::MockSpdyFramerVisitor receiver;
receiver.DelegateHeaderHandling();
EventForwarder event_forwarder([]() { return false; }, receiver);
EXPECT_CALL(receiver, OnError).Times(0);
event_forwarder.OnError(
Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING,
std::string(some_data));
EXPECT_CALL(receiver, OnCommonHeader).Times(0);
event_forwarder.OnCommonHeader(stream_id, length, 0x0,
END_STREAM_FLAG);
EXPECT_CALL(receiver, OnDataFrameHeader).Times(0);
event_forwarder.OnDataFrameHeader(stream_id, length, true);
EXPECT_CALL(receiver, OnStreamFrameData).Times(0);
event_forwarder.OnStreamFrameData(stream_id, some_data.data(),
some_data.size());
EXPECT_CALL(receiver, OnStreamEnd).Times(0);
event_forwarder.OnStreamEnd(stream_id);
EXPECT_CALL(receiver, OnStreamPadLength).Times(0);
event_forwarder.OnStreamPadLength(stream_id, length);
EXPECT_CALL(receiver, OnStreamPadding).Times(0);
event_forwarder.OnStreamPadding(stream_id, length);
EXPECT_CALL(receiver, OnHeaderFrameStart(stream_id));
spdy::SpdyHeadersHandlerInterface* handler =
event_forwarder.OnHeaderFrameStart(stream_id);
EXPECT_EQ(handler, receiver.ReturnTestHeadersHandler(stream_id));
EXPECT_CALL(receiver, OnHeaderFrameEnd).Times(0);
event_forwarder.OnHeaderFrameEnd(stream_id);
EXPECT_CALL(receiver, OnRstStream).Times(0);
event_forwarder.OnRstStream(stream_id, error_code);
EXPECT_CALL(receiver, OnSettings).Times(0);
event_forwarder.OnSettings();
EXPECT_CALL(receiver, OnSetting).Times(0);
event_forwarder.OnSetting(
spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS, 100);
EXPECT_CALL(receiver, OnSettingsEnd).Times(0);
event_forwarder.OnSettingsEnd();
EXPECT_CALL(receiver, OnSettingsAck).Times(0);
event_forwarder.OnSettingsAck();
EXPECT_CALL(receiver, OnPing).Times(0);
event_forwarder.OnPing(42, false);
EXPECT_CALL(receiver, OnGoAway).Times(0);
event_forwarder.OnGoAway(stream_id, error_code);
EXPECT_CALL(receiver, OnGoAwayFrameData).Times(0);
event_forwarder.OnGoAwayFrameData(some_data.data(), some_data.size());
EXPECT_CALL(receiver, OnHeaders).Times(0);
event_forwarder.OnHeaders(stream_id, 1234,
false, 42,
stream_id + 2, false, true,
true);
EXPECT_CALL(receiver, OnWindowUpdate).Times(0);
event_forwarder.OnWindowUpdate(stream_id, 42);
EXPECT_CALL(receiver, OnPushPromise).Times(0);
event_forwarder.OnPushPromise(stream_id, stream_id + 1, true);
EXPECT_CALL(receiver, OnContinuation).Times(0);
event_forwarder.OnContinuation(stream_id, 42,
true);
EXPECT_CALL(receiver, OnAltSvc).Times(0);
const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector;
event_forwarder.OnAltSvc(stream_id, some_data, altsvc_vector);
EXPECT_CALL(receiver, OnPriority).Times(0);
event_forwarder.OnPriority(stream_id, stream_id + 2, 42,
false);
EXPECT_CALL(receiver, OnPriorityUpdate).Times(0);
event_forwarder.OnPriorityUpdate(stream_id, some_data);
EXPECT_CALL(receiver, OnUnknownFrame).Times(0);
event_forwarder.OnUnknownFrame(stream_id, 0x4D);
EXPECT_CALL(receiver, OnUnknownFrameStart).Times(0);
event_forwarder.OnUnknownFrameStart(stream_id, 42, 0x4D,
0x0);
}
}
}
}
} |
406 | cpp | google/quiche | recording_http2_visitor | quiche/http2/adapter/recording_http2_visitor.cc | quiche/http2/adapter/recording_http2_visitor_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_RECORDING_HTTP2_VISITOR_H_
#define QUICHE_HTTP2_ADAPTER_RECORDING_HTTP2_VISITOR_H_
#include <cstdint>
#include <list>
#include <string>
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
class QUICHE_NO_EXPORT RecordingHttp2Visitor : public Http2VisitorInterface {
public:
using Event = std::string;
using EventSequence = std::list<Event>;
int64_t OnReadyToSend(absl::string_view serialized) override;
DataFrameHeaderInfo OnReadyToSendDataForStream(Http2StreamId stream_id,
size_t max_length) override;
bool SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header,
size_t payload_bytes) override;
void OnConnectionError(ConnectionError error) override;
bool OnFrameHeader(Http2StreamId stream_id, size_t length, uint8_t type,
uint8_t flags) override;
void OnSettingsStart() override;
void OnSetting(Http2Setting setting) override;
void OnSettingsEnd() override;
void OnSettingsAck() override;
bool OnBeginHeadersForStream(Http2StreamId stream_id) override;
OnHeaderResult OnHeaderForStream(Http2StreamId stream_id,
absl::string_view name,
absl::string_view value) override;
bool OnEndHeadersForStream(Http2StreamId stream_id) override;
bool OnDataPaddingLength(Http2StreamId stream_id,
size_t padding_length) override;
bool OnBeginDataForStream(Http2StreamId stream_id,
size_t payload_length) override;
bool OnDataForStream(Http2StreamId stream_id,
absl::string_view data) override;
bool OnEndStream(Http2StreamId stream_id) override;
void OnRstStream(Http2StreamId stream_id, Http2ErrorCode error_code) override;
bool OnCloseStream(Http2StreamId stream_id,
Http2ErrorCode error_code) override;
void OnPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id, int weight,
bool exclusive) override;
void OnPing(Http2PingId ping_id, bool is_ack) override;
void OnPushPromiseForStream(Http2StreamId stream_id,
Http2StreamId promised_stream_id) override;
bool OnGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) override;
void OnWindowUpdate(Http2StreamId stream_id, int window_increment) override;
int OnBeforeFrameSent(uint8_t frame_type, Http2StreamId stream_id,
size_t length, uint8_t flags) override;
int OnFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length,
uint8_t flags, uint32_t error_code) override;
bool OnInvalidFrame(Http2StreamId stream_id,
InvalidFrameError error) override;
void OnBeginMetadataForStream(Http2StreamId stream_id,
size_t payload_length) override;
bool OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) override;
bool OnMetadataEndForStream(Http2StreamId stream_id) override;
std::pair<int64_t, bool> PackMetadataForStream(Http2StreamId stream_id,
uint8_t* dest,
size_t dest_len) override;
void OnErrorDebug(absl::string_view message) override;
const EventSequence& GetEventSequence() const { return events_; }
void Clear() { events_.clear(); }
private:
EventSequence events_;
};
}
}
}
#endif
#include "quiche/http2/adapter/recording_http2_visitor.h"
#include "absl/strings/str_format.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_util.h"
namespace http2 {
namespace adapter {
namespace test {
int64_t RecordingHttp2Visitor::OnReadyToSend(absl::string_view serialized) {
events_.push_back(absl::StrFormat("OnReadyToSend %d", serialized.size()));
return serialized.size();
}
Http2VisitorInterface::DataFrameHeaderInfo
RecordingHttp2Visitor::OnReadyToSendDataForStream(Http2StreamId stream_id,
size_t max_length) {
events_.push_back(absl::StrFormat("OnReadyToSendDataForStream %d %d",
stream_id, max_length));
return {70000, true, true};
}
bool RecordingHttp2Visitor::SendDataFrame(Http2StreamId stream_id,
absl::string_view ,
size_t payload_bytes) {
events_.push_back(
absl::StrFormat("SendDataFrame %d %d", stream_id, payload_bytes));
return true;
}
void RecordingHttp2Visitor::OnConnectionError(ConnectionError error) {
events_.push_back(
absl::StrFormat("OnConnectionError %s", ConnectionErrorToString(error)));
}
bool RecordingHttp2Visitor::OnFrameHeader(Http2StreamId stream_id,
size_t length, uint8_t type,
uint8_t flags) {
events_.push_back(absl::StrFormat("OnFrameHeader %d %d %d %d", stream_id,
length, type, flags));
return true;
}
void RecordingHttp2Visitor::OnSettingsStart() {
events_.push_back("OnSettingsStart");
}
void RecordingHttp2Visitor::OnSetting(Http2Setting setting) {
events_.push_back(absl::StrFormat(
"OnSetting %s %d", Http2SettingsIdToString(setting.id), setting.value));
}
void RecordingHttp2Visitor::OnSettingsEnd() {
events_.push_back("OnSettingsEnd");
}
void RecordingHttp2Visitor::OnSettingsAck() {
events_.push_back("OnSettingsAck");
}
bool RecordingHttp2Visitor::OnBeginHeadersForStream(Http2StreamId stream_id) {
events_.push_back(absl::StrFormat("OnBeginHeadersForStream %d", stream_id));
return true;
}
Http2VisitorInterface::OnHeaderResult RecordingHttp2Visitor::OnHeaderForStream(
Http2StreamId stream_id, absl::string_view name, absl::string_view value) {
events_.push_back(
absl::StrFormat("OnHeaderForStream %d %s %s", stream_id, name, value));
return HEADER_OK;
}
bool RecordingHttp2Visitor::OnEndHeadersForStream(Http2StreamId stream_id) {
events_.push_back(absl::StrFormat("OnEndHeadersForStream %d", stream_id));
return true;
}
bool RecordingHttp2Visitor::OnDataPaddingLength(Http2StreamId stream_id,
size_t padding_length) {
events_.push_back(
absl::StrFormat("OnDataPaddingLength %d %d", stream_id, padding_length));
return true;
}
bool RecordingHttp2Visitor::OnBeginDataForStream(Http2StreamId stream_id,
size_t payload_length) {
events_.push_back(
absl::StrFormat("OnBeginDataForStream %d %d", stream_id, payload_length));
return true;
}
bool RecordingHttp2Visitor::OnDataForStream(Http2StreamId stream_id,
absl::string_view data) {
events_.push_back(absl::StrFormat("OnDataForStream %d %s", stream_id, data));
return true;
}
bool RecordingHttp2Visitor::OnEndStream(Http2StreamId stream_id) {
events_.push_back(absl::StrFormat("OnEndStream %d", stream_id));
return true;
}
void RecordingHttp2Visitor::OnRstStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
events_.push_back(absl::StrFormat("OnRstStream %d %s", stream_id,
Http2ErrorCodeToString(error_code)));
}
bool RecordingHttp2Visitor::OnCloseStream(Http2StreamId stream_id,
Http2ErrorCode error_code) {
events_.push_back(absl::StrFormat("OnCloseStream %d %s", stream_id,
Http2ErrorCodeToString(error_code)));
return true;
}
void RecordingHttp2Visitor::OnPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id,
int weight, bool exclusive) {
events_.push_back(absl::StrFormat("OnPriorityForStream %d %d %d %d",
stream_id, parent_stream_id, weight,
exclusive));
}
void RecordingHttp2Visitor::OnPing(Http2PingId ping_id, bool is_ack) {
events_.push_back(absl::StrFormat("OnPing %d %d", ping_id, is_ack));
}
void RecordingHttp2Visitor::OnPushPromiseForStream(
Http2StreamId stream_id, Http2StreamId promised_stream_id) {
events_.push_back(absl::StrFormat("OnPushPromiseForStream %d %d", stream_id,
promised_stream_id));
}
bool RecordingHttp2Visitor::OnGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
events_.push_back(
absl::StrFormat("OnGoAway %d %s %s", last_accepted_stream_id,
Http2ErrorCodeToString(error_code), opaque_data));
return true;
}
void RecordingHttp2Visitor::OnWindowUpdate(Http2StreamId stream_id,
int window_increment) {
events_.push_back(
absl::StrFormat("OnWindowUpdate %d %d", stream_id, window_increment));
}
int RecordingHttp2Visitor::OnBeforeFrameSent(uint8_t frame_type,
Http2StreamId stream_id,
size_t length, uint8_t flags) {
events_.push_back(absl::StrFormat("OnBeforeFrameSent %d %d %d %d", frame_type,
stream_id, length, flags));
return 0;
}
int RecordingHttp2Visitor::OnFrameSent(uint8_t frame_type,
Http2StreamId stream_id, size_t length,
uint8_t flags, uint32_t error_code) {
events_.push_back(absl::StrFormat("OnFrameSent %d %d %d %d %d", frame_type,
stream_id, length, flags, error_code));
return 0;
}
bool RecordingHttp2Visitor::OnInvalidFrame(Http2StreamId stream_id,
InvalidFrameError error) {
events_.push_back(absl::StrFormat("OnInvalidFrame %d %s", stream_id,
InvalidFrameErrorToString(error)));
return true;
}
void RecordingHttp2Visitor::OnBeginMetadataForStream(Http2StreamId stream_id,
size_t payload_length) {
events_.push_back(absl::StrFormat("OnBeginMetadataForStream %d %d", stream_id,
payload_length));
}
bool RecordingHttp2Visitor::OnMetadataForStream(Http2StreamId stream_id,
absl::string_view metadata) {
events_.push_back(
absl::StrFormat("OnMetadataForStream %d %s", stream_id, metadata));
return true;
}
bool RecordingHttp2Visitor::OnMetadataEndForStream(Http2StreamId stream_id) {
events_.push_back(absl::StrFormat("OnMetadataEndForStream %d", stream_id));
return true;
}
std::pair<int64_t, bool> RecordingHttp2Visitor::PackMetadataForStream(
Http2StreamId stream_id, uint8_t* , size_t ) {
events_.push_back(absl::StrFormat("PackMetadataForStream %d", stream_id));
return {1, true};
}
void RecordingHttp2Visitor::OnErrorDebug(absl::string_view message) {
events_.push_back(absl::StrFormat("OnErrorDebug %s", message));
}
}
}
} | #include "quiche/http2/adapter/recording_http2_visitor.h"
#include <list>
#include <string>
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using ::testing::IsEmpty;
TEST(RecordingHttp2VisitorTest, EmptySequence) {
RecordingHttp2Visitor chocolate_visitor;
RecordingHttp2Visitor vanilla_visitor;
EXPECT_THAT(chocolate_visitor.GetEventSequence(), IsEmpty());
EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty());
EXPECT_EQ(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
chocolate_visitor.OnSettingsStart();
EXPECT_THAT(chocolate_visitor.GetEventSequence(), testing::Not(IsEmpty()));
EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty());
EXPECT_NE(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
chocolate_visitor.Clear();
EXPECT_THAT(chocolate_visitor.GetEventSequence(), IsEmpty());
EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty());
EXPECT_EQ(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
}
TEST(RecordingHttp2VisitorTest, SameEventsProduceSameSequence) {
RecordingHttp2Visitor chocolate_visitor;
RecordingHttp2Visitor vanilla_visitor;
http2::test::Http2Random random;
const Http2StreamId stream_id = random.Uniform(kMaxStreamId);
const Http2StreamId another_stream_id = random.Uniform(kMaxStreamId);
const size_t length = random.Rand16();
const uint8_t type = random.Rand8();
const uint8_t flags = random.Rand8();
const Http2ErrorCode error_code = static_cast<Http2ErrorCode>(
random.Uniform(static_cast<int>(Http2ErrorCode::MAX_ERROR_CODE)));
const Http2Setting setting = {random.Rand16(), random.Rand32()};
const absl::string_view alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-";
const std::string some_string =
random.RandStringWithAlphabet(random.Rand8(), alphabet);
const std::string another_string =
random.RandStringWithAlphabet(random.Rand8(), alphabet);
const uint16_t some_int = random.Rand16();
const bool some_bool = random.OneIn(2);
std::list<RecordingHttp2Visitor*> visitors = {&chocolate_visitor,
&vanilla_visitor};
for (RecordingHttp2Visitor* visitor : visitors) {
visitor->OnConnectionError(
Http2VisitorInterface::ConnectionError::kSendError);
visitor->OnFrameHeader(stream_id, length, type, flags);
visitor->OnSettingsStart();
visitor->OnSetting(setting);
visitor->OnSettingsEnd();
visitor->OnSettingsAck();
visitor->OnBeginHeadersForStream(stream_id);
visitor->OnHeaderForStream(stream_id, some_string, another_string);
visitor->OnEndHeadersForStream(stream_id);
visitor->OnBeginDataForStream(stream_id, length);
visitor->OnDataForStream(stream_id, some_string);
visitor->OnDataForStream(stream_id, another_string);
visitor->OnEndStream(stream_id);
visitor->OnRstStream(stream_id, error_code);
visitor->OnCloseStream(stream_id, error_code);
visitor->OnPriorityForStream(stream_id, another_stream_id, some_int,
some_bool);
visitor->OnPing(some_int, some_bool);
visitor->OnPushPromiseForStream(stream_id, another_stream_id);
visitor->OnGoAway(stream_id, error_code, some_string);
visitor->OnWindowUpdate(stream_id, some_int);
visitor->OnBeginMetadataForStream(stream_id, length);
visitor->OnMetadataForStream(stream_id, some_string);
visitor->OnMetadataForStream(stream_id, another_string);
visitor->OnMetadataEndForStream(stream_id);
}
EXPECT_EQ(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
}
TEST(RecordingHttp2VisitorTest, DifferentEventsProduceDifferentSequence) {
RecordingHttp2Visitor chocolate_visitor;
RecordingHttp2Visitor vanilla_visitor;
EXPECT_EQ(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
const Http2StreamId stream_id = 1;
const size_t length = 42;
chocolate_visitor.OnBeginDataForStream(stream_id, length);
vanilla_visitor.OnBeginMetadataForStream(stream_id, length);
EXPECT_NE(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
chocolate_visitor.Clear();
vanilla_visitor.Clear();
EXPECT_EQ(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
chocolate_visitor.OnBeginHeadersForStream(stream_id);
vanilla_visitor.OnBeginHeadersForStream(stream_id + 2);
EXPECT_NE(chocolate_visitor.GetEventSequence(),
vanilla_visitor.GetEventSequence());
}
}
}
}
} |
407 | cpp | google/quiche | oghttp2_session | quiche/http2/adapter/oghttp2_session.cc | quiche/http2/adapter/oghttp2_session_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_OGHTTP2_SESSION_H_
#define QUICHE_HTTP2_ADAPTER_OGHTTP2_SESSION_H_
#include <cstdint>
#include <limits>
#include <list>
#include <memory>
#include <optional>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/types/variant.h"
#include "quiche/http2/adapter/chunked_buffer.h"
#include "quiche/http2/adapter/data_source.h"
#include "quiche/http2/adapter/event_forwarder.h"
#include "quiche/http2/adapter/header_validator.h"
#include "quiche/http2/adapter/header_validator_base.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_session.h"
#include "quiche/http2/adapter/http2_util.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/window_manager.h"
#include "quiche/http2/core/http2_trace_logging.h"
#include "quiche/http2/core/priority_write_scheduler.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_flags.h"
#include "quiche/common/quiche_callbacks.h"
#include "quiche/common/quiche_circular_deque.h"
#include "quiche/common/quiche_linked_hash_map.h"
#include "quiche/spdy/core/http2_frame_decoder_adapter.h"
#include "quiche/spdy/core/http2_header_block.h"
#include "quiche/spdy/core/no_op_headers_handler.h"
#include "quiche/spdy/core/spdy_framer.h"
#include "quiche/spdy/core/spdy_protocol.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT OgHttp2Session : public Http2Session,
public spdy::SpdyFramerVisitorInterface {
public:
struct QUICHE_EXPORT Options {
WindowManager::ShouldWindowUpdateFn should_window_update_fn =
DeltaAtLeastHalfLimit;
Perspective perspective = Perspective::kClient;
std::optional<size_t> max_hpack_encoding_table_capacity;
std::optional<uint32_t> max_header_list_bytes = std::nullopt;
std::optional<uint32_t> max_header_field_size = std::nullopt;
std::optional<uint32_t> remote_max_concurrent_streams = std::nullopt;
bool auto_ping_ack = true;
bool rst_stream_no_error_when_incomplete = false;
bool blackhole_data_on_connection_error = true;
bool allow_extended_connect = true;
bool allow_obs_text = true;
bool validate_http_headers = true;
bool validate_path = false;
bool allow_fragment_in_path = true;
bool allow_different_host_and_authority = false;
bool crumble_cookies = false;
};
OgHttp2Session(Http2VisitorInterface& visitor, Options options);
~OgHttp2Session() override;
void EnqueueFrame(std::unique_ptr<spdy::SpdyFrameIR> frame);
void StartGracefulShutdown();
int Send();
int32_t SubmitRequest(absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream, void* user_data);
int SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream);
int SubmitTrailer(Http2StreamId stream_id, absl::Span<const Header> trailers);
void SubmitMetadata(Http2StreamId stream_id,
std::unique_ptr<MetadataSource> source);
void SubmitMetadata(Http2StreamId stream_id);
void SubmitSettings(absl::Span<const Http2Setting> settings);
bool IsServerSession() const {
return options_.perspective == Perspective::kServer;
}
Http2StreamId GetHighestReceivedStreamId() const {
return highest_received_stream_id_;
}
void SetStreamUserData(Http2StreamId stream_id, void* user_data);
void* GetStreamUserData(Http2StreamId stream_id);
bool ResumeStream(Http2StreamId stream_id);
int GetStreamSendWindowSize(Http2StreamId stream_id) const;
int GetStreamReceiveWindowLimit(Http2StreamId stream_id) const;
int GetStreamReceiveWindowSize(Http2StreamId stream_id) const;
int GetReceiveWindowSize() const;
int GetHpackEncoderDynamicTableSize() const;
int GetHpackEncoderDynamicTableCapacity() const;
int GetHpackDecoderDynamicTableSize() const;
int GetHpackDecoderSizeLimit() const;
uint32_t GetMaxOutboundConcurrentStreams() const {
return max_outbound_concurrent_streams_;
}
int64_t ProcessBytes(absl::string_view bytes) override;
int Consume(Http2StreamId stream_id, size_t num_bytes) override;
bool want_read() const override {
return !received_goaway_ && !decoder_.HasError();
}
bool want_write() const override {
return !fatal_send_error_ &&
(!frames_.empty() || !buffered_data_.Empty() || HasReadyStream() ||
!goaway_rejected_streams_.empty());
}
int GetRemoteWindowSize() const override { return connection_send_window_; }
bool peer_enables_connect_protocol() {
return peer_enables_connect_protocol_;
}
void OnError(http2::Http2DecoderAdapter::SpdyFramerError error,
std::string detailed_error) override;
void OnCommonHeader(spdy::SpdyStreamId , size_t ,
uint8_t , uint8_t ) override;
void OnDataFrameHeader(spdy::SpdyStreamId stream_id, size_t length,
bool fin) override;
void OnStreamFrameData(spdy::SpdyStreamId stream_id, const char* data,
size_t len) override;
void OnStreamEnd(spdy::SpdyStreamId stream_id) override;
void OnStreamPadLength(spdy::SpdyStreamId ,
size_t ) override;
void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override;
spdy::SpdyHeadersHandlerInterface* OnHeaderFrameStart(
spdy::SpdyStreamId stream_id) override;
void OnHeaderFrameEnd(spdy::SpdyStreamId stream_id) override;
void OnRstStream(spdy::SpdyStreamId stream_id,
spdy::SpdyErrorCode error_code) override;
void OnSettings() override;
void OnSetting(spdy::SpdySettingsId id, uint32_t value) override;
void OnSettingsEnd() override;
void OnSettingsAck() override;
void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override;
void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
spdy::SpdyErrorCode error_code) override;
bool OnGoAwayFrameData(const char* goaway_data, size_t len) override;
void OnHeaders(spdy::SpdyStreamId stream_id, size_t payload_length,
bool has_priority, int weight,
spdy::SpdyStreamId parent_stream_id, bool exclusive, bool fin,
bool end) override;
void OnWindowUpdate(spdy::SpdyStreamId stream_id,
int delta_window_size) override;
void OnPushPromise(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId promised_stream_id, bool end) override;
void OnContinuation(spdy::SpdyStreamId stream_id, size_t payload_length,
bool end) override;
void OnAltSvc(spdy::SpdyStreamId , absl::string_view ,
const spdy::SpdyAltSvcWireFormat::
AlternativeServiceVector& ) override;
void OnPriority(spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId parent_stream_id, int weight,
bool exclusive) override;
void OnPriorityUpdate(spdy::SpdyStreamId prioritized_stream_id,
absl::string_view priority_field_value) override;
bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
uint8_t frame_type) override;
void OnUnknownFrameStart(spdy::SpdyStreamId stream_id, size_t length,
uint8_t type, uint8_t flags) override;
void OnUnknownFramePayload(spdy::SpdyStreamId stream_id,
absl::string_view payload) override;
void OnHeaderStatus(Http2StreamId stream_id,
Http2VisitorInterface::OnHeaderResult result);
private:
struct QUICHE_EXPORT StreamState {
StreamState(int32_t stream_receive_window, int32_t stream_send_window,
WindowManager::WindowUpdateListener listener,
WindowManager::ShouldWindowUpdateFn should_window_update_fn)
: window_manager(stream_receive_window, std::move(listener),
std::move(should_window_update_fn),
false),
send_window(stream_send_window) {}
WindowManager window_manager;
std::unique_ptr<DataFrameSource> outbound_body;
std::unique_ptr<spdy::Http2HeaderBlock> trailers;
void* user_data = nullptr;
int32_t send_window;
std::optional<HeaderType> received_header_type;
std::optional<size_t> remaining_content_length;
bool check_visitor_for_body = false;
bool half_closed_local = false;
bool half_closed_remote = false;
bool data_deferred = false;
bool sent_head_method = false;
bool can_receive_body = true;
};
using StreamStateMap = absl::flat_hash_map<Http2StreamId, StreamState>;
struct QUICHE_EXPORT PendingStreamState {
spdy::Http2HeaderBlock headers;
std::unique_ptr<DataFrameSource> data_source;
void* user_data = nullptr;
bool end_stream;
};
class QUICHE_EXPORT PassthroughHeadersHandler
: public spdy::SpdyHeadersHandlerInterface {
public:
PassthroughHeadersHandler(OgHttp2Session& session,
Http2VisitorInterface& visitor);
void Reset() {
error_encountered_ = false;
}
void set_stream_id(Http2StreamId stream_id) { stream_id_ = stream_id; }
void set_frame_contains_fin(bool value) { frame_contains_fin_ = value; }
void set_header_type(HeaderType type) { type_ = type; }
HeaderType header_type() const { return type_; }
void OnHeaderBlockStart() override;
void OnHeader(absl::string_view key, absl::string_view value) override;
void OnHeaderBlockEnd(size_t ,
size_t ) override;
absl::string_view status_header() const {
QUICHE_DCHECK(type_ == HeaderType::RESPONSE ||
type_ == HeaderType::RESPONSE_100);
return validator_->status_header();
}
std::optional<size_t> content_length() const {
return validator_->content_length();
}
void SetAllowExtendedConnect() { validator_->SetAllowExtendedConnect(); }
void SetMaxFieldSize(uint32_t field_size) {
validator_->SetMaxFieldSize(field_size);
}
void SetAllowObsText(bool allow) {
validator_->SetObsTextOption(allow ? ObsTextOption::kAllow
: ObsTextOption::kDisallow);
}
bool CanReceiveBody() const;
private:
void SetResult(Http2VisitorInterface::OnHeaderResult result);
OgHttp2Session& session_;
Http2VisitorInterface& visitor_;
Http2StreamId stream_id_ = 0;
std::unique_ptr<HeaderValidatorBase> validator_;
HeaderType type_ = HeaderType::RESPONSE;
bool frame_contains_fin_ = false;
bool error_encountered_ = false;
};
struct QUICHE_EXPORT ProcessBytesResultVisitor;
void MaybeSetupPreface(bool sending_outbound_settings);
std::vector<Http2Setting> GetInitialSettings() const;
std::unique_ptr<spdy::SpdySettingsIR> PrepareSettingsFrame(
absl::Span<const Http2Setting> settings);
void HandleOutboundSettings(const spdy::SpdySettingsIR& settings_frame);
void SendWindowUpdate(Http2StreamId stream_id, size_t update_delta);
enum class SendResult {
SEND_OK,
SEND_BLOCKED,
SEND_ERROR,
};
int InterpretSendResult(SendResult result);
enum class ProcessBytesError {
kUnspecified,
kInvalidConnectionPreface,
kVisitorCallbackFailed,
};
using ProcessBytesResult = absl::variant<int64_t, ProcessBytesError>;
ProcessBytesResult ProcessBytesImpl(absl::string_view bytes);
bool HasReadyStream() const;
Http2StreamId GetNextReadyStream();
int32_t SubmitRequestInternal(absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream, void* user_data);
int SubmitResponseInternal(Http2StreamId stream_id,
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream);
SendResult MaybeSendBufferedData();
SendResult SendQueuedFrames();
bool AfterFrameSent(uint8_t frame_type_int, uint32_t stream_id,
size_t payload_length, uint8_t flags,
uint32_t error_code);
SendResult WriteForStream(Http2StreamId stream_id);
void SerializeMetadata(Http2StreamId stream_id,
std::unique_ptr<MetadataSource> source);
void SerializeMetadata(Http2StreamId stream_id);
void SendHeaders(Http2StreamId stream_id, spdy::Http2HeaderBlock headers,
bool end_stream);
void SendTrailers(Http2StreamId stream_id, spdy::Http2HeaderBlock trailers);
void MaybeFinWithRstStream(StreamStateMap::iterator iter);
void MarkDataBuffered(Http2StreamId stream_id, size_t bytes);
StreamStateMap::iterator CreateStream(Http2StreamId stream_id);
void StartRequest(Http2StreamId stream_id, spdy::Http2HeaderBlock headers,
std::unique_ptr<DataFrameSource> data_source,
void* user_data, bool end_stream);
void StartPendingStreams();
void CloseStream(Http2StreamId stream_id, Http2ErrorCode error_code);
HeaderType NextHeaderType(std::optional<HeaderType> current_type);
bool CanCreateStream() const;
void LatchErrorAndNotify(Http2ErrorCode error_code,
Http2VisitorInterface::ConnectionError error);
void CloseStreamIfReady(uint8_t frame_type, uint32_t stream_id);
void CloseGoAwayRejectedStreams();
void PrepareForImmediateGoAway();
void MaybeHandleMetadataEndForStream(Http2StreamId stream_id);
void DecrementQueuedFrameCount(uint32_t stream_id, uint8_t frame_type);
void HandleContentLengthError(Http2StreamId stream_id);
void UpdateReceiveWindow(Http2StreamId stream_id, int32_t delta);
void UpdateStreamSendWindowSizes(uint32_t new_value);
void UpdateStreamReceiveWindowSizes(uint32_t new_value);
bool HasMoreData(const StreamState& stream_state) const;
bool IsReadyToWriteData(const StreamState& stream_state) const;
void AbandonData(StreamState& stream_state);
using DataFrameHeaderInfo = Http2VisitorInterface::DataFrameHeaderInfo;
DataFrameHeaderInfo GetDataFrameInfo(Http2StreamId stream_id,
size_t flow_control_available,
StreamState& stream_state);
bool SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header,
size_t payload_length, StreamState& stream_state);
Http2VisitorInterface& visitor_;
const Options options_;
EventForwarder event_forwarder_;
Http2TraceLogger receive_logger_;
Http2FrameLogger send_logger_;
spdy::SpdyFramer framer_{spdy::SpdyFramer::ENABLE_COMPRESSION};
http2::Http2DecoderAdapter decoder_;
StreamStateMap stream_map_;
quiche::QuicheLinkedHashMap<Http2StreamId, PendingStreamState>
pending_streams_;
std::list<std::unique_ptr<spdy::SpdyFrameIR>> frames_;
ChunkedBuffer buffered_data_;
using WriteScheduler = PriorityWriteScheduler<Http2StreamId>;
WriteScheduler write_scheduler_;
using SettingsAckCallback = quiche::SingleUseCallback<void()>;
quiche::QuicheCircularDeque<SettingsAckCallback> settings_ack_callbacks_;
PassthroughHeadersHandler headers_handler_;
spdy::NoOpHeadersHandler noop_headers_handler_;
absl::string_view remaining_preface_;
WindowManager connection_window_manager_;
absl::flat_hash_set<Http2StreamId> streams_reset_;
absl::flat_hash_map<Http2StreamId, int> queued_frames_;
absl::flat_hash_set<Http2StreamId> trailers_ready_;
absl::flat_hash_set<Http2StreamId> goaway_rejected_streams_;
Http2StreamId next_stream_id_ = 1;
Http2StreamId highest_received_stream_id_ = 0;
Http2StreamId highest_processed_stream_id_ = 0;
Http2StreamId received_goaway_stream_id_ = 0;
size_t metadata_length_ = 0;
int32_t connection_send_window_ = kInitialFlowControlWindowSize;
int32_t initial_stream_receive_window_ = kInitialFlowControlWindowSize;
int32_t initial_stream_send_window_ = kInitialFlowControlWindowSize;
uint32_t max_frame_payload_ = kDefaultFramePayloadSizeLimit;
uint32_t max_outbound_concurrent_streams_;
uint32_t pending_max_inbound_concurrent_streams_ =
std::numeric_limits<uint32_t>::max();
uint32_t max_inbound_concurrent_streams_ =
std::numeric_limits<uint32_t>::max();
std::optional<uint32_t> encoder_header_table_capacity_when_acking_;
uint8_t current_frame_type_ = 0;
bool received_goaway_ = false;
bool queued_preface_ = false;
bool peer_supports_metadata_ = false;
bool end_metadata_ = false;
bool process_metadata_ = false;
bool sent_non_ack_settings_ = false;
bool processing_bytes_ = false;
bool sending_ = false;
bool peer_enables_connect_protocol_ = false;
bool queued_goaway_ = false;
bool queued_immediate_goaway_ = false;
bool latched_error_ = false;
bool fatal_send_error_ = false;
bool fatal_visitor_callback_failure_ = false;
};
}
}
#endif
#include "quiche/http2/adapter/oghttp2_session.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/memory/memory.h"
#include "absl/strings/escaping.h"
#include "quiche/http2/adapter/header_validator.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_util.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/noop_header_validator.h"
#include "quiche/http2/adapter/oghttp2_util.h"
#include "quiche/common/quiche_callbacks.h"
#include "quiche/spdy/core/spdy_protocol.h"
namespace http2 {
namespace adapter {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
using DataFrameHeaderInfo = Http2VisitorInterface::DataFrameHeaderInfo;
using SpdyFramerError = Http2DecoderAdapter::SpdyFramerError;
using ::spdy::SpdySettingsIR;
const uint32_t kMaxAllowedMetadataFrameSize = 65536u;
const uint32_t kDefaultHpackTableCapacity = 4096u;
const uint32_t kMaximumHpackTableCapacity = 65536u;
const int kSendError = -902;
constexpr absl::string_view kHeadValue = "HEAD";
class FrameAttributeCollector : public spdy::SpdyFrameVisitor {
public:
FrameAttributeCollector() = default;
void VisitData(const spdy::SpdyDataIR& data) override {
frame_type_ = static_cast<uint8_t>(data.frame_type());
stream_id_ = data.stream_id();
flags_ =
(data.fin() ? END_STREAM_FLAG : 0) | (data.padded() ? PADDED_FLAG : 0);
}
void VisitHeaders(const spdy::SpdyHeadersIR& headers) override {
frame_type_ = static_cast<uint8_t>(headers.frame_type());
stream_id_ = headers.stream_id();
flags_ = END_HEADERS_FLAG | (headers.fin() ? END_STREAM_FLAG : 0) |
(headers.padded() ? PADDED_FLAG : 0) |
(headers.has_priority() ? PRIORITY_FLAG : 0);
}
void VisitPriority(const spdy::SpdyPriorityIR& priority) override {
frame_type_ = static_cast<uint8_t>(priority.frame_type());
frame_type_ = 2;
stream_id_ = priority.stream_id();
}
void VisitRstStream(const spdy::SpdyRstStreamIR& rst_stream) override {
frame_type_ = static_cast<uint8_t>(rst_stream.frame_type());
frame_type_ = 3;
stream_id_ = rst_stream.stream_id();
error_code_ = rst_stream.error_code();
}
void VisitSettings(const spdy::SpdySettingsIR& settings) override {
frame_type_ = static_cast<uint8_t>(settings.frame_type());
frame_type_ = 4;
flags_ = (settings.is_ack() ? ACK_FLAG : 0);
}
void VisitPushPromise(const spdy::SpdyPushPromiseIR& push_promise) override {
frame_type_ = static_cast<uint8_t>(push_promise.frame_type());
frame_type_ = 5;
stream_id_ = push_promise.stream_id();
flags_ = (push_promise.padded() ? PADDED_FLAG : 0);
}
void VisitPing(const spdy::SpdyPingIR& ping) override {
frame_type_ = static_cast<uint8_t>(ping.frame_type());
frame_type_ = 6;
flags_ = (ping.is_ack() ? ACK_FLAG : 0);
}
void VisitGoAway(const spdy::SpdyGoAwayIR& goaway) override {
frame_type_ = static_cast<uint8_t>(goaway.frame_type());
frame_type_ = 7;
error_code_ = goaway.error_code();
}
void VisitWindowUpdate(
const spdy::SpdyWindowUpdateIR& window_update) override {
frame_type_ = static_cast<uint8_t>(window_update.frame_type());
frame_type_ = 8;
stream_id_ = window_update.stream_id();
}
void VisitContinuation(
const spdy::SpdyContinuationIR& continuation) override {
frame_type_ = static_cast<uint8_t>(continuation.frame_type());
stream_id_ = continuation.stream_id();
flags_ = continuation.end_headers() ? END_HEADERS_FLAG : 0;
}
void VisitUnknown(const spdy::SpdyUnknownIR& unknown) override {
frame_type_ = static_cast<uint8_t>(unknown.frame_type());
stream_id_ = unknown.stream_id();
flags_ = unknown.flags();
}
void VisitAltSvc(const spdy::SpdyAltSvcIR& ) override {}
void VisitPriorityUpdate(
const spdy::SpdyPriorityUpdateIR& ) override {}
void VisitAcceptCh(const spdy::SpdyAcceptChIR& ) override {}
uint32_t stream_id() { return stream_id_; }
uint32_t error_code() { return error_code_; }
uint8_t frame_type() { return frame_type_; }
uint8_t flags() { return flags_; }
private:
uint32_t stream_id_ = 0;
uint32_t error_code_ = 0;
uint8_t frame_type_ = 0;
uint8_t flags_ = 0;
};
absl::string_view TracePerspectiveAsString(Perspective p) {
switch (p) {
case Perspective::kClient:
return "OGHTTP2_CLIENT";
case Perspective::kServer:
return "OGHTTP2_SERVER";
}
return "OGHTTP2_SERVER";
}
Http2ErrorCode GetHttp2ErrorCode(SpdyFramerError error) {
switch (error) {
case SpdyFramerError::SPDY_NO_ERROR:
return Http2ErrorCode::HTTP2_NO_ERROR;
case SpdyFramerError::SPDY_INVALID_STREAM_ID:
case SpdyFramerError::SPDY_INVALID_CONTROL_FRAME:
case SpdyFramerError::SPDY_INVALID_PADDING:
case SpdyFramerError::SPDY_INVALID_DATA_FRAME_FLAGS:
case SpdyFramerError::SPDY_UNEXPECTED_FRAME:
return Http2ErrorCode::PROTOCOL_ERROR;
case SpdyFramerError::SPDY_CONTROL_PAYLOAD_TOO_LARGE:
case SpdyFramerError::SPDY_INVALID_CONTROL_FRAME_SIZE:
case SpdyFramerError::SPDY_OVERSIZED_PAYLOAD:
return Http2ErrorCode::FRAME_SIZE_ERROR;
case SpdyFramerError::SPDY_DECOMPRESS_FAILURE:
case SpdyFramerError::SPDY_HPACK_INDEX_VARINT_ERROR:
case SpdyFramerError::SPDY_HPACK_NAME_LENGTH_VARINT_ERROR:
case SpdyFramerError::SPDY_HPACK_VALUE_LENGTH_VARINT_ERROR:
case SpdyFramerError::SPDY_HPACK_NAME_TOO_LONG:
case SpdyFramerError::SPDY_HPACK_VALUE_TOO_LONG:
case SpdyFramerError::SPDY_HPACK_NAME_HUFFMAN_ERROR:
case SpdyFramerError::SPDY_HPACK_VALUE_HUFFMAN_ERROR:
case SpdyFramerError::SPDY_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE:
case SpdyFramerError::SPDY_HPACK_INVALID_INDEX:
case SpdyFramerError::SPDY_HPACK_INVALID_NAME_INDEX:
case SpdyFramerError::SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED:
case SpdyFramerError::
SPDY_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATE | #include "quiche/http2/adapter/oghttp2_session.h"
#include <memory>
#include <string>
#include <utility>
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using spdy::SpdyFrameType;
using testing::_;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
};
}
TEST(OgHttp2SessionTest, ClientConstruction) {
testing::StrictMock<MockHttp2Visitor> visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_TRUE(session.want_read());
EXPECT_FALSE(session.want_write());
EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize);
EXPECT_FALSE(session.IsServerSession());
EXPECT_EQ(0, session.GetHighestReceivedStreamId());
EXPECT_EQ(100u, session.GetMaxOutboundConcurrentStreams());
}
TEST(OgHttp2SessionTest, ClientConstructionWithMaxStreams) {
testing::StrictMock<MockHttp2Visitor> visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
options.remote_max_concurrent_streams = 200u;
OgHttp2Session session(visitor, options);
EXPECT_EQ(200u, session.GetMaxOutboundConcurrentStreams());
}
TEST(OgHttp2SessionTest, ClientHandlesFrames) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
const std::string initial_frames = TestFrameSequence()
.ServerPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1000));
const int64_t initial_result = session.ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_EQ(session.GetRemoteWindowSize(),
kInitialFlowControlWindowSize + 1000);
EXPECT_EQ(0, session.GetHighestReceivedStreamId());
EXPECT_EQ(kInitialFlowControlWindowSize, session.GetReceiveWindowSize());
EXPECT_EQ(0, session.GetHpackDecoderDynamicTableSize());
const char* kSentinel1 = "arbitrary pointer 1";
visitor.AppendPayloadForStream(1, "This is an example request body.");
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id = session.SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, const_cast<char*>(kSentinel1));
ASSERT_EQ(stream_id, 1);
int stream_id2 =
session.SubmitRequest(ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}}),
nullptr, true, nullptr);
EXPECT_EQ(stream_id2, 3);
const std::string stream_frames =
TestFrameSequence()
.Headers(stream_id,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(stream_id, "This is the response body.")
.RstStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR)
.GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200"));
EXPECT_CALL(visitor,
OnHeaderForStream(stream_id, "server", "my-fake-server"));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "date",
"Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id));
EXPECT_CALL(visitor, OnFrameHeader(stream_id, 26, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(stream_id, 26));
EXPECT_CALL(visitor,
OnDataForStream(stream_id, "This is the response body."));
EXPECT_CALL(visitor, OnFrameHeader(stream_id2, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor,
OnCloseStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor, OnFrameHeader(0, 19, GOAWAY, 0));
EXPECT_CALL(visitor, OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, ""));
const int64_t stream_result = session.ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_EQ(stream_id2, session.GetHighestReceivedStreamId());
EXPECT_GT(kInitialFlowControlWindowSize,
session.GetStreamReceiveWindowSize(stream_id));
EXPECT_EQ(session.GetReceiveWindowSize(),
session.GetStreamReceiveWindowSize(stream_id));
EXPECT_EQ(kInitialFlowControlWindowSize,
session.GetStreamReceiveWindowLimit(stream_id));
EXPECT_GT(session.GetHpackDecoderDynamicTableSize(), 0);
}
TEST(OgHttp2SessionTest, ClientEnqueuesSettingsOnSend) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(OgHttp2SessionTest, ClientEnqueuesSettingsBeforeOtherFrame) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
session.EnqueueFrame(std::make_unique<spdy::SpdyPingIR>(42));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x0));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
}
TEST(OgHttp2SessionTest, ClientEnqueuesSettingsOnce) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
session.EnqueueFrame(std::make_unique<spdy::SpdySettingsIR>());
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(OgHttp2SessionTest, ClientSubmitRequest) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = session.ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
EXPECT_EQ(0, session.GetHpackEncoderDynamicTableSize());
const char* kSentinel1 = "arbitrary pointer 1";
visitor.AppendPayloadForStream(1, "This is an example request body.");
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id = session.SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, const_cast<char*>(kSentinel1));
ASSERT_EQ(stream_id, 1);
EXPECT_TRUE(session.want_write());
EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS,
spdy::SpdyFrameType::DATA}));
visitor.Clear();
EXPECT_FALSE(session.want_write());
EXPECT_LT(session.GetStreamSendWindowSize(stream_id),
kInitialFlowControlWindowSize);
EXPECT_GT(session.GetStreamSendWindowSize(stream_id), 0);
EXPECT_EQ(-1, session.GetStreamSendWindowSize(stream_id + 2));
EXPECT_GT(session.GetHpackEncoderDynamicTableSize(), 0);
stream_id =
session.SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}}),
nullptr, true, nullptr);
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(session.want_write());
const char* kSentinel2 = "arbitrary pointer 2";
EXPECT_EQ(nullptr, session.GetStreamUserData(stream_id));
session.SetStreamUserData(stream_id, const_cast<char*>(kSentinel2));
EXPECT_EQ(kSentinel2, session.GetStreamUserData(stream_id));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS}));
EXPECT_EQ(session.GetStreamSendWindowSize(stream_id),
kInitialFlowControlWindowSize);
}
TEST(OgHttp2SessionTest, ClientSubmitRequestWithLargePayload) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
const std::string initial_frames =
TestFrameSequence()
.ServerPreface(
{Http2Setting{Http2KnownSettingsId::MAX_FRAME_SIZE, 32768u}})
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{
Http2KnownSettingsId::MAX_FRAME_SIZE, 32768u}));
EXPECT_CALL(visitor, OnSettingsEnd());
const int64_t initial_result = session.ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
visitor.Clear();
visitor.AppendPayloadForStream(1, std::string(20000, 'a'));
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id =
session.SubmitRequest(ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, nullptr);
ASSERT_EQ(stream_id, 1);
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS,
spdy::SpdyFrameType::DATA}));
visitor.Clear();
EXPECT_FALSE(session.want_write());
}
TEST(OgHttp2SessionTest, ClientSubmitRequestWithReadBlock) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
const char* kSentinel1 = "arbitrary pointer 1";
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id = session.SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, const_cast<char*>(kSentinel1));
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(session.want_write());
EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_FALSE(session.want_write());
visitor.AppendPayloadForStream(1, "This is an example request body.");
visitor.SetEndData(1, true);
EXPECT_TRUE(session.ResumeStream(stream_id));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA}));
EXPECT_FALSE(session.want_write());
EXPECT_FALSE(session.ResumeStream(stream_id));
EXPECT_FALSE(session.want_write());
}
TEST(OgHttp2SessionTest, ClientSubmitRequestEmptyDataWithFin) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
const char* kSentinel1 = "arbitrary pointer 1";
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id = session.SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, const_cast<char*>(kSentinel1));
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(session.want_write());
EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
int result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_FALSE(session.want_write());
visitor.SetEndData(1, true);
EXPECT_TRUE(session.ResumeStream(stream_id));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 0, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA}));
EXPECT_FALSE(session.want_write());
EXPECT_FALSE(session.ResumeStream(stream_id));
EXPECT_FALSE(session.want_write());
}
TEST(OgHttp2SessionTest, ClientSubmitRequestWithWriteBlock) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kClient;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
const char* kSentinel1 = "arbitrary pointer 1";
visitor.AppendPayloadForStream(1, "This is an example request body.");
visitor.SetEndData(1, true);
auto body1 = std::make_unique<VisitorDataSource>(visitor, 1);
int stream_id = session.SubmitRequest(
ToHeaders({{":method", "POST"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}}),
std::move(body1), false, const_cast<char*>(kSentinel1));
EXPECT_GT(stream_id, 0);
EXPECT_TRUE(session.want_write());
EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id));
visitor.set_is_write_blocked(true);
int result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
EXPECT_TRUE(session.want_write());
visitor.set_is_write_blocked(false);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0));
EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0));
result = session.Send();
EXPECT_EQ(0, result);
absl::string_view serialized = visitor.data();
EXPECT_THAT(serialized,
testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(serialized,
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS,
SpdyFrameType::DATA}));
EXPECT_FALSE(session.want_write());
}
TEST(OgHttp2SessionTest, ServerConstruction) {
testing::StrictMock<MockHttp2Visitor> visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
OgHttp2Session session(visitor, options);
EXPECT_TRUE(session.want_read());
EXPECT_FALSE(session.want_write());
EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize);
EXPECT_TRUE(session.IsServerSession());
EXPECT_EQ(0, session.GetHighestReceivedStreamId());
}
TEST(OgHttp2SessionTest, ServerHandlesFrames) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
OgHttp2Session session(visitor, options);
EXPECT_EQ(0, session.GetHpackDecoderDynamicTableSize());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Headers(1,
{{":method", "POST"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
false)
.WindowUpdate(1, 2000)
.Data(1, "This is the request body.")
.Headers(3,
{{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}},
true)
.RstStream(3, Http2ErrorCode::CANCEL)
.Ping(47)
.Serialize();
testing::InSequence s;
const char* kSentinel1 = "arbitrary pointer 1";
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1000));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1))
.WillOnce(testing::InvokeWithoutArgs([&session, kSentinel1]() {
session.SetStreamUserData(1, const_cast<char*>(kSentinel1));
return true;
}));
EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(1, 2000));
EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 25));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body."));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "http"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/two"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::CANCEL));
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(47, false));
const int64_t result = session.ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_EQ(kSentinel1, session.GetStreamUserData(1));
EXPECT_GT(kInitialFlowControlWindowSize,
session.GetStreamReceiveWindowSize(1));
EXPECT_EQ(session.GetReceiveWindowSize(),
session.GetStreamReceiveWindowSize(1));
EXPECT_EQ(kInitialFlowControlWindowSize,
session.GetStreamReceiveWindowLimit(1));
EXPECT_GT(session.GetHpackDecoderDynamicTableSize(), 0);
const char* kSentinel3 = "another arbitrary pointer";
session.SetStreamUserData(3, const_cast<char*>(kSentinel3));
EXPECT_EQ(nullptr, session.GetStreamUserData(3));
EXPECT_EQ(session.GetRemoteWindowSize(),
kInitialFlowControlWindowSize + 1000);
EXPECT_EQ(3, session.GetHighestReceivedStreamId());
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0));
int send_result = session.Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames(
{spdy::SpdyFrameType::SETTINGS, spdy::SpdyFrameType::SETTINGS,
spdy::SpdyFrameType::PING, spdy::SpdyFrameType::PING}));
}
TEST(OgHttp2SessionTest, ServerEnqueuesSettingsBeforeOtherFrame) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
session.EnqueueFrame(std::make_unique<spdy::SpdyPingIR>(42));
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
}
TEST(OgHttp2SessionTest, ServerEnqueuesSettingsOnce) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
session.EnqueueFrame(std::make_unique<spdy::SpdySettingsIR>());
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
int result = session.Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(OgHttp2SessionTest, ServerSubmitResponse) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
OgHttp2Session session(visitor, options);
EXPECT_FALSE(session.want_write());
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}},
true)
.Serialize();
testing::InSequence s;
const char* kSentinel1 = "arbitrary pointer 1";
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1))
.WillOnce(testing::InvokeWithoutArgs([&session, kSentinel1]() {
session.SetStreamUserData(1, const_cast<char*>(kSentinel1));
return true;
}));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = session.ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
EXPECT_EQ(1, session.GetHighestReceivedStreamId());
EXPECT_EQ(0, session.GetHpackEncoderDynamicTableSize());
EXPECT_TRUE(session.want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL |
408 | cpp | google/quiche | chunked_buffer | quiche/http2/adapter/chunked_buffer.cc | quiche/http2/adapter/chunked_buffer_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_CHUNKED_BUFFER_H_
#define QUICHE_HTTP2_ADAPTER_CHUNKED_BUFFER_H_
#include <memory>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_circular_deque.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT ChunkedBuffer {
public:
ChunkedBuffer() = default;
void Append(absl::string_view data);
void Append(std::unique_ptr<char[]> data, size_t size);
absl::string_view GetPrefix() const;
std::vector<absl::string_view> Read() const;
void RemovePrefix(size_t n);
bool Empty() const;
private:
static constexpr size_t kDefaultChunkSize = 1024;
struct Chunk {
std::unique_ptr<char[]> data;
const size_t size;
absl::string_view live;
void RemovePrefix(size_t n);
void AppendSuffix(absl::string_view to_append);
bool Empty() const { return live.empty(); }
size_t LiveDataOffset() const { return live.data() - data.get(); }
size_t TailBytesFree() const {
return size - live.size() - LiveDataOffset();
}
};
size_t TailBytesFree() const;
void EnsureTailBytesFree(size_t n);
void TrimFirstChunk();
quiche::QuicheCircularDeque<Chunk> chunks_;
};
}
}
#endif
#include "quiche/http2/adapter/chunked_buffer.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
namespace http2 {
namespace adapter {
namespace {
constexpr size_t kKilobyte = 1024;
size_t RoundUpToNearestKilobyte(size_t n) {
return ((n - 1) | (kKilobyte - 1)) + 1;
}
}
void ChunkedBuffer::Append(absl::string_view data) {
const size_t to_copy = std::min(TailBytesFree(), data.size());
if (to_copy > 0) {
chunks_.back().AppendSuffix(data.substr(0, to_copy));
data.remove_prefix(to_copy);
}
EnsureTailBytesFree(data.size());
chunks_.back().AppendSuffix(data);
}
void ChunkedBuffer::Append(std::unique_ptr<char[]> data, size_t size) {
if (TailBytesFree() >= size) {
Chunk& c = chunks_.back();
c.AppendSuffix(absl::string_view(data.get(), size));
return;
}
while (!chunks_.empty() && chunks_.front().Empty()) {
chunks_.pop_front();
}
absl::string_view v = {data.get(), size};
chunks_.push_back({std::move(data), size, v});
}
absl::string_view ChunkedBuffer::GetPrefix() const {
if (chunks_.empty()) {
return "";
}
return chunks_.front().live;
}
std::vector<absl::string_view> ChunkedBuffer::Read() const {
std::vector<absl::string_view> result;
result.reserve(chunks_.size());
for (const Chunk& c : chunks_) {
result.push_back(c.live);
}
return result;
}
void ChunkedBuffer::RemovePrefix(size_t n) {
while (!Empty() && n > 0) {
Chunk& c = chunks_.front();
const size_t to_remove = std::min(n, c.live.size());
c.RemovePrefix(to_remove);
n -= to_remove;
if (c.Empty()) {
TrimFirstChunk();
}
}
}
bool ChunkedBuffer::Empty() const {
return chunks_.empty() ||
(chunks_.size() == 1 && chunks_.front().live.empty());
}
void ChunkedBuffer::Chunk::RemovePrefix(size_t n) {
QUICHE_DCHECK_GE(live.size(), n);
live.remove_prefix(n);
}
void ChunkedBuffer::Chunk::AppendSuffix(absl::string_view to_append) {
QUICHE_DCHECK_GE(TailBytesFree(), to_append.size());
if (live.empty()) {
std::copy(to_append.begin(), to_append.end(), data.get());
live = absl::string_view(data.get(), to_append.size());
} else {
std::copy(to_append.begin(), to_append.end(),
const_cast<char*>(live.data()) + live.size());
live = absl::string_view(live.data(), live.size() + to_append.size());
}
}
size_t ChunkedBuffer::TailBytesFree() const {
if (chunks_.empty()) {
return 0;
}
return chunks_.back().TailBytesFree();
}
void ChunkedBuffer::EnsureTailBytesFree(size_t n) {
if (TailBytesFree() >= n) {
return;
}
const size_t to_allocate = RoundUpToNearestKilobyte(n);
auto data = std::unique_ptr<char[]>(new char[to_allocate]);
chunks_.push_back({std::move(data), to_allocate, ""});
}
void ChunkedBuffer::TrimFirstChunk() {
if (chunks_.empty() ||
(chunks_.size() == 1 && chunks_.front().size == kDefaultChunkSize)) {
return;
}
chunks_.pop_front();
}
}
} | #include "quiche/http2/adapter/chunked_buffer.h"
#include <algorithm>
#include <initializer_list>
#include <memory>
#include <utility>
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace {
constexpr absl::string_view kLoremIpsum =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
"tempor incididunt ut labore et dolore magna aliqua.";
struct DataAndSize {
std::unique_ptr<char[]> data;
size_t size;
};
DataAndSize MakeDataAndSize(absl::string_view source) {
auto data = std::unique_ptr<char[]>(new char[source.size()]);
std::copy(source.begin(), source.end(), data.get());
return {std::move(data), source.size()};
}
TEST(ChunkedBufferTest, Empty) {
ChunkedBuffer buffer;
EXPECT_TRUE(buffer.Empty());
buffer.Append("some data");
EXPECT_FALSE(buffer.Empty());
buffer.RemovePrefix(9);
EXPECT_TRUE(buffer.Empty());
}
TEST(ChunkedBufferTest, ReusedAfterEmptied) {
ChunkedBuffer buffer;
buffer.Append("some data");
buffer.RemovePrefix(9);
buffer.Append("different data");
EXPECT_EQ("different data", buffer.GetPrefix());
}
TEST(ChunkedBufferTest, LargeAppendAfterEmptied) {
ChunkedBuffer buffer;
buffer.Append("some data");
EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("some data"));
buffer.RemovePrefix(9);
auto more_data =
MakeDataAndSize(absl::StrCat("different data", std::string(2048, 'x')));
buffer.Append(std::move(more_data.data), more_data.size);
EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("different data"));
}
TEST(ChunkedBufferTest, LargeAppends) {
ChunkedBuffer buffer;
buffer.Append(std::string(500, 'a'));
buffer.Append(std::string(2000, 'b'));
buffer.Append(std::string(10, 'c'));
auto more_data = MakeDataAndSize(std::string(4490, 'd'));
buffer.Append(std::move(more_data.data), more_data.size);
EXPECT_EQ(500 + 2000 + 10 + 4490, absl::StrJoin(buffer.Read(), "").size());
}
TEST(ChunkedBufferTest, RemovePartialPrefix) {
ChunkedBuffer buffer;
auto data_and_size = MakeDataAndSize(kLoremIpsum);
buffer.Append(std::move(data_and_size.data), data_and_size.size);
buffer.RemovePrefix(6);
EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("ipsum"));
buffer.RemovePrefix(20);
EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith(", consectetur"));
buffer.Append(" Anday igpay atinlay!");
const std::initializer_list<absl::string_view> parts = {
kLoremIpsum.substr(26), " Anday igpay atinlay!"};
EXPECT_EQ(absl::StrJoin(parts, ""), absl::StrJoin(buffer.Read(), ""));
}
TEST(ChunkedBufferTest, DifferentAppends) {
ChunkedBuffer buffer;
buffer.Append("Lorem ipsum");
auto more_data = MakeDataAndSize(" dolor sit amet, ");
buffer.Append(std::move(more_data.data), more_data.size);
buffer.Append("consectetur adipiscing elit, ");
more_data = MakeDataAndSize("sed do eiusmod tempor incididunt ut ");
buffer.Append(std::move(more_data.data), more_data.size);
buffer.Append("labore et dolore magna aliqua.");
EXPECT_EQ(kLoremIpsum, absl::StrJoin(buffer.Read(), ""));
buffer.RemovePrefix(kLoremIpsum.size());
EXPECT_TRUE(buffer.Empty());
}
}
}
} |
409 | cpp | google/quiche | header_validator | quiche/http2/adapter/header_validator.cc | quiche/http2/adapter/header_validator_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_HEADER_VALIDATOR_H_
#define QUICHE_HTTP2_ADAPTER_HEADER_VALIDATOR_H_
#include <bitset>
#include <optional>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/header_validator_base.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT HeaderValidator : public HeaderValidatorBase {
public:
HeaderValidator() = default;
void StartHeaderBlock() override;
HeaderStatus ValidateSingleHeader(absl::string_view key,
absl::string_view value) override;
bool FinishHeaderBlock(HeaderType type) override;
static bool IsValidHeaderName(absl::string_view name);
static bool IsValidHeaderValue(absl::string_view value,
ObsTextOption ops_text_option);
static bool IsValidAuthority(absl::string_view authority);
static bool IsValidPath(absl::string_view path, bool allow_fragment);
private:
enum ContentLengthStatus {
CONTENT_LENGTH_OK,
CONTENT_LENGTH_SKIP,
CONTENT_LENGTH_ERROR,
};
ContentLengthStatus HandleContentLength(absl::string_view value);
bool ValidateAndSetAuthority(absl::string_view authority);
enum PseudoHeaderTag {
TAG_AUTHORITY = 0,
TAG_METHOD,
TAG_PATH,
TAG_PROTOCOL,
TAG_SCHEME,
TAG_STATUS,
TAG_UNKNOWN_EXTRA,
TAG_ENUM_SIZE,
};
void RecordPseudoHeader(PseudoHeaderTag tag);
using PseudoHeaderTagSet = std::bitset<TAG_ENUM_SIZE>;
enum PseudoHeaderState {
STATE_AUTHORITY_IS_NONEMPTY,
STATE_METHOD_IS_OPTIONS,
STATE_METHOD_IS_CONNECT,
STATE_PATH_IS_EMPTY,
STATE_PATH_IS_STAR,
STATE_PATH_INITIAL_SLASH,
STATE_ENUM_SIZE,
};
using PseudoHeaderStateSet = std::bitset<STATE_ENUM_SIZE>;
static bool ValidateRequestHeaders(
const PseudoHeaderTagSet& pseudo_headers,
const PseudoHeaderStateSet& pseudo_header_state,
bool allow_extended_connect);
static bool ValidateRequestTrailers(const PseudoHeaderTagSet& pseudo_headers);
static bool ValidateResponseHeaders(const PseudoHeaderTagSet& pseudo_headers);
static bool ValidateResponseTrailers(
const PseudoHeaderTagSet& pseudo_headers);
PseudoHeaderTagSet pseudo_headers_;
PseudoHeaderStateSet pseudo_header_state_;
std::string authority_;
};
}
}
#endif
#include "quiche/http2/adapter/header_validator.h"
#include <array>
#include <bitset>
#include <string>
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "quiche/http2/adapter/header_validator_base.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace adapter {
namespace {
constexpr absl::string_view kHttpTokenChars =
"!#$%&'*+-.^_`|~0123456789"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
constexpr absl::string_view kHttp2HeaderNameAllowedChars =
"!#$%&'*+-.0123456789"
"^_`abcdefghijklmnopqrstuvwxyz|~";
constexpr absl::string_view kHttp2HeaderValueAllowedChars =
"\t "
"!\"#$%&'()*+,-./"
"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
"abcdefghijklmnopqrstuvwxyz{|}~";
constexpr absl::string_view kHttp2StatusValueAllowedChars = "0123456789";
constexpr absl::string_view kValidAuthorityChars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()["
"]*+,;=:";
constexpr absl::string_view kValidPathChars =
"/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()"
"*+,;=:@?";
constexpr absl::string_view kValidPathCharsWithFragment =
"/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()"
"*+,;=:@?#";
using CharMap = std::array<bool, 256>;
constexpr CharMap BuildValidCharMap(absl::string_view valid_chars) {
CharMap map = {};
for (char c : valid_chars) {
map[static_cast<uint8_t>(c)] = true;
}
return map;
}
constexpr CharMap AllowObsText(CharMap map) {
for (uint8_t c = 0xff; c >= 0x80; --c) {
map[c] = true;
}
return map;
}
bool AllCharsInMap(absl::string_view str, const CharMap& map) {
for (char c : str) {
if (!map[static_cast<uint8_t>(c)]) {
return false;
}
}
return true;
}
bool IsValidStatus(absl::string_view status) {
static constexpr CharMap valid_chars =
BuildValidCharMap(kHttp2StatusValueAllowedChars);
return AllCharsInMap(status, valid_chars);
}
bool IsValidMethod(absl::string_view method) {
static constexpr CharMap valid_chars = BuildValidCharMap(kHttpTokenChars);
return AllCharsInMap(method, valid_chars);
}
}
void HeaderValidator::StartHeaderBlock() {
HeaderValidatorBase::StartHeaderBlock();
pseudo_headers_.reset();
pseudo_header_state_.reset();
authority_.clear();
}
void HeaderValidator::RecordPseudoHeader(PseudoHeaderTag tag) {
if (pseudo_headers_[tag]) {
pseudo_headers_[TAG_UNKNOWN_EXTRA] = true;
} else {
pseudo_headers_[tag] = true;
}
}
HeaderValidator::HeaderStatus HeaderValidator::ValidateSingleHeader(
absl::string_view key, absl::string_view value) {
if (key.empty()) {
return HEADER_FIELD_INVALID;
}
if (max_field_size_.has_value() &&
key.size() + value.size() > *max_field_size_) {
QUICHE_VLOG(2) << "Header field size is " << key.size() + value.size()
<< ", exceeds max size of " << *max_field_size_;
return HEADER_FIELD_TOO_LONG;
}
if (key[0] == ':') {
key.remove_prefix(1);
if (key == "status") {
if (value.size() != 3 || !IsValidStatus(value)) {
QUICHE_VLOG(2) << "malformed status value: [" << absl::CEscape(value)
<< "]";
return HEADER_FIELD_INVALID;
}
if (value == "101") {
return HEADER_FIELD_INVALID;
}
status_ = std::string(value);
RecordPseudoHeader(TAG_STATUS);
} else if (key == "method") {
if (value == "OPTIONS") {
pseudo_header_state_[STATE_METHOD_IS_OPTIONS] = true;
} else if (value == "CONNECT") {
pseudo_header_state_[STATE_METHOD_IS_CONNECT] = true;
} else if (!IsValidMethod(value)) {
return HEADER_FIELD_INVALID;
}
RecordPseudoHeader(TAG_METHOD);
} else if (key == "authority") {
if (!ValidateAndSetAuthority(value)) {
return HEADER_FIELD_INVALID;
}
RecordPseudoHeader(TAG_AUTHORITY);
} else if (key == "path") {
if (value == "*") {
pseudo_header_state_[STATE_PATH_IS_STAR] = true;
} else if (value.empty()) {
pseudo_header_state_[STATE_PATH_IS_EMPTY] = true;
return HEADER_FIELD_INVALID;
} else if (validate_path_ &&
!IsValidPath(value, allow_fragment_in_path_)) {
return HEADER_FIELD_INVALID;
}
if (value[0] == '/') {
pseudo_header_state_[STATE_PATH_INITIAL_SLASH] = true;
}
RecordPseudoHeader(TAG_PATH);
} else if (key == "protocol") {
RecordPseudoHeader(TAG_PROTOCOL);
} else if (key == "scheme") {
RecordPseudoHeader(TAG_SCHEME);
} else {
pseudo_headers_[TAG_UNKNOWN_EXTRA] = true;
if (!IsValidHeaderName(key)) {
QUICHE_VLOG(2) << "invalid chars in header name: ["
<< absl::CEscape(key) << "]";
return HEADER_FIELD_INVALID;
}
}
if (!IsValidHeaderValue(value, obs_text_option_)) {
QUICHE_VLOG(2) << "invalid chars in header value: ["
<< absl::CEscape(value) << "]";
return HEADER_FIELD_INVALID;
}
} else {
std::string lowercase_key;
if (allow_uppercase_in_header_names_) {
lowercase_key = absl::AsciiStrToLower(key);
key = lowercase_key;
}
if (!IsValidHeaderName(key)) {
QUICHE_VLOG(2) << "invalid chars in header name: [" << absl::CEscape(key)
<< "]";
return HEADER_FIELD_INVALID;
}
if (!IsValidHeaderValue(value, obs_text_option_)) {
QUICHE_VLOG(2) << "invalid chars in header value: ["
<< absl::CEscape(value) << "]";
return HEADER_FIELD_INVALID;
}
if (key == "host") {
if (pseudo_headers_[TAG_STATUS]) {
} else {
if (!ValidateAndSetAuthority(value)) {
return HEADER_FIELD_INVALID;
}
pseudo_headers_[TAG_AUTHORITY] = true;
}
} else if (key == "content-length") {
const ContentLengthStatus status = HandleContentLength(value);
switch (status) {
case CONTENT_LENGTH_ERROR:
return HEADER_FIELD_INVALID;
case CONTENT_LENGTH_SKIP:
return HEADER_SKIP;
case CONTENT_LENGTH_OK:
return HEADER_OK;
default:
return HEADER_FIELD_INVALID;
}
} else if (key == "te" && value != "trailers") {
return HEADER_FIELD_INVALID;
} else if (key == "upgrade" || GetInvalidHttp2HeaderSet().contains(key)) {
return HEADER_FIELD_INVALID;
}
}
return HEADER_OK;
}
bool HeaderValidator::FinishHeaderBlock(HeaderType type) {
switch (type) {
case HeaderType::REQUEST:
return ValidateRequestHeaders(pseudo_headers_, pseudo_header_state_,
allow_extended_connect_);
case HeaderType::REQUEST_TRAILER:
return ValidateRequestTrailers(pseudo_headers_);
case HeaderType::RESPONSE_100:
case HeaderType::RESPONSE:
return ValidateResponseHeaders(pseudo_headers_);
case HeaderType::RESPONSE_TRAILER:
return ValidateResponseTrailers(pseudo_headers_);
}
return false;
}
bool HeaderValidator::IsValidHeaderName(absl::string_view name) {
static constexpr CharMap valid_chars =
BuildValidCharMap(kHttp2HeaderNameAllowedChars);
return AllCharsInMap(name, valid_chars);
}
bool HeaderValidator::IsValidHeaderValue(absl::string_view value,
ObsTextOption option) {
static constexpr CharMap valid_chars =
BuildValidCharMap(kHttp2HeaderValueAllowedChars);
static constexpr CharMap valid_chars_with_obs_text =
AllowObsText(BuildValidCharMap(kHttp2HeaderValueAllowedChars));
return AllCharsInMap(value, option == ObsTextOption::kAllow
? valid_chars_with_obs_text
: valid_chars);
}
bool HeaderValidator::IsValidAuthority(absl::string_view authority) {
static constexpr CharMap valid_chars =
BuildValidCharMap(kValidAuthorityChars);
return AllCharsInMap(authority, valid_chars);
}
bool HeaderValidator::IsValidPath(absl::string_view path, bool allow_fragment) {
static constexpr CharMap valid_chars = BuildValidCharMap(kValidPathChars);
static constexpr CharMap valid_chars_with_fragment =
BuildValidCharMap(kValidPathCharsWithFragment);
if (allow_fragment) {
return AllCharsInMap(path, valid_chars_with_fragment);
} else {
return AllCharsInMap(path, valid_chars);
}
}
HeaderValidator::ContentLengthStatus HeaderValidator::HandleContentLength(
absl::string_view value) {
if (value.empty()) {
return CONTENT_LENGTH_ERROR;
}
if (status_ == "204" && value != "0") {
return CONTENT_LENGTH_ERROR;
}
if (!status_.empty() && status_[0] == '1' && value != "0") {
return CONTENT_LENGTH_ERROR;
}
size_t content_length = 0;
const bool valid = absl::SimpleAtoi(value, &content_length);
if (!valid) {
return CONTENT_LENGTH_ERROR;
}
if (content_length_.has_value()) {
return content_length == *content_length_ ? CONTENT_LENGTH_SKIP
: CONTENT_LENGTH_ERROR;
}
content_length_ = content_length;
return CONTENT_LENGTH_OK;
}
bool HeaderValidator::ValidateAndSetAuthority(absl::string_view authority) {
if (!IsValidAuthority(authority)) {
return false;
}
if (!allow_different_host_and_authority_ && pseudo_headers_[TAG_AUTHORITY] &&
authority != authority_) {
return false;
}
if (!authority.empty()) {
pseudo_header_state_[STATE_AUTHORITY_IS_NONEMPTY] = true;
if (authority_.empty()) {
authority_ = authority;
} else {
absl::StrAppend(&authority_, ", ", authority);
}
}
return true;
}
bool HeaderValidator::ValidateRequestHeaders(
const PseudoHeaderTagSet& pseudo_headers,
const PseudoHeaderStateSet& pseudo_header_state,
bool allow_extended_connect) {
QUICHE_VLOG(2) << "Request pseudo-headers: [" << pseudo_headers
<< "], pseudo_header_state: [" << pseudo_header_state
<< "], allow_extended_connect: " << allow_extended_connect;
if (pseudo_header_state[STATE_METHOD_IS_CONNECT]) {
if (allow_extended_connect) {
static const auto* kExtendedConnectHeaders =
new PseudoHeaderTagSet(0b0011111);
if (pseudo_headers == *kExtendedConnectHeaders) {
return true;
}
}
static const auto* kConnectHeaders = new PseudoHeaderTagSet(0b0000011);
return pseudo_header_state[STATE_AUTHORITY_IS_NONEMPTY] &&
pseudo_headers == *kConnectHeaders;
}
if (pseudo_header_state[STATE_PATH_IS_EMPTY]) {
return false;
}
if (pseudo_header_state[STATE_PATH_IS_STAR]) {
if (!pseudo_header_state[STATE_METHOD_IS_OPTIONS]) {
return false;
}
} else if (!pseudo_header_state[STATE_PATH_INITIAL_SLASH]) {
return false;
}
static const auto* kRequiredHeaders = new PseudoHeaderTagSet(0b0010111);
return pseudo_headers == *kRequiredHeaders;
}
bool HeaderValidator::ValidateRequestTrailers(
const PseudoHeaderTagSet& pseudo_headers) {
return pseudo_headers.none();
}
bool HeaderValidator::ValidateResponseHeaders(
const PseudoHeaderTagSet& pseudo_headers) {
static const auto* kRequiredHeaders = new PseudoHeaderTagSet(0b0100000);
return pseudo_headers == *kRequiredHeaders;
}
bool HeaderValidator::ValidateResponseTrailers(
const PseudoHeaderTagSet& pseudo_headers) {
return pseudo_headers.none();
}
}
} | #include "quiche/http2/adapter/header_validator.h"
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
using ::testing::Optional;
using Header = std::pair<absl::string_view, absl::string_view>;
constexpr Header kSampleRequestPseudoheaders[] = {{":authority", "www.foo.com"},
{":method", "GET"},
{":path", "/foo"},
{":scheme", "https"}};
TEST(HeaderValidatorTest, HeaderNameEmpty) {
HeaderValidator v;
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("", "value");
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
TEST(HeaderValidatorTest, HeaderValueEmpty) {
HeaderValidator v;
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", "");
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
TEST(HeaderValidatorTest, ExceedsMaxSize) {
HeaderValidator v;
v.SetMaxFieldSize(64u);
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("name", "value");
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
status = v.ValidateSingleHeader(
"name2",
"Antidisestablishmentariansism is supercalifragilisticexpialodocious.");
EXPECT_EQ(HeaderValidator::HEADER_FIELD_TOO_LONG, status);
}
TEST(HeaderValidatorTest, NameHasInvalidChar) {
HeaderValidator v;
for (const bool is_pseudo_header : {true, false}) {
for (const char* c : {"!", "3", "a", "_", "|", "~"}) {
const std::string name = is_pseudo_header ? absl::StrCat(":met", c, "hod")
: absl::StrCat("na", c, "me");
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader(name, "value");
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
for (const char* c : {"\\", "<", ";", "[", "=", " ", "\r", "\n", ",", "\"",
"\x1F", "\x91"}) {
const std::string name = is_pseudo_header ? absl::StrCat(":met", c, "hod")
: absl::StrCat("na", c, "me");
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader(name, "value");
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status)
<< "with name [" << name << "]";
}
{
const absl::string_view name = is_pseudo_header
? absl::string_view(":met\0hod", 8)
: absl::string_view("na\0me", 5);
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader(name, "value");
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
const std::string uc_name = is_pseudo_header ? ":Method" : "Name";
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader(uc_name, "value");
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
}
TEST(HeaderValidatorTest, ValueHasInvalidChar) {
HeaderValidator v;
for (const char* c :
{"!", "3", "a", "_", "|", "~", "\\", "<", ";", "[", "=", "A", "\t"}) {
const std::string value = absl::StrCat("val", c, "ue");
EXPECT_TRUE(
HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow));
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("name", value);
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
for (const char* c : {"\r", "\n"}) {
const std::string value = absl::StrCat("val", c, "ue");
EXPECT_FALSE(
HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow));
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("name", value);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
{
const std::string value("val\0ue", 6);
EXPECT_FALSE(
HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow));
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("name", value);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
{
const std::string obs_text_value = "val\xa9ue";
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("name", obs_text_value));
v.SetObsTextOption(ObsTextOption::kDisallow);
EXPECT_FALSE(HeaderValidator::IsValidHeaderValue(obs_text_value,
ObsTextOption::kDisallow));
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("name", obs_text_value));
v.SetObsTextOption(ObsTextOption::kAllow);
EXPECT_TRUE(HeaderValidator::IsValidHeaderValue(obs_text_value,
ObsTextOption::kAllow));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("name", obs_text_value));
}
}
TEST(HeaderValidatorTest, StatusHasInvalidChar) {
HeaderValidator v;
for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) {
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(":status", "bar"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(":status", "10"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(":status", "9000"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "400"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
}
}
TEST(HeaderValidatorTest, AuthorityHasInvalidChar) {
for (absl::string_view key : {":authority", "host"}) {
for (const absl::string_view c : {"1", "-", "!", ":", "+", "=", ","}) {
const std::string value = absl::StrCat("ho", c, "st.example.com");
EXPECT_TRUE(HeaderValidator::IsValidAuthority(value));
HeaderValidator v;
v.StartHeaderBlock();
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value);
EXPECT_EQ(HeaderValidator::HEADER_OK, status)
<< " with name [" << key << "] and value [" << value << "]";
}
for (const absl::string_view c : {"\r", "\n", "|", "\\", "`"}) {
const std::string value = absl::StrCat("ho", c, "st.example.com");
EXPECT_FALSE(HeaderValidator::IsValidAuthority(value));
HeaderValidator v;
v.StartHeaderBlock();
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status);
}
{
const std::string value = "123.45.67.89";
EXPECT_TRUE(HeaderValidator::IsValidAuthority(value));
HeaderValidator v;
v.StartHeaderBlock();
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value);
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
{
const std::string value1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
EXPECT_TRUE(HeaderValidator::IsValidAuthority(value1));
HeaderValidator v;
v.StartHeaderBlock();
HeaderValidator::HeaderStatus status =
v.ValidateSingleHeader(key, value1);
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
const std::string value2 = "[::1]:80";
EXPECT_TRUE(HeaderValidator::IsValidAuthority(value2));
HeaderValidator v2;
v2.StartHeaderBlock();
status = v2.ValidateSingleHeader(key, value2);
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
{
EXPECT_TRUE(HeaderValidator::IsValidAuthority(""));
HeaderValidator v;
v.StartHeaderBlock();
HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, "");
EXPECT_EQ(HeaderValidator::HEADER_OK, status);
}
}
}
TEST(HeaderValidatorTest, RequestHostAndAuthority) {
HeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "www.foo.com"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("host", "www.bar.com"));
}
TEST(HeaderValidatorTest, RequestHostAndAuthorityLax) {
HeaderValidator v;
v.SetAllowDifferentHostAndAuthority();
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "www.bar.com"));
}
TEST(HeaderValidatorTest, MethodHasInvalidChar) {
HeaderValidator v;
v.StartHeaderBlock();
std::vector<absl::string_view> bad_methods = {
"In[]valid{}", "co,mma", "spac e", "a@t", "equals=",
"question?mark", "co:lon", "semi;colon", "sla/sh", "back\\slash",
};
std::vector<absl::string_view> good_methods = {
"lowercase", "MiXeDcAsE", "NONCANONICAL", "HASH#",
"under_score", "PI|PE", "Tilde~", "quote'",
};
for (absl::string_view value : bad_methods) {
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(":method", value));
}
for (absl::string_view value : good_methods) {
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", value));
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":method") {
continue;
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
}
TEST(HeaderValidatorTest, RequestPseudoHeaders) {
HeaderValidator v;
for (Header to_skip : kSampleRequestPseudoheaders) {
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add != to_skip) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":extra", "blah"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
for (Header to_repeat : kSampleRequestPseudoheaders) {
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
if (to_add == to_repeat) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
}
TEST(HeaderValidatorTest, ConnectHeaders) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", "CONNECT"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", "CONNECT"));
EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":path", "/"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":authority", ""));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", "CONNECT"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", "CONNECT"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.SetAllowExtendedConnect();
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":method", "CONNECT"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(HeaderValidatorTest, WebsocketPseudoHeaders) {
HeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.SetAllowExtendedConnect();
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":method") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "CONNECT"));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(HeaderValidatorTest, AsteriskPathPseudoHeader) {
HeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "*"));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "*"));
} else if (to_add.first == ":method") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "OPTIONS"));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(HeaderValidatorTest, InvalidPathPseudoHeader) {
HeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(to_add.first, ""));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.SetValidatePath();
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "shawarma"));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST));
for (const absl::string_view c :
{"/", "?", "_", "'", "9", "&", "(", "@", ":"}) {
const std::string value = absl::StrCat("/shawa", c, "rma");
HeaderValidator validator;
validator.SetValidatePath();
validator.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
validator.ValidateSingleHeader(to_add.first, value))
<< "Problematic char: [" << c << "]";
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
validator.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(validator.FinishHeaderBlock(HeaderType::REQUEST));
}
for (const absl::string_view c : {"[", "<", "}", "`", "\\", " ", "\t", "#"}) {
const std::string value = absl::StrCat("/shawa", c, "rma");
HeaderValidator validator;
validator.SetValidatePath();
validator.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
validator.ValidateSingleHeader(to_add.first, value));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
validator.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_FALSE(validator.FinishHeaderBlock(HeaderType::REQUEST));
}
{
HeaderValidator validator;
validator.SetValidatePath();
validator.SetAllowFragmentInPath();
validator.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(HeaderValidator::HEADER_OK,
validator.ValidateSingleHeader(to_add.first, "/shawa#rma"));
} else {
EXPECT_EQ(HeaderValidator::HEADER_OK,
validator.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(validator.FinishHeaderBlock(HeaderType::REQUEST));
}
}
TEST(HeaderValidatorTest, ResponsePseudoHeaders) {
HeaderValidator v;
for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) {
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
EXPECT_EQ("199", v.status_header());
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "299"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":extra", "blorp"));
EXPECT_FALSE(v.FinishHeaderBlock(type));
}
}
TEST(HeaderValidatorTest, ResponseWithHost) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "myserver.com"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(HeaderValidatorTest, Response204) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(HeaderValidatorTest, ResponseWithMultipleIdenticalContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "13"));
EXPECT_EQ(HeaderValidator::HEADER_SKIP,
v.ValidateSingleHeader("content-length", "13"));
}
TEST(HeaderValidatorTest, ResponseWithMultipleDifferingContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "13"));
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", "17"));
}
TEST(HeaderValidatorTest, Response204WithContentLengthZero) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "0"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(HeaderValidatorTest, Response204WithContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", "1"));
}
TEST(HeaderValidatorTest, Response100) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(HeaderValidatorTest, Response100WithContentLengthZero) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "0"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(HeaderValidatorTest, Response100WithContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", "1"));
}
TEST(HeaderValidatorTest, ResponseTrailerPseudoHeaders) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar"));
EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER));
}
TEST(HeaderValidatorTest, ValidContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "41"));
EXPECT_THAT(v.content_length(), Optional(41));
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "42"));
EXPECT_THAT(v.content_length(), Optional(42));
}
TEST(HeaderValidatorTest, InvalidContentLength) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", ""));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", "nan"));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("content-length", "-42"));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "42"));
EXPECT_THAT(v.content_length(), Optional(42));
}
TEST(HeaderValidatorTest, TeHeader) {
HeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("te", "trailers"));
v.StartHeaderBlock();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("te", "trailers, deflate"));
}
TEST(HeaderValidatorTest, ConnectionSpecificHeaders) {
const std::vector<Header> connection_headers = {
{"connection", "keep-alive"}, {"proxy-connection", "keep-alive"},
{"keep-alive", "timeout=42"}, {"transfer-encoding", "chunked"},
{"upgrade", "h2c"},
};
for (const auto& [connection_key, connection_value] : connection_headers) {
HeaderValidator v;
v.StartHeaderBlock();
for (const auto& [sample_key, sample_value] : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(sample_key, sample_value));
}
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(connection_key, connection_value));
}
}
TEST(HeaderValidatorTest, MixedCaseHeaderName) {
HeaderValidator v;
v.SetAllowUppercaseInHeaderNames();
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("MixedCaseName", "value"));
}
TEST(HeaderValidatorTest, MixedCasePseudoHeader) {
HeaderValidator v;
v.SetAllowUppercaseInHeaderNames();
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader(":PATH", "/"));
}
TEST(HeaderValidatorTest, MixedCaseHost) {
HeaderValidator v;
v.SetAllowUppercaseInHeaderNames();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID,
v.ValidateSingleHeader("Host", "www.bar.com"));
}
TEST(HeaderValidatorTest, MixedCaseContentLength) {
HeaderValidator v;
v.SetAllowUppercaseInHeaderNames();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(HeaderValidator::HEADER_OK,
v.ValidateSingleHeader("Content-Length", "42"));
EXPECT_THAT(v.content_length(), Optional(42));
}
}
}
} |
410 | cpp | google/quiche | noop_header_validator | quiche/http2/adapter/noop_header_validator.cc | quiche/http2/adapter/noop_header_validator_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_NOOP_HEADER_VALIDATOR_H_
#define QUICHE_HTTP2_ADAPTER_NOOP_HEADER_VALIDATOR_H_
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/header_validator_base.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT NoopHeaderValidator : public HeaderValidatorBase {
public:
NoopHeaderValidator() = default;
HeaderStatus ValidateSingleHeader(absl::string_view key,
absl::string_view value) override;
bool FinishHeaderBlock(HeaderType type) override;
};
}
}
#endif
#include "quiche/http2/adapter/noop_header_validator.h"
#include <string>
#include "absl/strings/escaping.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace adapter {
HeaderValidatorBase::HeaderStatus NoopHeaderValidator::ValidateSingleHeader(
absl::string_view key, absl::string_view value) {
if (key == ":status") {
status_ = std::string(value);
}
return HEADER_OK;
}
bool NoopHeaderValidator::FinishHeaderBlock(HeaderType ) {
return true;
}
}
} | #include "quiche/http2/adapter/noop_header_validator.h"
#include <limits>
#include <optional>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
using ::testing::Optional;
using Header = std::pair<absl::string_view, absl::string_view>;
constexpr Header kSampleRequestPseudoheaders[] = {{":authority", "www.foo.com"},
{":method", "GET"},
{":path", "/foo"},
{":scheme", "https"}};
TEST(NoopHeaderValidatorTest, HeaderNameEmpty) {
NoopHeaderValidator v;
NoopHeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("", "value");
EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status);
}
TEST(NoopHeaderValidatorTest, HeaderValueEmpty) {
NoopHeaderValidator v;
NoopHeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", "");
EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status);
}
TEST(NoopHeaderValidatorTest, ExceedsMaxSize) {
NoopHeaderValidator v;
v.SetMaxFieldSize(64u);
NoopHeaderValidator::HeaderStatus status =
v.ValidateSingleHeader("name", "value");
EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status);
status = v.ValidateSingleHeader(
"name2",
"Antidisestablishmentariansism is supercalifragilisticexpialodocious.");
EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status);
}
TEST(NoopHeaderValidatorTest, AnyNameCharIsValid) {
NoopHeaderValidator v;
char pseudo_name[] = ":met hod";
char name[] = "na me";
for (int i = std::numeric_limits<char>::min();
i < std::numeric_limits<char>::max(); ++i) {
char c = static_cast<char>(i);
pseudo_name[3] = c;
auto sv = absl::string_view(pseudo_name, 8);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(sv, "value"));
name[2] = c;
sv = absl::string_view(name, 5);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(sv, "value"));
}
}
TEST(NoopHeaderValidatorTest, AnyValueCharIsValid) {
NoopHeaderValidator v;
char value[] = "val ue";
for (int i = std::numeric_limits<char>::min();
i < std::numeric_limits<char>::max(); ++i) {
char c = static_cast<char>(i);
value[3] = c;
auto sv = absl::string_view(value, 6);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("name", sv));
}
}
TEST(NoopHeaderValidatorTest, AnyStatusIsValid) {
NoopHeaderValidator v;
for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) {
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "bar"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "10"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "9000"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "400"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
}
}
TEST(NoopHeaderValidatorTest, AnyAuthorityCharIsValid) {
char value[] = "ho st.example.com";
for (int i = std::numeric_limits<char>::min();
i < std::numeric_limits<char>::max(); ++i) {
char c = static_cast<char>(i);
value[2] = c;
auto sv = absl::string_view(value, 17);
for (absl::string_view key : {":authority", "host"}) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(key, sv));
}
}
}
TEST(NoopHeaderValidatorTest, RequestHostAndAuthority) {
NoopHeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "www.foo.com"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "www.bar.com"));
}
TEST(NoopHeaderValidatorTest, RequestPseudoHeaders) {
NoopHeaderValidator v;
for (Header to_skip : kSampleRequestPseudoheaders) {
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add != to_skip) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":extra", "blah"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
for (Header to_repeat : kSampleRequestPseudoheaders) {
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
if (to_add == to_repeat) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
}
TEST(NoopHeaderValidatorTest, WebsocketPseudoHeaders) {
NoopHeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.SetAllowExtendedConnect();
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":method") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "CONNECT"));
} else {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":protocol", "websocket"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(NoopHeaderValidatorTest, AsteriskPathPseudoHeader) {
NoopHeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "*"));
} else {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "*"));
} else if (to_add.first == ":method") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "OPTIONS"));
} else {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(NoopHeaderValidatorTest, InvalidPathPseudoHeader) {
NoopHeaderValidator v;
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, ""));
} else {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
v.StartHeaderBlock();
for (Header to_add : kSampleRequestPseudoheaders) {
if (to_add.first == ":path") {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, "shawarma"));
} else {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(to_add.first, to_add.second));
}
}
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST));
}
TEST(NoopHeaderValidatorTest, ResponsePseudoHeaders) {
NoopHeaderValidator v;
for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) {
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("foo", "bar"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
EXPECT_EQ("199", v.status_header());
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "299"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "199"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":extra", "blorp"));
EXPECT_TRUE(v.FinishHeaderBlock(type));
}
}
TEST(NoopHeaderValidatorTest, ResponseWithHost) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("host", "myserver.com"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(NoopHeaderValidatorTest, Response204) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(NoopHeaderValidatorTest, ResponseWithMultipleIdenticalContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "13"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "13"));
}
TEST(NoopHeaderValidatorTest, ResponseWithMultipleDifferingContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "13"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "17"));
}
TEST(NoopHeaderValidatorTest, Response204WithContentLengthZero) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "0"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(NoopHeaderValidatorTest, Response204WithContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "204"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "1"));
}
TEST(NoopHeaderValidatorTest, Response100) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(NoopHeaderValidatorTest, Response100WithContentLengthZero) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "0"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE));
}
TEST(NoopHeaderValidatorTest, Response100WithContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "100"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("x-content", "is not present"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "1"));
}
TEST(NoopHeaderValidatorTest, ResponseTrailerPseudoHeaders) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("foo", "bar"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(":status", "200"));
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("foo", "bar"));
EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER));
}
TEST(NoopHeaderValidatorTest, ValidContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "41"));
EXPECT_EQ(v.content_length(), std::nullopt);
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "42"));
EXPECT_EQ(v.content_length(), std::nullopt);
}
TEST(NoopHeaderValidatorTest, InvalidContentLength) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", ""));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "nan"));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "-42"));
EXPECT_EQ(v.content_length(), std::nullopt);
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("content-length", "42"));
EXPECT_EQ(v.content_length(), std::nullopt);
}
TEST(NoopHeaderValidatorTest, TeHeader) {
NoopHeaderValidator v;
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("te", "trailers"));
v.StartHeaderBlock();
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader("te", "trailers, deflate"));
}
TEST(NoopHeaderValidatorTest, ConnectionSpecificHeaders) {
const std::vector<Header> connection_headers = {
{"connection", "keep-alive"}, {"proxy-connection", "keep-alive"},
{"keep-alive", "timeout=42"}, {"transfer-encoding", "chunked"},
{"upgrade", "h2c"},
};
for (const auto& [connection_key, connection_value] : connection_headers) {
NoopHeaderValidator v;
v.StartHeaderBlock();
for (const auto& [sample_key, sample_value] : kSampleRequestPseudoheaders) {
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(sample_key, sample_value));
}
EXPECT_EQ(NoopHeaderValidator::HEADER_OK,
v.ValidateSingleHeader(connection_key, connection_value));
}
}
}
}
} |
411 | cpp | google/quiche | nghttp2_adapter | quiche/http2/adapter/nghttp2_adapter.cc | quiche/http2/adapter/nghttp2_adapter_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_NGHTTP2_ADAPTER_H_
#define QUICHE_HTTP2_ADAPTER_NGHTTP2_ADAPTER_H_
#include <cstdint>
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "quiche/http2/adapter/http2_adapter.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/nghttp2_session.h"
#include "quiche/http2/adapter/nghttp2_util.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT NgHttp2Adapter : public Http2Adapter {
public:
~NgHttp2Adapter() override;
static std::unique_ptr<NgHttp2Adapter> CreateClientAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options = nullptr);
static std::unique_ptr<NgHttp2Adapter> CreateServerAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options = nullptr);
bool IsServerSession() const override;
bool want_read() const override { return session_->want_read(); }
bool want_write() const override { return session_->want_write(); }
int64_t ProcessBytes(absl::string_view bytes) override;
void SubmitSettings(absl::Span<const Http2Setting> settings) override;
void SubmitPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id, int weight,
bool exclusive) override;
void SubmitPing(Http2PingId ping_id) override;
void SubmitShutdownNotice() override;
void SubmitGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) override;
void SubmitWindowUpdate(Http2StreamId stream_id,
int window_increment) override;
void SubmitRst(Http2StreamId stream_id, Http2ErrorCode error_code) override;
void SubmitMetadata(Http2StreamId stream_id, size_t max_frame_size,
std::unique_ptr<MetadataSource> source) override;
void SubmitMetadata(Http2StreamId stream_id, size_t num_frames) override;
int Send() override;
int GetSendWindowSize() const override;
int GetStreamSendWindowSize(Http2StreamId stream_id) const override;
int GetStreamReceiveWindowLimit(Http2StreamId stream_id) const override;
int GetStreamReceiveWindowSize(Http2StreamId stream_id) const override;
int GetReceiveWindowSize() const override;
int GetHpackEncoderDynamicTableSize() const override;
int GetHpackDecoderDynamicTableSize() const override;
Http2StreamId GetHighestReceivedStreamId() const override;
void MarkDataConsumedForStream(Http2StreamId stream_id,
size_t num_bytes) override;
int32_t SubmitRequest(absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream, void* user_data) override;
int SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream) override;
int SubmitTrailer(Http2StreamId stream_id,
absl::Span<const Header> trailers) override;
void SetStreamUserData(Http2StreamId stream_id, void* user_data) override;
void* GetStreamUserData(Http2StreamId stream_id) override;
bool ResumeStream(Http2StreamId stream_id) override;
void FrameNotSent(Http2StreamId stream_id, uint8_t frame_type) override;
void RemoveStream(Http2StreamId stream_id);
size_t sources_size() const { return sources_.size(); }
size_t stream_metadata_size() const { return stream_metadata_.size(); }
size_t pending_metadata_count(Http2StreamId stream_id) const {
if (auto it = stream_metadata_.find(stream_id);
it != stream_metadata_.end()) {
return it->second.size();
}
return 0;
}
ssize_t DelegateReadCallback(int32_t stream_id, size_t max_length,
uint32_t* data_flags);
int DelegateSendCallback(int32_t stream_id, const uint8_t* framehd,
size_t length);
private:
class NotifyingMetadataSource;
class NotifyingVisitorMetadataSource;
NgHttp2Adapter(Http2VisitorInterface& visitor, Perspective perspective,
const nghttp2_option* options);
void Initialize();
void RemovePendingMetadata(Http2StreamId stream_id);
std::unique_ptr<NgHttp2Session> session_;
Http2VisitorInterface& visitor_;
const nghttp2_option* options_;
Perspective perspective_;
using MetadataSourceVec =
absl::InlinedVector<std::unique_ptr<MetadataSource>, 2>;
using MetadataMap = absl::flat_hash_map<Http2StreamId, MetadataSourceVec>;
MetadataMap stream_metadata_;
absl::flat_hash_map<int32_t, std::unique_ptr<DataFrameSource>> sources_;
};
}
}
#endif
#include "quiche/http2/adapter/nghttp2_adapter.h"
#include <cstring>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_callbacks.h"
#include "quiche/http2/adapter/nghttp2_data_provider.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_endian.h"
namespace http2 {
namespace adapter {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
const size_t kFrameHeaderSize = 9;
ssize_t DataFrameReadCallback(nghttp2_session* , int32_t stream_id,
uint8_t* , size_t length,
uint32_t* data_flags, nghttp2_data_source* source,
void* ) {
NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr);
return adapter->DelegateReadCallback(stream_id, length, data_flags);
}
int DataFrameSendCallback(nghttp2_session* , nghttp2_frame* frame,
const uint8_t* framehd, size_t length,
nghttp2_data_source* source, void* ) {
NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr);
return adapter->DelegateSendCallback(frame->hd.stream_id, framehd, length);
}
}
class NgHttp2Adapter::NotifyingMetadataSource : public MetadataSource {
public:
explicit NotifyingMetadataSource(NgHttp2Adapter* adapter,
Http2StreamId stream_id,
std::unique_ptr<MetadataSource> source)
: adapter_(adapter), stream_id_(stream_id), source_(std::move(source)) {}
size_t NumFrames(size_t max_frame_size) const override {
return source_->NumFrames(max_frame_size);
}
std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override {
const auto result = source_->Pack(dest, dest_len);
if (result.first < 0 || result.second) {
adapter_->RemovePendingMetadata(stream_id_);
}
return result;
}
void OnFailure() override {
source_->OnFailure();
adapter_->RemovePendingMetadata(stream_id_);
}
private:
NgHttp2Adapter* const adapter_;
const Http2StreamId stream_id_;
std::unique_ptr<MetadataSource> source_;
};
class NgHttp2Adapter::NotifyingVisitorMetadataSource : public MetadataSource {
public:
explicit NotifyingVisitorMetadataSource(NgHttp2Adapter* adapter,
Http2StreamId stream_id,
Http2VisitorInterface& visitor)
: adapter_(adapter), stream_id_(stream_id), visitor_(visitor) {}
size_t NumFrames(size_t ) const override {
QUICHE_LOG(DFATAL) << "Should not be invoked.";
return 0;
}
std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override {
const auto [packed, end_metadata] =
visitor_.PackMetadataForStream(stream_id_, dest, dest_len);
if (packed < 0 || end_metadata) {
adapter_->RemovePendingMetadata(stream_id_);
}
return {packed, end_metadata};
}
void OnFailure() override { adapter_->RemovePendingMetadata(stream_id_); }
private:
NgHttp2Adapter* const adapter_;
const Http2StreamId stream_id_;
Http2VisitorInterface& visitor_;
};
std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateClientAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options) {
auto adapter = new NgHttp2Adapter(visitor, Perspective::kClient, options);
adapter->Initialize();
return absl::WrapUnique(adapter);
}
std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateServerAdapter(
Http2VisitorInterface& visitor, const nghttp2_option* options) {
auto adapter = new NgHttp2Adapter(visitor, Perspective::kServer, options);
adapter->Initialize();
return absl::WrapUnique(adapter);
}
bool NgHttp2Adapter::IsServerSession() const {
int result = nghttp2_session_check_server_session(session_->raw_ptr());
QUICHE_DCHECK_EQ(perspective_ == Perspective::kServer, result > 0);
return result > 0;
}
int64_t NgHttp2Adapter::ProcessBytes(absl::string_view bytes) {
const int64_t processed_bytes = session_->ProcessBytes(bytes);
if (processed_bytes < 0) {
visitor_.OnConnectionError(ConnectionError::kParseError);
}
return processed_bytes;
}
void NgHttp2Adapter::SubmitSettings(absl::Span<const Http2Setting> settings) {
std::vector<nghttp2_settings_entry> nghttp2_settings;
absl::c_transform(settings, std::back_inserter(nghttp2_settings),
[](const Http2Setting& setting) {
return nghttp2_settings_entry{setting.id, setting.value};
});
nghttp2_submit_settings(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
nghttp2_settings.data(), nghttp2_settings.size());
}
void NgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id,
int weight, bool exclusive) {
nghttp2_priority_spec priority_spec;
nghttp2_priority_spec_init(&priority_spec, parent_stream_id, weight,
static_cast<int>(exclusive));
nghttp2_submit_priority(session_->raw_ptr(), NGHTTP2_FLAG_NONE, stream_id,
&priority_spec);
}
void NgHttp2Adapter::SubmitPing(Http2PingId ping_id) {
uint8_t opaque_data[8] = {};
Http2PingId ping_id_to_serialize = quiche::QuicheEndian::HostToNet64(ping_id);
std::memcpy(opaque_data, &ping_id_to_serialize, sizeof(Http2PingId));
nghttp2_submit_ping(session_->raw_ptr(), NGHTTP2_FLAG_NONE, opaque_data);
}
void NgHttp2Adapter::SubmitShutdownNotice() {
nghttp2_submit_shutdown_notice(session_->raw_ptr());
}
void NgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
nghttp2_submit_goaway(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
last_accepted_stream_id,
static_cast<uint32_t>(error_code),
ToUint8Ptr(opaque_data.data()), opaque_data.size());
}
void NgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id,
int window_increment) {
nghttp2_submit_window_update(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
stream_id, window_increment);
}
void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t max_frame_size,
std::unique_ptr<MetadataSource> source) {
auto wrapped_source = std::make_unique<NotifyingMetadataSource>(
this, stream_id, std::move(source));
const size_t num_frames = wrapped_source->NumFrames(max_frame_size);
size_t num_successes = 0;
for (size_t i = 1; i <= num_frames; ++i) {
const int result =
nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType,
i == num_frames ? kMetadataEndFlag : 0,
stream_id, wrapped_source.get());
if (result != 0) {
QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of "
<< num_frames;
break;
}
++num_successes;
}
if (num_successes > 0) {
auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}});
it->second.push_back(std::move(wrapped_source));
}
}
void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t num_frames) {
auto wrapped_source = std::make_unique<NotifyingVisitorMetadataSource>(
this, stream_id, visitor_);
size_t num_successes = 0;
for (size_t i = 1; i <= num_frames; ++i) {
const int result =
nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType,
i == num_frames ? kMetadataEndFlag : 0,
stream_id, wrapped_source.get());
if (result != 0) {
QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of "
<< num_frames;
break;
}
++num_successes;
}
if (num_successes > 0) {
auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}});
it->second.push_back(std::move(wrapped_source));
}
}
int NgHttp2Adapter::Send() {
const int result = nghttp2_session_send(session_->raw_ptr());
if (result != 0) {
QUICHE_VLOG(1) << "nghttp2_session_send returned " << result;
visitor_.OnConnectionError(ConnectionError::kSendError);
}
return result;
}
int NgHttp2Adapter::GetSendWindowSize() const {
return session_->GetRemoteWindowSize();
}
int NgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_remote_window_size(session_->raw_ptr(),
stream_id);
}
int NgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_effective_local_window_size(
session_->raw_ptr(), stream_id);
}
int NgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const {
return nghttp2_session_get_stream_local_window_size(session_->raw_ptr(),
stream_id);
}
int NgHttp2Adapter::GetReceiveWindowSize() const {
return nghttp2_session_get_local_window_size(session_->raw_ptr());
}
int NgHttp2Adapter::GetHpackEncoderDynamicTableSize() const {
return nghttp2_session_get_hd_deflate_dynamic_table_size(session_->raw_ptr());
}
int NgHttp2Adapter::GetHpackDecoderDynamicTableSize() const {
return nghttp2_session_get_hd_inflate_dynamic_table_size(session_->raw_ptr());
}
Http2StreamId NgHttp2Adapter::GetHighestReceivedStreamId() const {
return nghttp2_session_get_last_proc_stream_id(session_->raw_ptr());
}
void NgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id,
size_t num_bytes) {
int rc = session_->Consume(stream_id, num_bytes);
if (rc != 0) {
QUICHE_LOG(ERROR) << "Error " << rc << " marking " << num_bytes
<< " bytes consumed for stream " << stream_id;
}
}
void NgHttp2Adapter::SubmitRst(Http2StreamId stream_id,
Http2ErrorCode error_code) {
int status =
nghttp2_submit_rst_stream(session_->raw_ptr(), NGHTTP2_FLAG_NONE,
stream_id, static_cast<uint32_t>(error_code));
if (status < 0) {
QUICHE_LOG(WARNING) << "Reset stream failed: " << stream_id
<< " with status code " << status;
}
}
int32_t NgHttp2Adapter::SubmitRequest(
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source, bool end_stream,
void* stream_user_data) {
auto nvs = GetNghttp2Nvs(headers);
std::unique_ptr<nghttp2_data_provider> provider;
if (data_source != nullptr || !end_stream) {
provider = std::make_unique<nghttp2_data_provider>();
provider->source.ptr = this;
provider->read_callback = &DataFrameReadCallback;
}
int32_t stream_id =
nghttp2_submit_request(session_->raw_ptr(), nullptr, nvs.data(),
nvs.size(), provider.get(), stream_user_data);
if (data_source != nullptr) {
sources_.emplace(stream_id, std::move(data_source));
}
QUICHE_VLOG(1) << "Submitted request with " << nvs.size()
<< " request headers and user data " << stream_user_data
<< "; resulted in stream " << stream_id;
return stream_id;
}
int NgHttp2Adapter::SubmitResponse(Http2StreamId stream_id,
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream) {
auto nvs = GetNghttp2Nvs(headers);
std::unique_ptr<nghttp2_data_provider> provider;
if (data_source != nullptr || !end_stream) {
provider = std::make_unique<nghttp2_data_provider>();
provider->source.ptr = this;
provider->read_callback = &DataFrameReadCallback;
}
if (data_source != nullptr) {
sources_.emplace(stream_id, std::move(data_source));
}
int result = nghttp2_submit_response(session_->raw_ptr(), stream_id,
nvs.data(), nvs.size(), provider.get());
QUICHE_VLOG(1) << "Submitted response with " << nvs.size()
<< " response headers; result = " << result;
return result;
}
int NgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id,
absl::Span<const Header> trailers) {
auto nvs = GetNghttp2Nvs(trailers);
int result = nghttp2_submit_trailer(session_->raw_ptr(), stream_id,
nvs.data(), nvs.size());
QUICHE_VLOG(1) << "Submitted trailers with " << nvs.size()
<< " response trailers; result = " << result;
return result;
}
void NgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id,
void* stream_user_data) {
nghttp2_session_set_stream_user_data(session_->raw_ptr(), stream_id,
stream_user_data);
}
void* NgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) {
return nghttp2_session_get_stream_user_data(session_->raw_ptr(), stream_id);
}
bool NgHttp2Adapter::ResumeStream(Http2StreamId stream_id) {
return 0 == nghttp2_session_resume_data(session_->raw_ptr(), stream_id);
}
void NgHttp2Adapter::FrameNotSent(Http2StreamId stream_id, uint8_t frame_type) {
if (frame_type == kMetadataFrameType) {
RemovePendingMetadata(stream_id);
}
}
void NgHttp2Adapter::RemoveStream(Http2StreamId stream_id) {
sources_.erase(stream_id);
}
ssize_t NgHttp2Adapter::DelegateReadCallback(int32_t stream_id,
size_t max_length,
uint32_t* data_flags) {
auto it = sources_.find(stream_id);
if (it == sources_.end()) {
return callbacks::VisitorReadCallback(visitor_, stream_id, max_length,
data_flags);
} else {
return callbacks::DataFrameSourceReadCallback(*it->second, max_length,
data_flags);
}
}
int NgHttp2Adapter::DelegateSendCallback(int32_t stream_id,
const uint8_t* framehd,
size_t length) {
auto it = sources_.find(stream_id);
if (it == sources_.end()) {
visitor_.SendDataFrame(stream_id, ToStringView(framehd, kFrameHeaderSize),
length);
} else {
it->second->Send(ToStringView(framehd, kFrameHeaderSize), length);
}
return 0;
}
NgHttp2Adapter::NgHttp2Adapter(Http2VisitorInterface& visitor,
Perspective perspective,
const nghttp2_option* options)
: Http2Adapter(visitor),
visitor_(visitor),
options_(options),
perspective_(perspective) {}
NgHttp2Adapter::~NgHttp2Adapter() {}
void NgHttp2Adapter::Initialize() {
nghttp2_option* owned_options = nullptr;
if (options_ == nullptr) {
nghttp2_option_new(&owned_options);
nghttp2_option_set_no_closed_streams(owned_options, 1);
nghttp2_option_set_no_auto_window_update(owned_options, 1);
nghttp2_option_set_max_send_header_block_length(owned_options, 0x2000000);
nghttp2_option_set_max_outbound_ack(owned_options, 10000);
nghttp2_option_set_user_recv_extension_type(owned_options,
kMetadataFrameType);
options_ = owned_options;
}
session_ = std::make_unique<NgHttp2Session>(
perspective_, callbacks::Create(&DataFrameSendCallback), options_,
static_cast<void*>(&visitor_));
if (owned_options != nullptr) {
nghttp2_option_del(owned_options);
}
options_ = nullptr;
}
void NgHttp2Adapter::RemovePendingMetadata(Http2StreamId stream_id) {
auto it = stream_metadata_.find(stream_id);
if (it != stream_metadata_.end()) {
it->second.erase(it->second.begin());
if (it->second.empty()) {
stream_metadata_.erase(it);
}
}
}
}
} | #include "quiche/http2/adapter/nghttp2_adapter.h"
#include <memory>
#include <string>
#include <vector>
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/http2/adapter/nghttp2_test_utils.h"
#include "quiche/http2/adapter/oghttp2_util.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
using spdy::SpdyFrameType;
using testing::_;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
CONTINUATION,
};
int TestSendCallback(nghttp2_session*, nghttp2_frame* ,
const uint8_t* framehd, size_t length,
nghttp2_data_source* source, void* user_data) {
auto* visitor = static_cast<Http2VisitorInterface*>(user_data);
ssize_t result = visitor->OnReadyToSend(ToStringView(framehd, 9));
if (result == 0) {
return NGHTTP2_ERR_WOULDBLOCK;
}
auto* test_source = static_cast<TestDataSource*>(source->ptr);
absl::string_view payload = test_source->ReadNext(length);
visitor->OnReadyToSend(payload);
return 0;
}
TEST(NgHttp2AdapterTest, ClientConstruction) {
testing::StrictMock<MockHttp2Visitor> visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
ASSERT_NE(nullptr, adapter);
EXPECT_TRUE(adapter->want_read());
EXPECT_FALSE(adapter->want_write());
EXPECT_FALSE(adapter->IsServerSession());
}
TEST(NgHttp2AdapterTest, ClientHandlesFrames) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));
visitor.Clear();
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
const std::string initial_frames = TestFrameSequence()
.ServerPreface()
.Ping(42)
.WindowUpdate(0, 1000)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0));
EXPECT_CALL(visitor, OnWindowUpdate(0, 1000));
const int64_t initial_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), initial_result);
EXPECT_EQ(adapter->GetSendWindowSize(), kInitialFlowControlWindowSize + 1000);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
visitor.Clear();
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const std::vector<Header> headers3 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/three"}});
const char* kSentinel1 = "arbitrary pointer 1";
const char* kSentinel3 = "arbitrary pointer 3";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id2;
const int32_t stream_id3 = adapter->SubmitRequest(
headers3, nullptr, true, const_cast<char*>(kSentinel3));
ASSERT_GT(stream_id3, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id3;
const char* kSentinel2 = "arbitrary pointer 2";
adapter->SetStreamUserData(stream_id2, const_cast<char*>(kSentinel2));
adapter->SetStreamUserData(stream_id3, nullptr);
EXPECT_EQ(adapter->sources_size(), 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::HEADERS,
SpdyFrameType::HEADERS}));
visitor.Clear();
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id2));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id3));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetReceiveWindowSize());
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(stream_id1));
EXPECT_EQ(kSentinel2, adapter->GetStreamUserData(stream_id2));
EXPECT_EQ(nullptr, adapter->GetStreamUserData(stream_id3));
EXPECT_EQ(0, adapter->GetHpackDecoderDynamicTableSize());
const std::string stream_frames =
TestFrameSequence()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.RstStream(3, Http2ErrorCode::INTERNAL_ERROR)
.GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 26));
EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body."));
EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
EXPECT_CALL(visitor, OnFrameHeader(0, 19, GOAWAY, 0));
EXPECT_CALL(visitor,
OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!"));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), stream_result);
EXPECT_GT(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(-1, adapter->GetStreamReceiveWindowSize(stream_id2));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowSize(stream_id3));
EXPECT_EQ(adapter->GetReceiveWindowSize(),
adapter->GetStreamReceiveWindowSize(stream_id1));
EXPECT_EQ(kInitialFlowControlWindowSize,
adapter->GetStreamReceiveWindowLimit(stream_id1));
EXPECT_GT(adapter->GetHpackDecoderDynamicTableSize(), 0);
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_TRUE(adapter->want_read());
EXPECT_CALL(visitor, OnFrameHeader(1, 0, DATA, 1));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 0));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
EXPECT_CALL(visitor, OnFrameHeader(5, 4, RST_STREAM, 0));
EXPECT_CALL(visitor, OnRstStream(5, Http2ErrorCode::REFUSED_STREAM));
EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM))
.WillOnce(
[&adapter](Http2StreamId stream_id, Http2ErrorCode ) {
adapter->RemoveStream(stream_id);
return true;
});
adapter->ProcessBytes(TestFrameSequence()
.Data(1, "", true)
.RstStream(5, Http2ErrorCode::REFUSED_STREAM)
.Serialize());
EXPECT_EQ(0, adapter->GetHighestReceivedStreamId());
EXPECT_FALSE(adapter->want_read());
EXPECT_FALSE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), testing::IsEmpty());
}
TEST(NgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(0, 10000);
EXPECT_EQ(adapter->GetReceiveWindowSize(),
kInitialFlowControlWindowSize + 10000);
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(1, 20000);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize + 20000);
}
TEST(NgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
const std::string initial_frames =
TestFrameSequence().ServerPreface().Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
int64_t parse_result = adapter->ProcessBytes(initial_frames);
EXPECT_EQ(initial_frames.size(), static_cast<size_t>(parse_result));
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 80000u}});
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1),
kInitialFlowControlWindowSize);
const std::string settings_ack =
TestFrameSequence().SettingsAck().Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1));
EXPECT_CALL(visitor, OnSettingsAck);
parse_result = adapter->ProcessBytes(settings_ack);
EXPECT_EQ(settings_ack.size(), static_cast<size_t>(parse_result));
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), 80000);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id2), 80000);
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithFin) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}}, false)
.Headers(1, {{":status", "100"}}, true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor,
OnInvalidFrame(
1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}},
false)
.Data(1, "We needed the final headers before data, whoops")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, _));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}, {"content-length", "42"}},
false)
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [content-length], value: [42]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientHandles204WithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
const std::vector<Header> headers2 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/two"}});
const int32_t stream_id2 =
adapter->SubmitRequest(headers2, nullptr, true, nullptr);
ASSERT_GT(stream_id2, stream_id1);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "204"}, {"content-length", "2"}},
false)
.Data(1, "hi")
.Headers(3, {{":status", "204"}}, false)
.Data(3, "hi")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "204"));
EXPECT_CALL(
visitor,
OnErrorDebug("Invalid HTTP header field was received: frame type: 1, "
"stream: 1, name: [content-length], value: [2]"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":status", "204"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(3, 2));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 3, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientHandles304WithContent) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "304"}, {"content-length", "2"}},
false)
.Data(1, "hi")
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0));
EXPECT_CALL(visitor, OnBeginDataForStream(1, 2));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(RST_STREAM, 1, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS,
SpdyFrameType::RST_STREAM}));
}
TEST(NgHttp2AdapterTest, ClientHandles304WithContentLength) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
ASSERT_GT(stream_id, 0);
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "304"}, {"content-length", "2"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS}));
}
TEST(NgHttp2AdapterTest, ClientHandlesTrailers) {
TestVisitor visitor;
auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const char* kSentinel1 = "arbitrary pointer 1";
const int32_t stream_id1 = adapter->SubmitRequest(
headers1, nullptr, true, const_cast<char*>(kSentinel1));
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS}));
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
false)
.Data(1, "This is the response body.")
.Headers(1, {{"final-status", "A-OK"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnH |
412 | cpp | google/quiche | nghttp2_util | quiche/http2/adapter/nghttp2_util.cc | quiche/http2/adapter/nghttp2_util_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_NGHTTP2_UTIL_H_
#define QUICHE_HTTP2_ADAPTER_NGHTTP2_UTIL_H_
#include <cstdint>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/http2/adapter/data_source.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/nghttp2.h"
#include "quiche/spdy/core/http2_header_block.h"
namespace http2 {
namespace adapter {
inline constexpr int kStreamCallbackFailureStatus =
NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
inline constexpr int kCancelStatus = NGHTTP2_ERR_CANCEL;
using CallbacksDeleter = void (*)(nghttp2_session_callbacks*);
using SessionDeleter = void (*)(nghttp2_session*);
using nghttp2_session_callbacks_unique_ptr =
std::unique_ptr<nghttp2_session_callbacks, CallbacksDeleter>;
using nghttp2_session_unique_ptr =
std::unique_ptr<nghttp2_session, SessionDeleter>;
nghttp2_session_callbacks_unique_ptr MakeCallbacksPtr(
nghttp2_session_callbacks* callbacks);
nghttp2_session_unique_ptr MakeSessionPtr(nghttp2_session* session);
uint8_t* ToUint8Ptr(char* str);
uint8_t* ToUint8Ptr(const char* str);
absl::string_view ToStringView(nghttp2_rcbuf* rc_buffer);
absl::string_view ToStringView(uint8_t* pointer, size_t length);
absl::string_view ToStringView(const uint8_t* pointer, size_t length);
std::vector<nghttp2_nv> GetNghttp2Nvs(absl::Span<const Header> headers);
std::vector<nghttp2_nv> GetResponseNghttp2Nvs(
const spdy::Http2HeaderBlock& headers, absl::string_view response_code);
Http2ErrorCode ToHttp2ErrorCode(uint32_t wire_error_code);
int ToNgHttp2ErrorCode(Http2VisitorInterface::InvalidFrameError error);
Http2VisitorInterface::InvalidFrameError ToInvalidFrameError(int error);
std::unique_ptr<DataFrameSource> MakeZeroCopyDataFrameSource(
nghttp2_data_provider provider, void* user_data,
nghttp2_send_data_callback send_data);
void LogBeforeSend(const nghttp2_frame& frame);
}
}
#endif
#include "quiche/http2/adapter/nghttp2_util.h"
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_endian.h"
namespace http2 {
namespace adapter {
namespace {
using InvalidFrameError = Http2VisitorInterface::InvalidFrameError;
void DeleteCallbacks(nghttp2_session_callbacks* callbacks) {
if (callbacks) {
nghttp2_session_callbacks_del(callbacks);
}
}
void DeleteSession(nghttp2_session* session) {
if (session) {
nghttp2_session_del(session);
}
}
}
nghttp2_session_callbacks_unique_ptr MakeCallbacksPtr(
nghttp2_session_callbacks* callbacks) {
return nghttp2_session_callbacks_unique_ptr(callbacks, &DeleteCallbacks);
}
nghttp2_session_unique_ptr MakeSessionPtr(nghttp2_session* session) {
return nghttp2_session_unique_ptr(session, &DeleteSession);
}
uint8_t* ToUint8Ptr(char* str) { return reinterpret_cast<uint8_t*>(str); }
uint8_t* ToUint8Ptr(const char* str) {
return const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(str));
}
absl::string_view ToStringView(nghttp2_rcbuf* rc_buffer) {
nghttp2_vec buffer = nghttp2_rcbuf_get_buf(rc_buffer);
return absl::string_view(reinterpret_cast<const char*>(buffer.base),
buffer.len);
}
absl::string_view ToStringView(uint8_t* pointer, size_t length) {
return absl::string_view(reinterpret_cast<const char*>(pointer), length);
}
absl::string_view ToStringView(const uint8_t* pointer, size_t length) {
return absl::string_view(reinterpret_cast<const char*>(pointer), length);
}
std::vector<nghttp2_nv> GetNghttp2Nvs(absl::Span<const Header> headers) {
const int num_headers = headers.size();
std::vector<nghttp2_nv> nghttp2_nvs;
nghttp2_nvs.reserve(num_headers);
for (int i = 0; i < num_headers; ++i) {
nghttp2_nv header;
uint8_t flags = NGHTTP2_NV_FLAG_NONE;
const auto [name, no_copy_name] = GetStringView(headers[i].first);
header.name = ToUint8Ptr(name.data());
header.namelen = name.size();
if (no_copy_name) {
flags |= NGHTTP2_NV_FLAG_NO_COPY_NAME;
}
const auto [value, no_copy_value] = GetStringView(headers[i].second);
header.value = ToUint8Ptr(value.data());
header.valuelen = value.size();
if (no_copy_value) {
flags |= NGHTTP2_NV_FLAG_NO_COPY_VALUE;
}
header.flags = flags;
nghttp2_nvs.push_back(std::move(header));
}
return nghttp2_nvs;
}
std::vector<nghttp2_nv> GetResponseNghttp2Nvs(
const spdy::Http2HeaderBlock& headers, absl::string_view response_code) {
const int num_headers = headers.size();
std::vector<nghttp2_nv> nghttp2_nvs;
nghttp2_nvs.reserve(num_headers + 1);
nghttp2_nv status;
status.name = ToUint8Ptr(kHttp2StatusPseudoHeader);
status.namelen = strlen(kHttp2StatusPseudoHeader);
status.value = ToUint8Ptr(response_code.data());
status.valuelen = response_code.size();
status.flags = NGHTTP2_FLAG_NONE;
nghttp2_nvs.push_back(std::move(status));
for (const auto& header_pair : headers) {
nghttp2_nv header;
header.name = ToUint8Ptr(header_pair.first.data());
header.namelen = header_pair.first.size();
header.value = ToUint8Ptr(header_pair.second.data());
header.valuelen = header_pair.second.size();
header.flags = NGHTTP2_FLAG_NONE;
nghttp2_nvs.push_back(std::move(header));
}
return nghttp2_nvs;
}
Http2ErrorCode ToHttp2ErrorCode(uint32_t wire_error_code) {
if (wire_error_code > static_cast<int>(Http2ErrorCode::MAX_ERROR_CODE)) {
return Http2ErrorCode::INTERNAL_ERROR;
}
return static_cast<Http2ErrorCode>(wire_error_code);
}
int ToNgHttp2ErrorCode(InvalidFrameError error) {
switch (error) {
case InvalidFrameError::kProtocol:
return NGHTTP2_ERR_PROTO;
case InvalidFrameError::kRefusedStream:
return NGHTTP2_ERR_REFUSED_STREAM;
case InvalidFrameError::kHttpHeader:
return NGHTTP2_ERR_HTTP_HEADER;
case InvalidFrameError::kHttpMessaging:
return NGHTTP2_ERR_HTTP_MESSAGING;
case InvalidFrameError::kFlowControl:
return NGHTTP2_ERR_FLOW_CONTROL;
case InvalidFrameError::kStreamClosed:
return NGHTTP2_ERR_STREAM_CLOSED;
}
return NGHTTP2_ERR_PROTO;
}
InvalidFrameError ToInvalidFrameError(int error) {
switch (error) {
case NGHTTP2_ERR_PROTO:
return InvalidFrameError::kProtocol;
case NGHTTP2_ERR_REFUSED_STREAM:
return InvalidFrameError::kRefusedStream;
case NGHTTP2_ERR_HTTP_HEADER:
return InvalidFrameError::kHttpHeader;
case NGHTTP2_ERR_HTTP_MESSAGING:
return InvalidFrameError::kHttpMessaging;
case NGHTTP2_ERR_FLOW_CONTROL:
return InvalidFrameError::kFlowControl;
case NGHTTP2_ERR_STREAM_CLOSED:
return InvalidFrameError::kStreamClosed;
}
return InvalidFrameError::kProtocol;
}
class Nghttp2DataFrameSource : public DataFrameSource {
public:
Nghttp2DataFrameSource(nghttp2_data_provider provider,
nghttp2_send_data_callback send_data, void* user_data)
: provider_(std::move(provider)),
send_data_(std::move(send_data)),
user_data_(user_data) {}
std::pair<int64_t, bool> SelectPayloadLength(size_t max_length) override {
const int32_t stream_id = 0;
uint32_t data_flags = 0;
int64_t result = provider_.read_callback(
nullptr , stream_id, nullptr , max_length,
&data_flags, &provider_.source, nullptr );
if (result == NGHTTP2_ERR_DEFERRED) {
return {kBlocked, false};
} else if (result < 0) {
return {kError, false};
} else if ((data_flags & NGHTTP2_DATA_FLAG_NO_COPY) == 0) {
QUICHE_LOG(ERROR) << "Source did not use the zero-copy API!";
return {kError, false};
} else {
const bool eof = data_flags & NGHTTP2_DATA_FLAG_EOF;
if (eof && (data_flags & NGHTTP2_DATA_FLAG_NO_END_STREAM) == 0) {
send_fin_ = true;
}
return {result, eof};
}
}
bool Send(absl::string_view frame_header, size_t payload_length) override {
nghttp2_frame frame;
frame.hd.type = 0;
frame.hd.length = payload_length;
frame.hd.flags = 0;
frame.hd.stream_id = 0;
frame.data.padlen = 0;
const int result = send_data_(
nullptr , &frame, ToUint8Ptr(frame_header.data()),
payload_length, &provider_.source, user_data_);
QUICHE_LOG_IF(ERROR, result < 0 && result != NGHTTP2_ERR_WOULDBLOCK)
<< "Unexpected error code from send: " << result;
return result == 0;
}
bool send_fin() const override { return send_fin_; }
private:
nghttp2_data_provider provider_;
nghttp2_send_data_callback send_data_;
void* user_data_;
bool send_fin_ = false;
};
std::unique_ptr<DataFrameSource> MakeZeroCopyDataFrameSource(
nghttp2_data_provider provider, void* user_data,
nghttp2_send_data_callback send_data) {
return std::make_unique<Nghttp2DataFrameSource>(
std::move(provider), std::move(send_data), user_data);
}
absl::string_view ErrorString(uint32_t error_code) {
return Http2ErrorCodeToString(static_cast<Http2ErrorCode>(error_code));
}
size_t PaddingLength(uint8_t flags, size_t padlen) {
return (flags & PADDED_FLAG ? 1 : 0) + padlen;
}
struct NvFormatter {
void operator()(std::string* out, const nghttp2_nv& nv) {
absl::StrAppend(out, ToStringView(nv.name, nv.namelen), ": ",
ToStringView(nv.value, nv.valuelen));
}
};
std::string NvsAsString(nghttp2_nv* nva, size_t nvlen) {
return absl::StrJoin(absl::MakeConstSpan(nva, nvlen), ", ", NvFormatter());
}
#define HTTP2_FRAME_SEND_LOG QUICHE_VLOG(1)
void LogBeforeSend(const nghttp2_frame& frame) {
switch (static_cast<FrameType>(frame.hd.type)) {
case FrameType::DATA:
HTTP2_FRAME_SEND_LOG << "Sending DATA on stream " << frame.hd.stream_id
<< " with length "
<< frame.hd.length - PaddingLength(frame.hd.flags,
frame.data.padlen)
<< " and padding "
<< PaddingLength(frame.hd.flags, frame.data.padlen);
break;
case FrameType::HEADERS:
HTTP2_FRAME_SEND_LOG << "Sending HEADERS on stream " << frame.hd.stream_id
<< " with headers ["
<< NvsAsString(frame.headers.nva,
frame.headers.nvlen)
<< "]";
break;
case FrameType::PRIORITY:
HTTP2_FRAME_SEND_LOG << "Sending PRIORITY";
break;
case FrameType::RST_STREAM:
HTTP2_FRAME_SEND_LOG << "Sending RST_STREAM on stream "
<< frame.hd.stream_id << " with error code "
<< ErrorString(frame.rst_stream.error_code);
break;
case FrameType::SETTINGS:
HTTP2_FRAME_SEND_LOG << "Sending SETTINGS with " << frame.settings.niv
<< " entries, is_ack: "
<< (frame.hd.flags & ACK_FLAG);
break;
case FrameType::PUSH_PROMISE:
HTTP2_FRAME_SEND_LOG << "Sending PUSH_PROMISE";
break;
case FrameType::PING: {
Http2PingId ping_id;
std::memcpy(&ping_id, frame.ping.opaque_data, sizeof(Http2PingId));
HTTP2_FRAME_SEND_LOG << "Sending PING with unique_id "
<< quiche::QuicheEndian::NetToHost64(ping_id)
<< ", is_ack: " << (frame.hd.flags & ACK_FLAG);
break;
}
case FrameType::GOAWAY:
HTTP2_FRAME_SEND_LOG << "Sending GOAWAY with last_stream: "
<< frame.goaway.last_stream_id << " and error "
<< ErrorString(frame.goaway.error_code);
break;
case FrameType::WINDOW_UPDATE:
HTTP2_FRAME_SEND_LOG << "Sending WINDOW_UPDATE on stream "
<< frame.hd.stream_id << " with update delta "
<< frame.window_update.window_size_increment;
break;
case FrameType::CONTINUATION:
HTTP2_FRAME_SEND_LOG << "Sending CONTINUATION, which is unexpected";
break;
}
}
#undef HTTP2_FRAME_SEND_LOG
}
} | #include "quiche/http2/adapter/nghttp2_util.h"
#include <memory>
#include <string>
#include "quiche/http2/adapter/nghttp2_test_utils.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
int FakeSendCallback(nghttp2_session*, nghttp2_frame* ,
const uint8_t* framehd, size_t length,
nghttp2_data_source* source, void* user_data) {
auto* dest = static_cast<std::string*>(user_data);
absl::StrAppend(dest, ToStringView(framehd, 9));
auto* test_source = static_cast<TestDataSource*>(source->ptr);
absl::string_view payload = test_source->ReadNext(length);
absl::StrAppend(dest, payload);
return 0;
}
TEST(MakeZeroCopyDataFrameSource, EmptyPayload) {
std::string result;
const absl::string_view kEmptyBody = "";
TestDataSource body1{kEmptyBody};
nghttp2_data_provider provider = body1.MakeDataProvider();
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback);
auto [length, eof] = frame_source->SelectPayloadLength(100);
EXPECT_EQ(length, 0);
EXPECT_TRUE(eof);
frame_source->Send("ninebytes", 0);
EXPECT_EQ(result, "ninebytes");
}
TEST(MakeZeroCopyDataFrameSource, ShortPayload) {
std::string result;
const absl::string_view kShortBody =
"<html><head><title>Example Page!</title></head>"
"<body><div><span><table><tr><th><blink>Wow!!"
"</blink></th></tr></table></span></div></body>"
"</html>";
TestDataSource body1{kShortBody};
nghttp2_data_provider provider = body1.MakeDataProvider();
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback);
auto [length, eof] = frame_source->SelectPayloadLength(200);
EXPECT_EQ(length, kShortBody.size());
EXPECT_TRUE(eof);
frame_source->Send("ninebytes", length);
EXPECT_EQ(result, absl::StrCat("ninebytes", kShortBody));
}
TEST(MakeZeroCopyDataFrameSource, MultiFramePayload) {
std::string result;
const absl::string_view kShortBody =
"<html><head><title>Example Page!</title></head>"
"<body><div><span><table><tr><th><blink>Wow!!"
"</blink></th></tr></table></span></div></body>"
"</html>";
TestDataSource body1{kShortBody};
nghttp2_data_provider provider = body1.MakeDataProvider();
std::unique_ptr<DataFrameSource> frame_source =
MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback);
auto ret = frame_source->SelectPayloadLength(50);
EXPECT_EQ(ret.first, 50);
EXPECT_FALSE(ret.second);
frame_source->Send("ninebyte1", ret.first);
ret = frame_source->SelectPayloadLength(50);
EXPECT_EQ(ret.first, 50);
EXPECT_FALSE(ret.second);
frame_source->Send("ninebyte2", ret.first);
ret = frame_source->SelectPayloadLength(50);
EXPECT_EQ(ret.first, 44);
EXPECT_TRUE(ret.second);
frame_source->Send("ninebyte3", ret.first);
EXPECT_EQ(result,
"ninebyte1<html><head><title>Example Page!</title></head><bo"
"ninebyte2dy><div><span><table><tr><th><blink>Wow!!</blink><"
"ninebyte3/th></tr></table></span></div></body></html>");
}
}
}
}
} |
413 | cpp | google/quiche | oghttp2_adapter | quiche/http2/adapter/oghttp2_adapter.cc | quiche/http2/adapter/oghttp2_adapter_test.cc | #ifndef QUICHE_HTTP2_ADAPTER_OGHTTP2_ADAPTER_H_
#define QUICHE_HTTP2_ADAPTER_OGHTTP2_ADAPTER_H_
#include <cstdint>
#include <memory>
#include "quiche/http2/adapter/http2_adapter.h"
#include "quiche/http2/adapter/http2_session.h"
#include "quiche/http2/adapter/oghttp2_session.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace adapter {
class QUICHE_EXPORT OgHttp2Adapter : public Http2Adapter {
public:
using Options = OgHttp2Session::Options;
static std::unique_ptr<OgHttp2Adapter> Create(Http2VisitorInterface& visitor,
Options options);
~OgHttp2Adapter() override;
bool IsServerSession() const override;
bool want_read() const override { return session_->want_read(); }
bool want_write() const override { return session_->want_write(); }
int64_t ProcessBytes(absl::string_view bytes) override;
void SubmitSettings(absl::Span<const Http2Setting> settings) override;
void SubmitPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id, int weight,
bool exclusive) override;
void SubmitPing(Http2PingId ping_id) override;
void SubmitShutdownNotice() override;
void SubmitGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) override;
void SubmitWindowUpdate(Http2StreamId stream_id,
int window_increment) override;
void SubmitMetadata(Http2StreamId stream_id, size_t max_frame_size,
std::unique_ptr<MetadataSource> source) override;
void SubmitMetadata(Http2StreamId stream_id, size_t num_frames) override;
int Send() override;
int GetSendWindowSize() const override;
int GetStreamSendWindowSize(Http2StreamId stream_id) const override;
int GetStreamReceiveWindowLimit(Http2StreamId stream_id) const override;
int GetStreamReceiveWindowSize(Http2StreamId stream_id) const override;
int GetReceiveWindowSize() const override;
int GetHpackEncoderDynamicTableSize() const override;
int GetHpackEncoderDynamicTableCapacity() const;
int GetHpackDecoderDynamicTableSize() const override;
int GetHpackDecoderSizeLimit() const;
Http2StreamId GetHighestReceivedStreamId() const override;
void MarkDataConsumedForStream(Http2StreamId stream_id,
size_t num_bytes) override;
void SubmitRst(Http2StreamId stream_id, Http2ErrorCode error_code) override;
int32_t SubmitRequest(absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream, void* user_data) override;
int SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream) override;
int SubmitTrailer(Http2StreamId stream_id,
absl::Span<const Header> trailers) override;
void SetStreamUserData(Http2StreamId stream_id, void* user_data) override;
void* GetStreamUserData(Http2StreamId stream_id) override;
bool ResumeStream(Http2StreamId stream_id) override;
private:
OgHttp2Adapter(Http2VisitorInterface& visitor, Options options);
std::unique_ptr<OgHttp2Session> session_;
};
}
}
#endif
#include "quiche/http2/adapter/oghttp2_adapter.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "quiche/http2/adapter/http2_util.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/spdy/core/spdy_protocol.h"
namespace http2 {
namespace adapter {
namespace {
using spdy::SpdyGoAwayIR;
using spdy::SpdyPingIR;
using spdy::SpdyPriorityIR;
using spdy::SpdyWindowUpdateIR;
}
std::unique_ptr<OgHttp2Adapter> OgHttp2Adapter::Create(
Http2VisitorInterface& visitor, Options options) {
return absl::WrapUnique(new OgHttp2Adapter(visitor, std::move(options)));
}
OgHttp2Adapter::~OgHttp2Adapter() {}
bool OgHttp2Adapter::IsServerSession() const {
return session_->IsServerSession();
}
int64_t OgHttp2Adapter::ProcessBytes(absl::string_view bytes) {
return session_->ProcessBytes(bytes);
}
void OgHttp2Adapter::SubmitSettings(absl::Span<const Http2Setting> settings) {
session_->SubmitSettings(settings);
}
void OgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id,
Http2StreamId parent_stream_id,
int weight, bool exclusive) {
session_->EnqueueFrame(std::make_unique<SpdyPriorityIR>(
stream_id, parent_stream_id, weight, exclusive));
}
void OgHttp2Adapter::SubmitPing(Http2PingId ping_id) {
session_->EnqueueFrame(std::make_unique<SpdyPingIR>(ping_id));
}
void OgHttp2Adapter::SubmitShutdownNotice() {
session_->StartGracefulShutdown();
}
void OgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id,
Http2ErrorCode error_code,
absl::string_view opaque_data) {
session_->EnqueueFrame(std::make_unique<SpdyGoAwayIR>(
last_accepted_stream_id, TranslateErrorCode(error_code),
std::string(opaque_data)));
}
void OgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id,
int window_increment) {
session_->EnqueueFrame(
std::make_unique<SpdyWindowUpdateIR>(stream_id, window_increment));
}
void OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t ,
std::unique_ptr<MetadataSource> source) {
session_->SubmitMetadata(stream_id, std::move(source));
}
void OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id,
size_t ) {
session_->SubmitMetadata(stream_id);
}
int OgHttp2Adapter::Send() { return session_->Send(); }
int OgHttp2Adapter::GetSendWindowSize() const {
return session_->GetRemoteWindowSize();
}
int OgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const {
return session_->GetStreamSendWindowSize(stream_id);
}
int OgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const {
return session_->GetStreamReceiveWindowLimit(stream_id);
}
int OgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const {
return session_->GetStreamReceiveWindowSize(stream_id);
}
int OgHttp2Adapter::GetReceiveWindowSize() const {
return session_->GetReceiveWindowSize();
}
int OgHttp2Adapter::GetHpackEncoderDynamicTableSize() const {
return session_->GetHpackEncoderDynamicTableSize();
}
int OgHttp2Adapter::GetHpackEncoderDynamicTableCapacity() const {
return session_->GetHpackEncoderDynamicTableCapacity();
}
int OgHttp2Adapter::GetHpackDecoderDynamicTableSize() const {
return session_->GetHpackDecoderDynamicTableSize();
}
int OgHttp2Adapter::GetHpackDecoderSizeLimit() const {
return session_->GetHpackDecoderSizeLimit();
}
Http2StreamId OgHttp2Adapter::GetHighestReceivedStreamId() const {
return session_->GetHighestReceivedStreamId();
}
void OgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id,
size_t num_bytes) {
session_->Consume(stream_id, num_bytes);
}
void OgHttp2Adapter::SubmitRst(Http2StreamId stream_id,
Http2ErrorCode error_code) {
session_->EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>(
stream_id, TranslateErrorCode(error_code)));
}
int32_t OgHttp2Adapter::SubmitRequest(
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source, bool end_stream,
void* user_data) {
return session_->SubmitRequest(headers, std::move(data_source), end_stream,
user_data);
}
int OgHttp2Adapter::SubmitResponse(Http2StreamId stream_id,
absl::Span<const Header> headers,
std::unique_ptr<DataFrameSource> data_source,
bool end_stream) {
return session_->SubmitResponse(stream_id, headers, std::move(data_source),
end_stream);
}
int OgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id,
absl::Span<const Header> trailers) {
return session_->SubmitTrailer(stream_id, trailers);
}
void OgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id,
void* user_data) {
session_->SetStreamUserData(stream_id, user_data);
}
void* OgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) {
return session_->GetStreamUserData(stream_id);
}
bool OgHttp2Adapter::ResumeStream(Http2StreamId stream_id) {
return session_->ResumeStream(stream_id);
}
OgHttp2Adapter::OgHttp2Adapter(Http2VisitorInterface& visitor, Options options)
: Http2Adapter(visitor),
session_(std::make_unique<OgHttp2Session>(visitor, std::move(options))) {}
}
} | #include "quiche/http2/adapter/oghttp2_adapter.h"
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/str_join.h"
#include "quiche/http2/adapter/http2_protocol.h"
#include "quiche/http2/adapter/http2_visitor_interface.h"
#include "quiche/http2/adapter/mock_http2_visitor.h"
#include "quiche/http2/adapter/oghttp2_util.h"
#include "quiche/http2/adapter/test_frame_sequence.h"
#include "quiche/http2/adapter/test_utils.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/spdy/core/http2_header_block.h"
namespace http2 {
namespace adapter {
namespace test {
namespace {
using ConnectionError = Http2VisitorInterface::ConnectionError;
using spdy::SpdyFrameType;
using testing::_;
enum FrameType {
DATA,
HEADERS,
PRIORITY,
RST_STREAM,
SETTINGS,
PUSH_PROMISE,
PING,
GOAWAY,
WINDOW_UPDATE,
CONTINUATION,
};
TEST(OgHttp2AdapterTest, IsServerSession) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
EXPECT_TRUE(adapter->IsServerSession());
}
TEST(OgHttp2AdapterTest, ProcessBytes) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
testing::InSequence seq;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, 4, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 8, 6, 0));
EXPECT_CALL(visitor, OnPing(17, false));
adapter->ProcessBytes(
TestFrameSequence().ClientPreface().Ping(17).Serialize());
}
TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextAllowedByDefault) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.perspective = Perspective::kServer;
ASSERT_TRUE(options.allow_obs_text);
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{"name", "val\xa1ue"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "name", "val\xa1ue"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextDisallowed) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.allow_obs_text = false;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/"},
{"name", "val\xa1ue"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTab) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.allow_obs_text = false;
options.perspective = Perspective::kServer;
ASSERT_EQ(false, options.validate_path);
options.validate_path = true;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/ fragment"}},
true)
.Headers(3,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/\tfragment2"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(
visitor,
OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(
visitor,
OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTabNoPathValidation) {
TestVisitor visitor;
OgHttp2Session::Options options;
options.allow_obs_text = false;
options.perspective = Perspective::kServer;
ASSERT_EQ(false, options.validate_path);
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames = TestFrameSequence()
.ClientPreface()
.Headers(1,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/ fragment"}},
true)
.Headers(3,
{{":method", "GET"},
{":scheme", "https"},
{":authority", "example.com"},
{":path", "/\tfragment2"}},
true)
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/ fragment"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(3));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com"));
EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/\tfragment2"));
EXPECT_CALL(visitor, OnEndHeadersForStream(3));
EXPECT_CALL(visitor, OnEndStream(3));
const int64_t result = adapter->ProcessBytes(frames);
EXPECT_EQ(frames.size(), static_cast<size_t>(result));
}
TEST(OgHttp2AdapterTest, InitialSettingsNoExtendedConnect) {
TestVisitor client_visitor;
OgHttp2Adapter::Options client_options;
client_options.perspective = Perspective::kClient;
client_options.max_header_list_bytes = 42;
client_options.allow_extended_connect = false;
auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options);
TestVisitor server_visitor;
OgHttp2Adapter::Options server_options;
server_options.perspective = Perspective::kServer;
server_options.allow_extended_connect = false;
auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options);
testing::InSequence s;
EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0));
EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0));
{
int result = client_adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = client_visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
}
EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0));
EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0));
{
int result = server_adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = server_visitor.data();
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
}
EXPECT_CALL(client_visitor, OnFrameHeader(0, 0, SETTINGS, 0x0));
EXPECT_CALL(client_visitor, OnSettingsStart());
EXPECT_CALL(client_visitor, OnSettingsEnd());
{
const int64_t result = client_adapter->ProcessBytes(server_visitor.data());
EXPECT_EQ(server_visitor.data().size(), static_cast<size_t>(result));
}
EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0));
EXPECT_CALL(server_visitor, OnSettingsStart());
EXPECT_CALL(server_visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u}));
EXPECT_CALL(
server_visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u}));
EXPECT_CALL(server_visitor, OnSettingsEnd());
{
const int64_t result = server_adapter->ProcessBytes(client_visitor.data());
EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result));
}
}
TEST(OgHttp2AdapterTest, InitialSettings) {
TestVisitor client_visitor;
OgHttp2Adapter::Options client_options;
client_options.perspective = Perspective::kClient;
client_options.max_header_list_bytes = 42;
ASSERT_TRUE(client_options.allow_extended_connect);
auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options);
TestVisitor server_visitor;
OgHttp2Adapter::Options server_options;
server_options.perspective = Perspective::kServer;
ASSERT_TRUE(server_options.allow_extended_connect);
auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options);
testing::InSequence s;
EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0));
EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0));
{
int result = client_adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = client_visitor.data();
EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix));
data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix));
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
}
EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0));
EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0));
{
int result = server_adapter->Send();
EXPECT_EQ(0, result);
absl::string_view data = server_visitor.data();
EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS}));
}
EXPECT_CALL(client_visitor, OnFrameHeader(0, 6, SETTINGS, 0x0));
EXPECT_CALL(client_visitor, OnSettingsStart());
EXPECT_CALL(client_visitor,
OnSetting(Http2Setting{
Http2KnownSettingsId::ENABLE_CONNECT_PROTOCOL, 1u}));
EXPECT_CALL(client_visitor, OnSettingsEnd());
{
const int64_t result = client_adapter->ProcessBytes(server_visitor.data());
EXPECT_EQ(server_visitor.data().size(), static_cast<size_t>(result));
}
EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0));
EXPECT_CALL(server_visitor, OnSettingsStart());
EXPECT_CALL(server_visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u}));
EXPECT_CALL(
server_visitor,
OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u}));
EXPECT_CALL(server_visitor, OnSettingsEnd());
{
const int64_t result = server_adapter->ProcessBytes(client_visitor.data());
EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result));
}
}
TEST(OgHttp2AdapterTest, AutomaticSettingsAndPingAcks) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames =
TestFrameSequence().ClientPreface().Ping(42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS,
SpdyFrameType::PING}));
}
TEST(OgHttp2AdapterTest, AutomaticPingAcksDisabled) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
options.auto_ping_ack = false;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames =
TestFrameSequence().ClientPreface().Ping(42).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0));
EXPECT_CALL(visitor, OnPing(42, false));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS}));
}
TEST(OgHttp2AdapterTest, InvalidMaxFrameSizeSetting) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames =
TestFrameSequence().ClientPreface({{MAX_FRAME_SIZE, 3u}}).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));
}
TEST(OgHttp2AdapterTest, InvalidPushSetting) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames =
TestFrameSequence().ClientPreface({{ENABLE_PUSH, 3u}}).Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));
const int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));
}
TEST(OgHttp2AdapterTest, InvalidConnectProtocolSetting) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kServer;
auto adapter = OgHttp2Adapter::Create(visitor, options);
const std::string frames = TestFrameSequence()
.ClientPreface({{ENABLE_CONNECT_PROTOCOL, 3u}})
.Serialize();
testing::InSequence s;
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));
int64_t read_result = adapter->ProcessBytes(frames);
EXPECT_EQ(static_cast<size_t>(read_result), frames.size());
EXPECT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
int send_result = adapter->Send();
EXPECT_EQ(0, send_result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY}));
auto adapter2 = OgHttp2Adapter::Create(visitor, options);
const std::string frames2 = TestFrameSequence()
.ClientPreface({{ENABLE_CONNECT_PROTOCOL, 1}})
.Settings({{ENABLE_CONNECT_PROTOCOL, 0}})
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 1u}));
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(
visitor,
OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol));
EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting));
read_result = adapter2->ProcessBytes(frames2);
EXPECT_EQ(static_cast<size_t>(read_result), frames2.size());
EXPECT_TRUE(adapter2->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0));
EXPECT_CALL(visitor,
OnFrameSent(GOAWAY, 0, _, 0x0,
static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR)));
adapter2->Send();
}
TEST(OgHttp2AdapterTest, ClientSetsRemoteMaxStreamOption) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kClient;
options.remote_max_concurrent_streams = 3;
auto adapter = OgHttp2Adapter::Create(visitor, options);
testing::InSequence s;
const std::vector<Header> headers = ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const int32_t stream_id2 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const int32_t stream_id3 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
const int32_t stream_id4 =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(stream_id1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(stream_id1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id1));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, ":status", "200"));
EXPECT_CALL(visitor,
OnHeaderForStream(stream_id1, "server", "my-fake-server"));
EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, "date",
"Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id1));
EXPECT_CALL(visitor, OnEndStream(stream_id1));
EXPECT_CALL(visitor,
OnCloseStream(stream_id1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
ASSERT_TRUE(adapter->want_write());
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id4, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id4, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
result = adapter->Send();
EXPECT_EQ(0, result);
}
TEST(OgHttp2AdapterTest, ClientHandles100Headers) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kClient;
auto adapter = OgHttp2Adapter::Create(visitor, options);
testing::InSequence s;
const std::vector<Header> headers1 =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id1 =
adapter->SubmitRequest(headers1, nullptr, true, nullptr);
ASSERT_GT(stream_id1, 0);
QUICHE_LOG(INFO) << "Created stream: " << stream_id1;
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
visitor.Clear();
const std::string stream_frames =
TestFrameSequence()
.ServerPreface()
.Headers(1, {{":status", "100"}},
false)
.Ping(101)
.Headers(1,
{{":status", "200"},
{"server", "my-fake-server"},
{"date", "Tue, 6 Apr 2021 12:54:01 GMT"}},
true)
.Serialize();
EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0));
EXPECT_CALL(visitor, OnSettingsStart());
EXPECT_CALL(visitor, OnSettingsEnd());
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0));
EXPECT_CALL(visitor, OnPing(101, false));
EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5));
EXPECT_CALL(visitor, OnBeginHeadersForStream(1));
EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200"));
EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server"));
EXPECT_CALL(visitor,
OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"));
EXPECT_CALL(visitor, OnEndHeadersForStream(1));
EXPECT_CALL(visitor, OnEndStream(1));
EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR));
const int64_t stream_result = adapter->ProcessBytes(stream_frames);
EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result));
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG));
EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0));
EXPECT_TRUE(adapter->want_write());
result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_THAT(visitor.data(),
EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING}));
}
TEST(OgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kClient;
auto adapter = OgHttp2Adapter::Create(visitor, options);
EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(0, 10000);
EXPECT_EQ(adapter->GetReceiveWindowSize(),
kInitialFlowControlWindowSize + 10000);
const std::vector<Header> headers =
ToHeaders({{":method", "GET"},
{":scheme", "http"},
{":authority", "example.com"},
{":path", "/this/is/request/one"}});
const int32_t stream_id =
adapter->SubmitRequest(headers, nullptr, true, nullptr);
EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0));
EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0));
EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0));
EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _,
END_STREAM_FLAG | END_HEADERS_FLAG));
EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _,
END_STREAM_FLAG | END_HEADERS_FLAG, 0));
int result = adapter->Send();
EXPECT_EQ(0, result);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize);
adapter->SubmitWindowUpdate(1, 20000);
EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id),
kInitialFlowControlWindowSize + 20000);
}
TEST(OgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) {
TestVisitor visitor;
OgHttp2Adapter::Options options;
options.perspective = Perspective::kClient;
auto adapter = OgHttp2Adapter::Create(visitor, options);
testing::InSequence s;
const std::vector<Header> headers = |
414 | cpp | google/quiche | http2_frame_decoder | quiche/http2/decoder/http2_frame_decoder.cc | quiche/http2/decoder/http2_frame_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_HTTP2_FRAME_DECODER_H_
#define QUICHE_HTTP2_DECODER_HTTP2_FRAME_DECODER_H_
#include <stddef.h>
#include <cstdint>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/data_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/headers_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/priority_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/settings_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h"
#include "quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace test {
class Http2FrameDecoderPeer;
}
class QUICHE_EXPORT Http2FrameDecoder {
public:
explicit Http2FrameDecoder(Http2FrameDecoderListener* listener);
Http2FrameDecoder(const Http2FrameDecoder&) = delete;
Http2FrameDecoder& operator=(const Http2FrameDecoder&) = delete;
void set_listener(Http2FrameDecoderListener* listener);
Http2FrameDecoderListener* listener() const;
void set_maximum_payload_size(size_t v) { maximum_payload_size_ = v; }
size_t maximum_payload_size() const { return maximum_payload_size_; }
DecodeStatus DecodeFrame(DecodeBuffer* db);
bool IsDiscardingPayload() const { return state_ == State::kDiscardPayload; }
size_t remaining_payload() const;
uint32_t remaining_padding() const;
private:
enum class State {
kStartDecodingHeader,
kResumeDecodingHeader,
kResumeDecodingPayload,
kDiscardPayload,
};
friend class test::Http2FrameDecoderPeer;
QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& out, State v);
DecodeStatus StartDecodingPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(DecodeBuffer* db);
DecodeStatus DiscardPayload(DecodeBuffer* db);
const Http2FrameHeader& frame_header() const {
return frame_decoder_state_.frame_header();
}
void RetainFlags(uint8_t valid_flags);
void ClearFlags();
DecodeStatus StartDecodingAltSvcPayload(DecodeBuffer* db);
DecodeStatus StartDecodingContinuationPayload(DecodeBuffer* db);
DecodeStatus StartDecodingDataPayload(DecodeBuffer* db);
DecodeStatus StartDecodingGoAwayPayload(DecodeBuffer* db);
DecodeStatus StartDecodingHeadersPayload(DecodeBuffer* db);
DecodeStatus StartDecodingPingPayload(DecodeBuffer* db);
DecodeStatus StartDecodingPriorityPayload(DecodeBuffer* db);
DecodeStatus StartDecodingPriorityUpdatePayload(DecodeBuffer* db);
DecodeStatus StartDecodingPushPromisePayload(DecodeBuffer* db);
DecodeStatus StartDecodingRstStreamPayload(DecodeBuffer* db);
DecodeStatus StartDecodingSettingsPayload(DecodeBuffer* db);
DecodeStatus StartDecodingUnknownPayload(DecodeBuffer* db);
DecodeStatus StartDecodingWindowUpdatePayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingAltSvcPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingContinuationPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingDataPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingGoAwayPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingHeadersPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingPingPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingPriorityPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingPriorityUpdatePayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingPushPromisePayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingRstStreamPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingSettingsPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingUnknownPayload(DecodeBuffer* db);
DecodeStatus ResumeDecodingWindowUpdatePayload(DecodeBuffer* db);
FrameDecoderState frame_decoder_state_;
union {
AltSvcPayloadDecoder altsvc_payload_decoder_;
ContinuationPayloadDecoder continuation_payload_decoder_;
DataPayloadDecoder data_payload_decoder_;
GoAwayPayloadDecoder goaway_payload_decoder_;
HeadersPayloadDecoder headers_payload_decoder_;
PingPayloadDecoder ping_payload_decoder_;
PriorityPayloadDecoder priority_payload_decoder_;
PriorityUpdatePayloadDecoder priority_payload_update_decoder_;
PushPromisePayloadDecoder push_promise_payload_decoder_;
RstStreamPayloadDecoder rst_stream_payload_decoder_;
SettingsPayloadDecoder settings_payload_decoder_;
UnknownPayloadDecoder unknown_payload_decoder_;
WindowUpdatePayloadDecoder window_update_payload_decoder_;
};
State state_;
size_t maximum_payload_size_;
Http2FrameDecoderNoOpListener no_op_listener_;
};
}
#endif
#include "quiche/http2/decoder/http2_frame_decoder.h"
#include <ostream>
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out, Http2FrameDecoder::State v) {
switch (v) {
case Http2FrameDecoder::State::kStartDecodingHeader:
return out << "kStartDecodingHeader";
case Http2FrameDecoder::State::kResumeDecodingHeader:
return out << "kResumeDecodingHeader";
case Http2FrameDecoder::State::kResumeDecodingPayload:
return out << "kResumeDecodingPayload";
case Http2FrameDecoder::State::kDiscardPayload:
return out << "kDiscardPayload";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_155_1) << "Http2FrameDecoder::State " << unknown;
return out << "Http2FrameDecoder::State(" << unknown << ")";
}
Http2FrameDecoder::Http2FrameDecoder(Http2FrameDecoderListener* listener)
: state_(State::kStartDecodingHeader),
maximum_payload_size_(Http2SettingsInfo::DefaultMaxFrameSize()) {
set_listener(listener);
}
void Http2FrameDecoder::set_listener(Http2FrameDecoderListener* listener) {
if (listener == nullptr) {
listener = &no_op_listener_;
}
frame_decoder_state_.set_listener(listener);
}
Http2FrameDecoderListener* Http2FrameDecoder::listener() const {
return frame_decoder_state_.listener();
}
DecodeStatus Http2FrameDecoder::DecodeFrame(DecodeBuffer* db) {
QUICHE_DVLOG(2) << "Http2FrameDecoder::DecodeFrame state=" << state_;
switch (state_) {
case State::kStartDecodingHeader:
if (frame_decoder_state_.StartDecodingFrameHeader(db)) {
return StartDecodingPayload(db);
}
state_ = State::kResumeDecodingHeader;
return DecodeStatus::kDecodeInProgress;
case State::kResumeDecodingHeader:
if (frame_decoder_state_.ResumeDecodingFrameHeader(db)) {
return StartDecodingPayload(db);
}
return DecodeStatus::kDecodeInProgress;
case State::kResumeDecodingPayload:
return ResumeDecodingPayload(db);
case State::kDiscardPayload:
return DiscardPayload(db);
}
QUICHE_NOTREACHED();
return DecodeStatus::kDecodeError;
}
size_t Http2FrameDecoder::remaining_payload() const {
return frame_decoder_state_.remaining_payload();
}
uint32_t Http2FrameDecoder::remaining_padding() const {
return frame_decoder_state_.remaining_padding();
}
DecodeStatus Http2FrameDecoder::StartDecodingPayload(DecodeBuffer* db) {
const Http2FrameHeader& header = frame_header();
if (!listener()->OnFrameHeader(header)) {
QUICHE_DVLOG(2)
<< "OnFrameHeader rejected the frame, will discard; header: " << header;
state_ = State::kDiscardPayload;
frame_decoder_state_.InitializeRemainders();
return DecodeStatus::kDecodeError;
}
if (header.payload_length > maximum_payload_size_) {
QUICHE_DVLOG(2) << "Payload length is greater than allowed: "
<< header.payload_length << " > " << maximum_payload_size_
<< "\n header: " << header;
state_ = State::kDiscardPayload;
frame_decoder_state_.InitializeRemainders();
listener()->OnFrameSizeError(header);
return DecodeStatus::kDecodeError;
}
DecodeBufferSubset subset(db, header.payload_length);
DecodeStatus status;
switch (header.type) {
case Http2FrameType::DATA:
status = StartDecodingDataPayload(&subset);
break;
case Http2FrameType::HEADERS:
status = StartDecodingHeadersPayload(&subset);
break;
case Http2FrameType::PRIORITY:
status = StartDecodingPriorityPayload(&subset);
break;
case Http2FrameType::RST_STREAM:
status = StartDecodingRstStreamPayload(&subset);
break;
case Http2FrameType::SETTINGS:
status = StartDecodingSettingsPayload(&subset);
break;
case Http2FrameType::PUSH_PROMISE:
status = StartDecodingPushPromisePayload(&subset);
break;
case Http2FrameType::PING:
status = StartDecodingPingPayload(&subset);
break;
case Http2FrameType::GOAWAY:
status = StartDecodingGoAwayPayload(&subset);
break;
case Http2FrameType::WINDOW_UPDATE:
status = StartDecodingWindowUpdatePayload(&subset);
break;
case Http2FrameType::CONTINUATION:
status = StartDecodingContinuationPayload(&subset);
break;
case Http2FrameType::ALTSVC:
status = StartDecodingAltSvcPayload(&subset);
break;
case Http2FrameType::PRIORITY_UPDATE:
status = StartDecodingPriorityUpdatePayload(&subset);
break;
default:
status = StartDecodingUnknownPayload(&subset);
break;
}
if (status == DecodeStatus::kDecodeDone) {
state_ = State::kStartDecodingHeader;
return status;
} else if (status == DecodeStatus::kDecodeInProgress) {
state_ = State::kResumeDecodingPayload;
return status;
} else {
state_ = State::kDiscardPayload;
return status;
}
}
DecodeStatus Http2FrameDecoder::ResumeDecodingPayload(DecodeBuffer* db) {
size_t remaining = frame_decoder_state_.remaining_total_payload();
QUICHE_DCHECK_LE(remaining, frame_header().payload_length);
DecodeBufferSubset subset(db, remaining);
DecodeStatus status;
switch (frame_header().type) {
case Http2FrameType::DATA:
status = ResumeDecodingDataPayload(&subset);
break;
case Http2FrameType::HEADERS:
status = ResumeDecodingHeadersPayload(&subset);
break;
case Http2FrameType::PRIORITY:
status = ResumeDecodingPriorityPayload(&subset);
break;
case Http2FrameType::RST_STREAM:
status = ResumeDecodingRstStreamPayload(&subset);
break;
case Http2FrameType::SETTINGS:
status = ResumeDecodingSettingsPayload(&subset);
break;
case Http2FrameType::PUSH_PROMISE:
status = ResumeDecodingPushPromisePayload(&subset);
break;
case Http2FrameType::PING:
status = ResumeDecodingPingPayload(&subset);
break;
case Http2FrameType::GOAWAY:
status = ResumeDecodingGoAwayPayload(&subset);
break;
case Http2FrameType::WINDOW_UPDATE:
status = ResumeDecodingWindowUpdatePayload(&subset);
break;
case Http2FrameType::CONTINUATION:
status = ResumeDecodingContinuationPayload(&subset);
break;
case Http2FrameType::ALTSVC:
status = ResumeDecodingAltSvcPayload(&subset);
break;
case Http2FrameType::PRIORITY_UPDATE:
status = ResumeDecodingPriorityUpdatePayload(&subset);
break;
default:
status = ResumeDecodingUnknownPayload(&subset);
break;
}
if (status == DecodeStatus::kDecodeDone) {
state_ = State::kStartDecodingHeader;
return status;
} else if (status == DecodeStatus::kDecodeInProgress) {
return status;
} else {
state_ = State::kDiscardPayload;
return status;
}
}
void Http2FrameDecoder::RetainFlags(uint8_t valid_flags) {
frame_decoder_state_.RetainFlags(valid_flags);
}
void Http2FrameDecoder::ClearFlags() { frame_decoder_state_.ClearFlags(); }
DecodeStatus Http2FrameDecoder::StartDecodingAltSvcPayload(DecodeBuffer* db) {
ClearFlags();
return altsvc_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingAltSvcPayload(DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return altsvc_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingContinuationPayload(
DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::END_HEADERS);
return continuation_payload_decoder_.StartDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingContinuationPayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return continuation_payload_decoder_.ResumeDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingDataPayload(DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED);
return data_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingDataPayload(DecodeBuffer* db) {
return data_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingGoAwayPayload(DecodeBuffer* db) {
ClearFlags();
return goaway_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingGoAwayPayload(DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return goaway_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingHeadersPayload(DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS |
Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY);
return headers_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingHeadersPayload(DecodeBuffer* db) {
QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(),
frame_header().payload_length);
return headers_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingPingPayload(DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::ACK);
return ping_payload_decoder_.StartDecodingPayload(&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingPingPayload(DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return ping_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingPriorityPayload(DecodeBuffer* db) {
ClearFlags();
return priority_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingPriorityPayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return priority_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingPriorityUpdatePayload(
DecodeBuffer* db) {
ClearFlags();
return priority_payload_update_decoder_.StartDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingPriorityUpdatePayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return priority_payload_update_decoder_.ResumeDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingPushPromisePayload(
DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED);
return push_promise_payload_decoder_.StartDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingPushPromisePayload(
DecodeBuffer* db) {
QUICHE_DCHECK_LE(frame_decoder_state_.remaining_payload_and_padding(),
frame_header().payload_length);
return push_promise_payload_decoder_.ResumeDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingRstStreamPayload(
DecodeBuffer* db) {
ClearFlags();
return rst_stream_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingRstStreamPayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return rst_stream_payload_decoder_.ResumeDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::StartDecodingSettingsPayload(DecodeBuffer* db) {
RetainFlags(Http2FrameFlag::ACK);
return settings_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingSettingsPayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return settings_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingUnknownPayload(DecodeBuffer* db) {
return unknown_payload_decoder_.StartDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingUnknownPayload(DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return unknown_payload_decoder_.ResumeDecodingPayload(&frame_decoder_state_,
db);
}
DecodeStatus Http2FrameDecoder::StartDecodingWindowUpdatePayload(
DecodeBuffer* db) {
ClearFlags();
return window_update_payload_decoder_.StartDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::ResumeDecodingWindowUpdatePayload(
DecodeBuffer* db) {
QUICHE_DCHECK_EQ(frame_decoder_state_.remaining_total_payload(),
frame_decoder_state_.remaining_payload());
return window_update_payload_decoder_.ResumeDecodingPayload(
&frame_decoder_state_, db);
}
DecodeStatus Http2FrameDecoder::DiscardPayload(DecodeBuffer* db) {
QUICHE_DVLOG(2) << "remaining_payload="
<< frame_decoder_state_.remaining_payload_
<< "; remaining_padding="
<< frame_decoder_state_.remaining_padding_;
frame_decoder_state_.remaining_payload_ +=
frame_decoder_state_.remaining_padding_;
frame_decoder_state_.remaining_padding_ = 0;
const size_t avail = frame_decoder_state_.AvailablePayload(db);
QUICHE_DVLOG(2) << "avail=" << avail;
if (avail > 0) {
frame_decoder_state_.ConsumePayload(avail);
db->AdvanceCursor(avail);
}
if (frame_decoder_state_.remaining_payload_ == 0) {
state_ = State::kStartDecodingHeader;
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
}
} | #include "quiche/http2/decoder/http2_frame_decoder.h"
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector_listener.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
class Http2FrameDecoderPeer {
public:
static size_t remaining_total_payload(Http2FrameDecoder* decoder) {
return decoder->frame_decoder_state_.remaining_total_payload();
}
};
namespace {
class Http2FrameDecoderTest : public RandomDecoderTest {
protected:
DecodeStatus StartDecoding(DecodeBuffer* db) override {
QUICHE_DVLOG(2) << "StartDecoding, db->Remaining=" << db->Remaining();
collector_.Reset();
PrepareDecoder();
DecodeStatus status = decoder_->DecodeFrame(db);
if (status != DecodeStatus::kDecodeInProgress) {
++fast_decode_count_;
if (status == DecodeStatus::kDecodeError) {
ConfirmDiscardsRemainingPayload();
}
}
return status;
}
DecodeStatus ResumeDecoding(DecodeBuffer* db) override {
QUICHE_DVLOG(2) << "ResumeDecoding, db->Remaining=" << db->Remaining();
DecodeStatus status = decoder_->DecodeFrame(db);
if (status != DecodeStatus::kDecodeInProgress) {
++slow_decode_count_;
if (status == DecodeStatus::kDecodeError) {
ConfirmDiscardsRemainingPayload();
}
}
return status;
}
void ConfirmDiscardsRemainingPayload() {
ASSERT_TRUE(decoder_->IsDiscardingPayload());
size_t remaining =
Http2FrameDecoderPeer::remaining_total_payload(decoder_.get());
size_t extra = 10;
std::string junk(remaining + extra, '0');
DecodeBuffer tmp(junk);
EXPECT_EQ(DecodeStatus::kDecodeDone, decoder_->DecodeFrame(&tmp));
EXPECT_EQ(remaining, tmp.Offset());
EXPECT_EQ(extra, tmp.Remaining());
EXPECT_FALSE(decoder_->IsDiscardingPayload());
}
void PrepareDecoder() {
decoder_ = std::make_unique<Http2FrameDecoder>(&collector_);
decoder_->set_maximum_payload_size(maximum_payload_size_);
}
void ResetDecodeSpeedCounters() {
fast_decode_count_ = 0;
slow_decode_count_ = 0;
}
AssertionResult VerifyCollected(const FrameParts& expected) {
HTTP2_VERIFY_FALSE(collector_.IsInProgress());
HTTP2_VERIFY_EQ(1u, collector_.size());
return expected.VerifyEquals(*collector_.frame(0));
}
AssertionResult DecodePayloadAndValidateSeveralWays(absl::string_view payload,
Validator validator) {
DecodeBuffer db(payload);
bool start_decoding_requires_non_empty = false;
return DecodeAndValidateSeveralWays(&db, start_decoding_requires_non_empty,
validator);
}
AssertionResult DecodePayloadAndValidateSeveralWays(
absl::string_view payload, const FrameParts& expected) {
auto validator = [&expected, this](const DecodeBuffer& ,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);
return VerifyCollected(expected);
};
ResetDecodeSpeedCounters();
HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays(
payload, ValidateDoneAndEmpty(validator)));
HTTP2_VERIFY_GT(fast_decode_count_, 0u);
HTTP2_VERIFY_GT(slow_decode_count_, 0u);
std::string next_frame = Random().RandString(10);
std::string input(payload.data(), payload.size());
input += next_frame;
ResetDecodeSpeedCounters();
HTTP2_VERIFY_SUCCESS(DecodePayloadAndValidateSeveralWays(
payload, ValidateDoneAndOffset(payload.size(), validator)));
HTTP2_VERIFY_GT(fast_decode_count_, 0u);
HTTP2_VERIFY_GT(slow_decode_count_, 0u);
return AssertionSuccess();
}
template <size_t N>
AssertionResult DecodePayloadAndValidateSeveralWays(
const char (&buf)[N], const FrameParts& expected) {
return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N),
expected);
}
template <size_t N>
AssertionResult DecodePayloadAndValidateSeveralWays(
const char (&buf)[N], const Http2FrameHeader& header) {
return DecodePayloadAndValidateSeveralWays(absl::string_view(buf, N),
FrameParts(header));
}
template <size_t N>
AssertionResult DecodePayloadExpectingError(const char (&buf)[N],
const FrameParts& expected) {
auto validator = [&expected, this](const DecodeBuffer& ,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeError);
return VerifyCollected(expected);
};
ResetDecodeSpeedCounters();
EXPECT_TRUE(
DecodePayloadAndValidateSeveralWays(ToStringPiece(buf), validator));
EXPECT_GT(fast_decode_count_, 0u);
EXPECT_GT(slow_decode_count_, 0u);
return AssertionSuccess();
}
template <size_t N>
AssertionResult DecodePayloadExpectingFrameSizeError(const char (&buf)[N],
FrameParts expected) {
expected.SetHasFrameSizeError(true);
return DecodePayloadExpectingError(buf, expected);
}
template <size_t N>
AssertionResult DecodePayloadExpectingFrameSizeError(
const char (&buf)[N], const Http2FrameHeader& header) {
return DecodePayloadExpectingFrameSizeError(buf, FrameParts(header));
}
size_t fast_decode_count_ = 0;
size_t slow_decode_count_ = 0;
uint32_t maximum_payload_size_ = Http2SettingsInfo::DefaultMaxFrameSize();
FramePartsCollectorListener collector_;
std::unique_ptr<Http2FrameDecoder> decoder_;
};
TEST_F(Http2FrameDecoderTest, DataEmpty) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x00',
'\x00',
'\x00', '\x00', '\x00',
'\x00',
};
Http2FrameHeader header(0, Http2FrameType::DATA, 0, 0);
FrameParts expected(header, "");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeadersEmpty) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x01',
'\x00',
'\x00', '\x00', '\x00', '\x01',
};
Http2FrameHeader header(0, Http2FrameType::HEADERS, 0, 1);
FrameParts expected(header, "");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, Priority) {
const char kFrameData[] = {
'\x00', '\x00', '\x05',
'\x02',
'\x00',
'\x00', '\x00', '\x00', '\x02',
'\x80', '\x00', '\x00', '\x01',
'\x10',
};
Http2FrameHeader header(5, Http2FrameType::PRIORITY, 0, 2);
FrameParts expected(header);
expected.SetOptPriority(Http2PriorityFields(1, 17, true));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, RstStream) {
const char kFrameData[] = {
'\x00', '\x00', '\x04',
'\x03',
'\x00',
'\x00', '\x00', '\x00', '\x01',
'\x00', '\x00', '\x00', '\x01',
};
Http2FrameHeader header(4, Http2FrameType::RST_STREAM, 0, 1);
FrameParts expected(header);
expected.SetOptRstStreamErrorCode(Http2ErrorCode::PROTOCOL_ERROR);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, SettingsEmpty) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x04',
'\x00',
'\x00', '\x00', '\x00', '\x01',
};
Http2FrameHeader header(0, Http2FrameType::SETTINGS, 0, 1);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, SettingsAck) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x04',
'\x01',
'\x00', '\x00', '\x00', '\x00',
};
Http2FrameHeader header(0, Http2FrameType::SETTINGS, Http2FrameFlag::ACK, 0);
FrameParts expected(header);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PushPromiseMinimal) {
const char kFrameData[] = {
'\x00', '\x00', '\x04',
'\x05',
'\x04',
'\x00', '\x00', '\x00',
'\x02',
'\x00', '\x00', '\x00',
'\x01',
};
Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE,
Http2FrameFlag::END_HEADERS, 2);
FrameParts expected(header, "");
expected.SetOptPushPromise(Http2PushPromiseFields{1});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, Ping) {
const char kFrameData[] = {
'\x00', '\x00', '\x08',
'\x06',
'\xfe',
'\x00', '\x00', '\x00', '\x00',
's', 'o', 'm', 'e',
'd', 'a', 't', 'a',
};
Http2FrameHeader header(8, Http2FrameType::PING, 0, 0);
FrameParts expected(header);
expected.SetOptPing(
Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PingAck) {
const char kFrameData[] = {
'\x00', '\x00', '\x08',
'\x06',
'\xff',
'\x00', '\x00', '\x00', '\x00',
's', 'o', 'm', 'e',
'd', 'a', 't', 'a',
};
Http2FrameHeader header(8, Http2FrameType::PING, Http2FrameFlag::ACK, 0);
FrameParts expected(header);
expected.SetOptPing(
Http2PingFields{{'s', 'o', 'm', 'e', 'd', 'a', 't', 'a'}});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, GoAwayMinimal) {
const char kFrameData[] = {
'\x00', '\x00', '\x08',
'\x07',
'\xff',
'\x00', '\x00', '\x00', '\x01',
'\x80', '\x00', '\x00', '\xff',
'\x00', '\x00', '\x00', '\x09',
};
Http2FrameHeader header(8, Http2FrameType::GOAWAY, 0, 1);
FrameParts expected(header);
expected.SetOptGoaway(
Http2GoAwayFields(255, Http2ErrorCode::COMPRESSION_ERROR));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, WindowUpdate) {
const char kFrameData[] = {
'\x00', '\x00', '\x04',
'\x08',
'\x0f',
'\x00', '\x00', '\x00', '\x01',
'\x80', '\x00', '\x04', '\x00',
};
Http2FrameHeader header(4, Http2FrameType::WINDOW_UPDATE, 0, 1);
FrameParts expected(header);
expected.SetOptWindowUpdateIncrement(1024);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, ContinuationEmpty) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x09',
'\x00',
'\x00', '\x00', '\x00',
'\x00',
};
Http2FrameHeader header(0, Http2FrameType::CONTINUATION, 0, 0);
FrameParts expected(header);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, AltSvcMinimal) {
const char kFrameData[] = {
'\x00', '\x00', '\x02',
'\x0a',
'\xff',
'\x00', '\x00', '\x00',
'\x00',
'\x00', '\x00',
};
Http2FrameHeader header(2, Http2FrameType::ALTSVC, 0, 0);
FrameParts expected(header);
expected.SetOptAltsvcOriginLength(0);
expected.SetOptAltsvcValueLength(0);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, UnknownEmpty) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x20',
'\xff',
'\x00', '\x00', '\x00', '\x00',
};
Http2FrameHeader header(0, static_cast<Http2FrameType>(32), 0xff, 0);
FrameParts expected(header);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, DataPayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x03',
'\x00',
'\x80',
'\x00', '\x00', '\x02', '\x02',
'a', 'b', 'c',
};
Http2FrameHeader header(3, Http2FrameType::DATA, 0, 514);
FrameParts expected(header, "abc");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeadersPayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x03',
'\x01',
'\x05',
'\x00', '\x00', '\x00', '\x02',
'a', 'b', 'c',
};
Http2FrameHeader header(
3, Http2FrameType::HEADERS,
Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS, 2);
FrameParts expected(header, "abc");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeadersPriority) {
const char kFrameData[] = {
'\x00', '\x00', '\x05',
'\x01',
'\x20',
'\x00', '\x00', '\x00', '\x02',
'\x00', '\x00', '\x00', '\x01',
'\xff',
};
Http2FrameHeader header(5, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY,
2);
FrameParts expected(header);
expected.SetOptPriority(Http2PriorityFields(1, 256, false));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, Settings) {
const char kFrameData[] = {
'\x00', '\x00', '\x0c',
'\x04',
'\x00',
'\x00', '\x00', '\x00', '\x00',
'\x00', '\x04',
'\x0a', '\x0b', '\x0c', '\x0d',
'\x00', '\x02',
'\x00', '\x00', '\x00', '\x03',
};
Http2FrameHeader header(12, Http2FrameType::SETTINGS, 0, 0);
FrameParts expected(header);
expected.AppendSetting(Http2SettingFields(
Http2SettingsParameter::INITIAL_WINDOW_SIZE, 168496141));
expected.AppendSetting(
Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PushPromisePayload) {
const char kFrameData[] = {
'\x00', '\x00', 7,
'\x05',
'\x04',
'\x00', '\x00', '\x00', '\xff',
'\x00', '\x00', '\x01', '\x00',
'a', 'b', 'c',
};
Http2FrameHeader header(7, Http2FrameType::PUSH_PROMISE,
Http2FrameFlag::END_HEADERS, 255);
FrameParts expected(header, "abc");
expected.SetOptPushPromise(Http2PushPromiseFields{256});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, GoAwayOpaqueData) {
const char kFrameData[] = {
'\x00', '\x00', '\x0e',
'\x07',
'\xff',
'\x80', '\x00', '\x00', '\x00',
'\x00', '\x00', '\x01', '\x00',
'\x00', '\x00', '\x00', '\x03',
'o', 'p', 'a', 'q', 'u', 'e',
};
Http2FrameHeader header(14, Http2FrameType::GOAWAY, 0, 0);
FrameParts expected(header, "opaque");
expected.SetOptGoaway(
Http2GoAwayFields(256, Http2ErrorCode::FLOW_CONTROL_ERROR));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, ContinuationPayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x03',
'\x09',
'\xff',
'\x00', '\x00', '\x00', '\x02',
'a', 'b', 'c',
};
Http2FrameHeader header(3, Http2FrameType::CONTINUATION,
Http2FrameFlag::END_HEADERS, 2);
FrameParts expected(header, "abc");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, AltSvcPayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x08',
'\x0a',
'\x00',
'\x00', '\x00', '\x00', '\x02',
'\x00', '\x03',
'a', 'b', 'c',
'd', 'e', 'f',
};
Http2FrameHeader header(8, Http2FrameType::ALTSVC, 0, 2);
FrameParts expected(header);
expected.SetAltSvcExpected("abc", "def");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PriorityUpdatePayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x07',
'\x10',
'\x00',
'\x00', '\x00', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x05',
'a', 'b', 'c',
};
Http2FrameHeader header(7, Http2FrameType::PRIORITY_UPDATE, 0, 0);
FrameParts expected(header, "abc");
expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{5});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, UnknownPayload) {
const char kFrameData[] = {
'\x00', '\x00', '\x03',
'\x30',
'\x00',
'\x00', '\x00', '\x00', '\x02',
'a', 'b', 'c',
};
Http2FrameHeader header(3, static_cast<Http2FrameType>(48), 0, 2);
FrameParts expected(header, "abc");
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, DataPayloadAndPadding) {
const char kFrameData[] = {
'\x00', '\x00', '\x07',
'\x00',
'\x09',
'\x00', '\x00', '\x00', '\x02',
'\x03',
'a', 'b', 'c',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(7, Http2FrameType::DATA,
Http2FrameFlag::END_STREAM | Http2FrameFlag::PADDED,
2);
size_t total_pad_length = 4;
FrameParts expected(header, "abc", total_pad_length);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeadersPayloadAndPadding) {
const char kFrameData[] = {
'\x00', '\x00', '\x07',
'\x01',
'\x08',
'\x00', '\x00', '\x00', '\x02',
'\x03',
'a', 'b', 'c',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(7, Http2FrameType::HEADERS, Http2FrameFlag::PADDED,
2);
size_t total_pad_length = 4;
FrameParts expected(header, "abc", total_pad_length);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeadersPayloadPriorityAndPadding) {
const char kFrameData[] = {
'\x00', '\x00', '\x0c',
'\x01',
'\xff',
'\x00', '\x00', '\x00', '\x02',
'\x03',
'\x80', '\x00', '\x00', '\x01',
'\x10',
'a', 'b', 'c',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(12, Http2FrameType::HEADERS,
Http2FrameFlag::END_STREAM |
Http2FrameFlag::END_HEADERS |
Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY,
2);
size_t total_pad_length = 4;
FrameParts expected(header, "abc", total_pad_length);
expected.SetOptPriority(Http2PriorityFields(1, 17, true));
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PushPromisePayloadAndPadding) {
const char kFrameData[] = {
'\x00', '\x00', 11,
'\x05',
'\xff',
'\x00', '\x00', '\x00', '\x01',
'\x03',
'\x00', '\x00', '\x00', '\x02',
'a', 'b', 'c',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(11, Http2FrameType::PUSH_PROMISE,
Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED,
1);
size_t total_pad_length = 4;
FrameParts expected(header, "abc", total_pad_length);
expected.SetOptPushPromise(Http2PushPromiseFields{2});
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, DataMissingPadLengthField) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x00',
'\x08',
'\x00', '\x00', '\x00', '\x01',
};
Http2FrameHeader header(0, Http2FrameType::DATA, Http2FrameFlag::PADDED, 1);
FrameParts expected(header);
expected.SetOptMissingLength(1);
EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeaderPaddingTooLong) {
const char kFrameData[] = {
'\x00', '\x00', '\x02',
'\x01',
'\x08',
'\x00', '\x01', '\x00', '\x00',
'\xff',
'\x00',
};
Http2FrameHeader header(2, Http2FrameType::HEADERS, Http2FrameFlag::PADDED,
65536);
FrameParts expected(header);
expected.SetOptMissingLength(254);
EXPECT_TRUE(DecodePayloadExpectingError(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, HeaderMissingPriority) {
const char kFrameData[] = {
'\x00', '\x00', '\x04',
'\x01',
'\x20',
'\x00', '\x01', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00',
};
Http2FrameHeader header(4, Http2FrameType::HEADERS, Http2FrameFlag::PRIORITY,
65536);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, PriorityTooShort) {
const char kFrameData[] = {
'\x00', '\x00', '\x04',
'\x02',
'\x00',
'\x00', '\x00', '\x00', '\x02',
'\x80', '\x00', '\x00', '\x01',
};
Http2FrameHeader header(4, Http2FrameType::PRIORITY, 0, 2);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, RstStreamTooShort) {
const char kFrameData[] = {
'\x00', '\x00', '\x03',
'\x03',
'\x00',
'\x00', '\x00', '\x00', '\x01',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(3, Http2FrameType::RST_STREAM, 0, 1);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, SettingsWrongSize) {
const char kFrameData[] = {
'\x00', '\x00', '\x09',
'\x04',
'\x00',
'\x00', '\x00', '\x00', '\x00',
'\x00', '\x02',
'\x00', '\x00', '\x00', '\x03',
'\x00', '\x04',
'\x00',
};
Http2FrameHeader header(9, Http2FrameType::SETTINGS, 0, 0);
FrameParts expected(header);
expected.AppendSetting(
Http2SettingFields(Http2SettingsParameter::ENABLE_PUSH, 3));
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, expected));
}
TEST_F(Http2FrameDecoderTest, PushPromiseTooShort) {
const char kFrameData[] = {
'\x00', '\x00', 3,
'\x05',
'\x00',
'\x00', '\x00', '\x00', '\x01',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(3, Http2FrameType::PUSH_PROMISE, 0, 1);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, PushPromisePaddedTruncatedPromise) {
const char kFrameData[] = {
'\x00', '\x00', 4,
'\x05',
'\x08',
'\x00', '\x00', '\x00', '\x01',
'\x00',
'\x00', '\x00', '\x00',
};
Http2FrameHeader header(4, Http2FrameType::PUSH_PROMISE,
Http2FrameFlag::PADDED, 1);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, PingTooShort) {
const char kFrameData[] = {
'\x00', '\x00', '\x07',
'\x06',
'\xfe',
'\x00', '\x00', '\x00', '\x00',
's', 'o', 'm', 'e',
'd', 'a', 't',
};
Http2FrameHeader header(7, Http2FrameType::PING, 0, 0);
EXPECT_TRUE(DecodePayloadExpectingFrameSizeError(kFrameData, header));
}
TEST_F(Http2FrameDecoderTest, GoAwayTooShort) {
const char kFrameData[] = {
'\x00', '\x00', '\x00',
'\x07',
'\xff',
'\x00', '\x00', '\x00', '\x00',
};
Http2FrameHeader header(0, |
415 | cpp | google/quiche | decode_buffer | quiche/http2/decoder/decode_buffer.cc | quiche/http2/decoder/decode_buffer_test.cc | #ifndef QUICHE_HTTP2_DECODER_DECODE_BUFFER_H_
#define QUICHE_HTTP2_DECODER_DECODE_BUFFER_H_
#include <stddef.h>
#include <algorithm>
#include <cstdint>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
class DecodeBufferSubset;
class QUICHE_EXPORT DecodeBuffer {
public:
static constexpr size_t kMaxDecodeBufferLength = 1 << 25;
DecodeBuffer(const char* buffer, size_t len)
: buffer_(buffer), cursor_(buffer), beyond_(buffer + len) {
QUICHE_DCHECK(buffer != nullptr);
QUICHE_DCHECK_LE(len, kMaxDecodeBufferLength);
}
explicit DecodeBuffer(absl::string_view s)
: DecodeBuffer(s.data(), s.size()) {}
template <size_t N>
explicit DecodeBuffer(const char (&buf)[N]) : DecodeBuffer(buf, N) {}
DecodeBuffer(const DecodeBuffer&) = delete;
DecodeBuffer operator=(const DecodeBuffer&) = delete;
bool Empty() const { return cursor_ >= beyond_; }
bool HasData() const { return cursor_ < beyond_; }
size_t Remaining() const {
QUICHE_DCHECK_LE(cursor_, beyond_);
return beyond_ - cursor_;
}
size_t Offset() const { return cursor_ - buffer_; }
size_t FullSize() const { return beyond_ - buffer_; }
size_t MinLengthRemaining(size_t length) const {
return std::min(length, Remaining());
}
const char* cursor() const { return cursor_; }
void AdvanceCursor(size_t amount) {
QUICHE_DCHECK_LE(amount,
Remaining());
QUICHE_DCHECK_EQ(subset_, nullptr)
<< "Access via subset only when present.";
cursor_ += amount;
}
char DecodeChar() {
QUICHE_DCHECK_LE(1u, Remaining());
QUICHE_DCHECK_EQ(subset_, nullptr)
<< "Access via subset only when present.";
return *cursor_++;
}
uint8_t DecodeUInt8();
uint16_t DecodeUInt16();
uint32_t DecodeUInt24();
uint32_t DecodeUInt31();
uint32_t DecodeUInt32();
protected:
#ifndef NDEBUG
void set_subset_of_base(DecodeBuffer* base, const DecodeBufferSubset* subset);
void clear_subset_of_base(DecodeBuffer* base,
const DecodeBufferSubset* subset);
#endif
private:
#ifndef NDEBUG
void set_subset(const DecodeBufferSubset* subset);
void clear_subset(const DecodeBufferSubset* subset);
#endif
static void* operator new(size_t s);
static void* operator new[](size_t s);
static void operator delete(void* p);
static void operator delete[](void* p);
const char* const buffer_;
const char* cursor_;
const char* const beyond_;
const DecodeBufferSubset* subset_ = nullptr;
};
class QUICHE_EXPORT DecodeBufferSubset : public DecodeBuffer {
public:
DecodeBufferSubset(DecodeBuffer* base, size_t subset_len)
: DecodeBuffer(base->cursor(), base->MinLengthRemaining(subset_len)),
base_buffer_(base) {
#ifndef NDEBUG
DebugSetup();
#endif
}
DecodeBufferSubset(const DecodeBufferSubset&) = delete;
DecodeBufferSubset operator=(const DecodeBufferSubset&) = delete;
~DecodeBufferSubset() {
size_t offset = Offset();
#ifndef NDEBUG
DebugTearDown();
#endif
base_buffer_->AdvanceCursor(offset);
}
private:
DecodeBuffer* const base_buffer_;
#ifndef NDEBUG
size_t start_base_offset_;
size_t max_base_offset_;
void DebugSetup();
void DebugTearDown();
#endif
};
}
#endif
#include "quiche/http2/decoder/decode_buffer.h"
namespace http2 {
uint8_t DecodeBuffer::DecodeUInt8() {
return static_cast<uint8_t>(DecodeChar());
}
uint16_t DecodeBuffer::DecodeUInt16() {
QUICHE_DCHECK_LE(2u, Remaining());
const uint8_t b1 = DecodeUInt8();
const uint8_t b2 = DecodeUInt8();
return b1 << 8 | b2;
}
uint32_t DecodeBuffer::DecodeUInt24() {
QUICHE_DCHECK_LE(3u, Remaining());
const uint8_t b1 = DecodeUInt8();
const uint8_t b2 = DecodeUInt8();
const uint8_t b3 = DecodeUInt8();
return b1 << 16 | b2 << 8 | b3;
}
uint32_t DecodeBuffer::DecodeUInt31() {
QUICHE_DCHECK_LE(4u, Remaining());
const uint8_t b1 = DecodeUInt8() & 0x7f;
const uint8_t b2 = DecodeUInt8();
const uint8_t b3 = DecodeUInt8();
const uint8_t b4 = DecodeUInt8();
return b1 << 24 | b2 << 16 | b3 << 8 | b4;
}
uint32_t DecodeBuffer::DecodeUInt32() {
QUICHE_DCHECK_LE(4u, Remaining());
const uint8_t b1 = DecodeUInt8();
const uint8_t b2 = DecodeUInt8();
const uint8_t b3 = DecodeUInt8();
const uint8_t b4 = DecodeUInt8();
return b1 << 24 | b2 << 16 | b3 << 8 | b4;
}
#ifndef NDEBUG
void DecodeBuffer::set_subset_of_base(DecodeBuffer* base,
const DecodeBufferSubset* subset) {
QUICHE_DCHECK_EQ(this, subset);
base->set_subset(subset);
}
void DecodeBuffer::clear_subset_of_base(DecodeBuffer* base,
const DecodeBufferSubset* subset) {
QUICHE_DCHECK_EQ(this, subset);
base->clear_subset(subset);
}
void DecodeBuffer::set_subset(const DecodeBufferSubset* subset) {
QUICHE_DCHECK(subset != nullptr);
QUICHE_DCHECK_EQ(subset_, nullptr) << "There is already a subset";
subset_ = subset;
}
void DecodeBuffer::clear_subset(const DecodeBufferSubset* subset) {
QUICHE_DCHECK(subset != nullptr);
QUICHE_DCHECK_EQ(subset_, subset);
subset_ = nullptr;
}
void DecodeBufferSubset::DebugSetup() {
start_base_offset_ = base_buffer_->Offset();
max_base_offset_ = start_base_offset_ + FullSize();
QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize());
set_subset_of_base(base_buffer_, this);
}
void DecodeBufferSubset::DebugTearDown() {
QUICHE_DCHECK_EQ(start_base_offset_, base_buffer_->Offset())
<< "The base buffer was modified";
size_t offset = Offset();
QUICHE_DCHECK_LE(offset, FullSize());
QUICHE_DCHECK_LE(start_base_offset_ + offset, max_base_offset_);
QUICHE_DCHECK_LE(max_base_offset_, base_buffer_->FullSize());
clear_subset_of_base(base_buffer_, this);
}
#endif
} | #include "quiche/http2/decoder/decode_buffer.h"
#include <functional>
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
enum class TestEnumClass32 {
kValue1 = 1,
kValue99 = 99,
kValue1M = 1000000,
};
enum class TestEnumClass8 {
kValue1 = 1,
kValue2 = 1,
kValue99 = 99,
kValue255 = 255,
};
enum TestEnum8 {
kMaskLo = 0x01,
kMaskHi = 0x80,
};
struct TestStruct {
uint8_t f1;
uint16_t f2;
uint32_t f3;
uint32_t f4;
uint32_t f5;
TestEnumClass32 f6;
TestEnumClass8 f7;
TestEnum8 f8;
};
class DecodeBufferTest : public quiche::test::QuicheTest {
protected:
Http2Random random_;
uint32_t decode_offset_;
};
TEST_F(DecodeBufferTest, DecodesFixedInts) {
const char data[] = "\x01\x12\x23\x34\x45\x56\x67\x78\x89\x9a";
DecodeBuffer b1(data, strlen(data));
EXPECT_EQ(1, b1.DecodeUInt8());
EXPECT_EQ(0x1223u, b1.DecodeUInt16());
EXPECT_EQ(0x344556u, b1.DecodeUInt24());
EXPECT_EQ(0x6778899Au, b1.DecodeUInt32());
}
TEST_F(DecodeBufferTest, HasNotCopiedInput) {
const char data[] = "ab";
DecodeBuffer b1(data, 2);
EXPECT_EQ(2u, b1.Remaining());
EXPECT_EQ(0u, b1.Offset());
EXPECT_FALSE(b1.Empty());
EXPECT_EQ(data, b1.cursor());
EXPECT_TRUE(b1.HasData());
b1.AdvanceCursor(1);
EXPECT_EQ(1u, b1.Remaining());
EXPECT_EQ(1u, b1.Offset());
EXPECT_FALSE(b1.Empty());
EXPECT_EQ(&data[1], b1.cursor());
EXPECT_TRUE(b1.HasData());
b1.AdvanceCursor(1);
EXPECT_EQ(0u, b1.Remaining());
EXPECT_EQ(2u, b1.Offset());
EXPECT_TRUE(b1.Empty());
EXPECT_EQ(&data[2], b1.cursor());
EXPECT_FALSE(b1.HasData());
DecodeBuffer b2(data, 0);
EXPECT_EQ(0u, b2.Remaining());
EXPECT_EQ(0u, b2.Offset());
EXPECT_TRUE(b2.Empty());
EXPECT_EQ(data, b2.cursor());
EXPECT_FALSE(b2.HasData());
}
TEST_F(DecodeBufferTest, DecodeBufferSubsetLimited) {
const char data[] = "abc";
DecodeBuffer base(data, 3);
base.AdvanceCursor(1);
DecodeBufferSubset subset(&base, 100);
EXPECT_EQ(2u, subset.FullSize());
}
TEST_F(DecodeBufferTest, DecodeBufferSubsetAdvancesCursor) {
const char data[] = "abc";
const size_t size = sizeof(data) - 1;
EXPECT_EQ(3u, size);
DecodeBuffer base(data, size);
{
DecodeBufferSubset subset(&base, size + 100);
EXPECT_EQ(size, subset.FullSize());
EXPECT_EQ(base.FullSize(), subset.FullSize());
EXPECT_EQ(0u, subset.Offset());
}
EXPECT_EQ(0u, base.Offset());
EXPECT_EQ(size, base.Remaining());
}
#if GTEST_HAS_DEATH_TEST && !defined(NDEBUG)
TEST(DecodeBufferDeathTest, NonNullBufferRequired) {
EXPECT_QUICHE_DEBUG_DEATH({ DecodeBuffer b(nullptr, 3); }, "nullptr");
}
TEST(DecodeBufferDeathTest, ModestBufferSizeRequired) {
EXPECT_QUICHE_DEBUG_DEATH(
{
constexpr size_t kLength = DecodeBuffer::kMaxDecodeBufferLength + 1;
auto data = std::make_unique<char[]>(kLength);
DecodeBuffer b(data.get(), kLength);
},
"Max.*Length");
}
TEST(DecodeBufferDeathTest, LimitedAdvance) {
{
const char data[] = "abc";
DecodeBuffer b(data, 3);
b.AdvanceCursor(3);
EXPECT_TRUE(b.Empty());
}
EXPECT_QUICHE_DEBUG_DEATH(
{
const char data[] = "abc";
DecodeBuffer b(data, 3);
b.AdvanceCursor(4);
},
"Remaining");
}
TEST(DecodeBufferDeathTest, DecodeUInt8PastEnd) {
const char data[] = {0x12, 0x23};
DecodeBuffer b(data, sizeof data);
EXPECT_EQ(2u, b.FullSize());
EXPECT_EQ(0x1223, b.DecodeUInt16());
EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt8(); }, "Remaining");
}
TEST(DecodeBufferDeathTest, DecodeUInt16OverEnd) {
const char data[] = {0x12, 0x23, 0x34};
DecodeBuffer b(data, sizeof data);
EXPECT_EQ(3u, b.FullSize());
EXPECT_EQ(0x1223, b.DecodeUInt16());
EXPECT_QUICHE_DEBUG_DEATH({ b.DecodeUInt16(); }, "Remaining");
}
TEST(DecodeBufferSubsetDeathTest, TwoSubsets) {
const char data[] = "abc";
DecodeBuffer base(data, 3);
DecodeBufferSubset subset1(&base, 1);
EXPECT_QUICHE_DEBUG_DEATH({ DecodeBufferSubset subset2(&base, 1); },
"There is already a subset");
}
TEST(DecodeBufferSubsetDeathTest, BaseCursorAdvanced) {
const char data[] = "abc";
DecodeBuffer base(data, 3);
base.AdvanceCursor(1);
EXPECT_QUICHE_DEBUG_DEATH(
{
DecodeBufferSubset subset1(&base, 2);
base.AdvanceCursor(1);
},
"Access via subset only when present");
}
#endif
}
}
} |
416 | cpp | google/quiche | http2_structure_decoder | quiche/http2/decoder/http2_structure_decoder.cc | quiche/http2/decoder/http2_structure_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_HTTP2_STRUCTURE_DECODER_H_
#define QUICHE_HTTP2_DECODER_HTTP2_STRUCTURE_DECODER_H_
#include <cstdint>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_http2_structures.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace test {
class Http2StructureDecoderPeer;
}
class QUICHE_EXPORT Http2StructureDecoder {
public:
template <class S>
bool Start(S* out, DecodeBuffer* db) {
static_assert(S::EncodedSize() <= sizeof buffer_, "buffer_ is too small");
QUICHE_DVLOG(2) << __func__ << "@" << this
<< ": db->Remaining=" << db->Remaining()
<< "; EncodedSize=" << S::EncodedSize();
if (db->Remaining() >= S::EncodedSize()) {
DoDecode(out, db);
return true;
}
IncompleteStart(db, S::EncodedSize());
return false;
}
template <class S>
bool Resume(S* out, DecodeBuffer* db) {
QUICHE_DVLOG(2) << __func__ << "@" << this << ": offset_=" << offset_
<< "; db->Remaining=" << db->Remaining();
if (ResumeFillingBuffer(db, S::EncodedSize())) {
QUICHE_DVLOG(2) << __func__ << "@" << this << " offset_=" << offset_
<< " Ready to decode from buffer_.";
DecodeBuffer buffer_db(buffer_, S::EncodedSize());
DoDecode(out, &buffer_db);
return true;
}
QUICHE_DCHECK_LT(offset_, S::EncodedSize());
return false;
}
template <class S>
DecodeStatus Start(S* out, DecodeBuffer* db, uint32_t* remaining_payload) {
static_assert(S::EncodedSize() <= sizeof buffer_, "buffer_ is too small");
QUICHE_DVLOG(2) << __func__ << "@" << this
<< ": *remaining_payload=" << *remaining_payload
<< "; db->Remaining=" << db->Remaining()
<< "; EncodedSize=" << S::EncodedSize();
if (db->MinLengthRemaining(*remaining_payload) >= S::EncodedSize()) {
DoDecode(out, db);
*remaining_payload -= S::EncodedSize();
return DecodeStatus::kDecodeDone;
}
return IncompleteStart(db, remaining_payload, S::EncodedSize());
}
template <class S>
bool Resume(S* out, DecodeBuffer* db, uint32_t* remaining_payload) {
QUICHE_DVLOG(3) << __func__ << "@" << this << ": offset_=" << offset_
<< "; *remaining_payload=" << *remaining_payload
<< "; db->Remaining=" << db->Remaining()
<< "; EncodedSize=" << S::EncodedSize();
if (ResumeFillingBuffer(db, remaining_payload, S::EncodedSize())) {
QUICHE_DVLOG(2) << __func__ << "@" << this << ": offset_=" << offset_
<< "; Ready to decode from buffer_.";
DecodeBuffer buffer_db(buffer_, S::EncodedSize());
DoDecode(out, &buffer_db);
return true;
}
QUICHE_DCHECK_LT(offset_, S::EncodedSize());
return false;
}
uint32_t offset() const { return offset_; }
private:
friend class test::Http2StructureDecoderPeer;
uint32_t IncompleteStart(DecodeBuffer* db, uint32_t target_size);
DecodeStatus IncompleteStart(DecodeBuffer* db, uint32_t* remaining_payload,
uint32_t target_size);
bool ResumeFillingBuffer(DecodeBuffer* db, uint32_t target_size);
bool ResumeFillingBuffer(DecodeBuffer* db, uint32_t* remaining_payload,
uint32_t target_size);
uint32_t offset_;
char buffer_[Http2FrameHeader::EncodedSize()];
};
}
#endif
#include "quiche/http2/decoder/http2_structure_decoder.h"
#include <algorithm>
#include <cstring>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
namespace http2 {
uint32_t Http2StructureDecoder::IncompleteStart(DecodeBuffer* db,
uint32_t target_size) {
if (target_size > sizeof buffer_) {
QUICHE_BUG(http2_bug_154_1)
<< "target_size too large for buffer: " << target_size;
return 0;
}
const uint32_t num_to_copy = db->MinLengthRemaining(target_size);
memcpy(buffer_, db->cursor(), num_to_copy);
offset_ = num_to_copy;
db->AdvanceCursor(num_to_copy);
return num_to_copy;
}
DecodeStatus Http2StructureDecoder::IncompleteStart(DecodeBuffer* db,
uint32_t* remaining_payload,
uint32_t target_size) {
QUICHE_DVLOG(1) << "IncompleteStart@" << this
<< ": *remaining_payload=" << *remaining_payload
<< "; target_size=" << target_size
<< "; db->Remaining=" << db->Remaining();
*remaining_payload -=
IncompleteStart(db, std::min(target_size, *remaining_payload));
if (*remaining_payload > 0 && db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
QUICHE_DVLOG(1) << "IncompleteStart: kDecodeError";
return DecodeStatus::kDecodeError;
}
bool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db,
uint32_t target_size) {
QUICHE_DVLOG(2) << "ResumeFillingBuffer@" << this
<< ": target_size=" << target_size << "; offset_=" << offset_
<< "; db->Remaining=" << db->Remaining();
if (target_size < offset_) {
QUICHE_BUG(http2_bug_154_2)
<< "Already filled buffer_! target_size=" << target_size
<< " offset_=" << offset_;
return false;
}
const uint32_t needed = target_size - offset_;
const uint32_t num_to_copy = db->MinLengthRemaining(needed);
QUICHE_DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy;
memcpy(&buffer_[offset_], db->cursor(), num_to_copy);
db->AdvanceCursor(num_to_copy);
offset_ += num_to_copy;
return needed == num_to_copy;
}
bool Http2StructureDecoder::ResumeFillingBuffer(DecodeBuffer* db,
uint32_t* remaining_payload,
uint32_t target_size) {
QUICHE_DVLOG(2) << "ResumeFillingBuffer@" << this
<< ": target_size=" << target_size << "; offset_=" << offset_
<< "; *remaining_payload=" << *remaining_payload
<< "; db->Remaining=" << db->Remaining();
if (target_size < offset_) {
QUICHE_BUG(http2_bug_154_3)
<< "Already filled buffer_! target_size=" << target_size
<< " offset_=" << offset_;
return false;
}
const uint32_t needed = target_size - offset_;
const uint32_t num_to_copy =
db->MinLengthRemaining(std::min(needed, *remaining_payload));
QUICHE_DVLOG(2) << "ResumeFillingBuffer num_to_copy=" << num_to_copy;
memcpy(&buffer_[offset_], db->cursor(), num_to_copy);
db->AdvanceCursor(num_to_copy);
offset_ += num_to_copy;
*remaining_payload -= num_to_copy;
return needed == num_to_copy;
}
} | #include "quiche/http2/decoder/http2_structure_decoder.h"
#include <stddef.h>
#include <cstdint>
#include <string>
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
namespace {
const bool kMayReturnZeroOnFirst = false;
template <class S>
class Http2StructureDecoderTest : public RandomDecoderTest {
protected:
typedef S Structure;
Http2StructureDecoderTest() {
stop_decode_on_done_ = true;
}
DecodeStatus StartDecoding(DecodeBuffer* b) override {
structure_ = std::make_unique<S>();
uint32_t old_remaining = b->Remaining();
if (structure_decoder_.Start(structure_.get(), b)) {
EXPECT_EQ(old_remaining - S::EncodedSize(), b->Remaining());
++fast_decode_count_;
return DecodeStatus::kDecodeDone;
} else {
EXPECT_LT(structure_decoder_.offset(), S::EncodedSize());
EXPECT_EQ(0u, b->Remaining());
EXPECT_EQ(old_remaining - structure_decoder_.offset(), b->Remaining());
++incomplete_start_count_;
return DecodeStatus::kDecodeInProgress;
}
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
uint32_t old_offset = structure_decoder_.offset();
EXPECT_LT(old_offset, S::EncodedSize());
uint32_t avail = b->Remaining();
if (structure_decoder_.Resume(structure_.get(), b)) {
EXPECT_LE(S::EncodedSize(), old_offset + avail);
EXPECT_EQ(b->Remaining(), avail - (S::EncodedSize() - old_offset));
++slow_decode_count_;
return DecodeStatus::kDecodeDone;
} else {
EXPECT_LT(structure_decoder_.offset(), S::EncodedSize());
EXPECT_EQ(0u, b->Remaining());
EXPECT_GT(S::EncodedSize(), old_offset + avail);
++incomplete_resume_count_;
return DecodeStatus::kDecodeInProgress;
}
}
AssertionResult DecodeLeadingStructure(const S* expected,
absl::string_view data) {
HTTP2_VERIFY_LE(S::EncodedSize(), data.size());
DecodeBuffer original(data);
Validator validator;
if (expected != nullptr) {
validator = [expected, this](const DecodeBuffer& ,
DecodeStatus ) -> AssertionResult {
HTTP2_VERIFY_EQ(*expected, *structure_);
return AssertionSuccess();
};
}
validator = ValidateDoneAndOffset(S::EncodedSize(), std::move(validator));
fast_decode_count_ = 0;
slow_decode_count_ = 0;
incomplete_start_count_ = 0;
incomplete_resume_count_ = 0;
HTTP2_VERIFY_SUCCESS(DecodeAndValidateSeveralWays(
&original, kMayReturnZeroOnFirst, validator));
HTTP2_VERIFY_FALSE(HasFailure());
HTTP2_VERIFY_EQ(S::EncodedSize(), structure_decoder_.offset());
HTTP2_VERIFY_EQ(S::EncodedSize(), original.Offset());
HTTP2_VERIFY_LT(0u, fast_decode_count_);
HTTP2_VERIFY_LT(0u, slow_decode_count_);
HTTP2_VERIFY_LT(0u, incomplete_start_count_);
if (S::EncodedSize() >= 2) {
HTTP2_VERIFY_LE(0u, incomplete_resume_count_);
} else {
HTTP2_VERIFY_EQ(0u, incomplete_resume_count_);
}
if (expected != nullptr) {
QUICHE_DVLOG(1) << "DecodeLeadingStructure expected: " << *expected;
QUICHE_DVLOG(1) << "DecodeLeadingStructure actual: " << *structure_;
HTTP2_VERIFY_EQ(*expected, *structure_);
}
return AssertionSuccess();
}
template <size_t N>
AssertionResult DecodeLeadingStructure(const char (&data)[N]) {
return DecodeLeadingStructure(nullptr, absl::string_view(data, N));
}
template <size_t N>
AssertionResult DecodeLeadingStructure(const unsigned char (&data)[N]) {
return DecodeLeadingStructure(nullptr, ToStringPiece(data));
}
AssertionResult EncodeThenDecode(const S& in_s) {
std::string bytes = SerializeStructure(in_s);
HTTP2_VERIFY_EQ(S::EncodedSize(), bytes.size());
return DecodeLeadingStructure(&in_s, bytes);
}
AssertionResult TestDecodingRandomizedStructures(size_t count) {
for (size_t i = 0; i < count; ++i) {
Structure input;
Randomize(&input, RandomPtr());
HTTP2_VERIFY_SUCCESS(EncodeThenDecode(input));
}
return AssertionSuccess();
}
AssertionResult TestDecodingRandomizedStructures() {
HTTP2_VERIFY_SUCCESS(TestDecodingRandomizedStructures(100));
return AssertionSuccess();
}
uint32_t decode_offset_ = 0;
std::unique_ptr<S> structure_;
Http2StructureDecoder structure_decoder_;
size_t fast_decode_count_ = 0;
size_t slow_decode_count_ = 0;
size_t incomplete_start_count_ = 0;
size_t incomplete_resume_count_ = 0;
};
class Http2FrameHeaderDecoderTest
: public Http2StructureDecoderTest<Http2FrameHeader> {};
TEST_F(Http2FrameHeaderDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x00, 0x05,
0x01,
0x08,
0x00, 0x00, 0x00, 0x01,
0x04,
0x00, 0x00, 0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(5u, structure_->payload_length);
EXPECT_EQ(Http2FrameType::HEADERS, structure_->type);
EXPECT_EQ(Http2FrameFlag::PADDED, structure_->flags);
EXPECT_EQ(1u, structure_->stream_id);
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff,
0xff,
0xff,
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ((1u << 24) - 1u, structure_->payload_length);
EXPECT_EQ(static_cast<Http2FrameType>(255), structure_->type);
EXPECT_EQ(255, structure_->flags);
EXPECT_EQ(0x7FFFFFFFu, structure_->stream_id);
}
}
TEST_F(Http2FrameHeaderDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2PriorityFieldsDecoderTest
: public Http2StructureDecoderTest<Http2PriorityFields> {};
TEST_F(Http2PriorityFieldsDecoderTest, DecodesLiteral) {
{
const unsigned char kData[] = {
0x80, 0x00, 0x00, 0x05,
0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(5u, structure_->stream_dependency);
EXPECT_EQ(256u, structure_->weight);
EXPECT_EQ(true, structure_->is_exclusive);
}
{
const unsigned char kData[] = {
0x7f, 0xff, 0xff, 0xff,
0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(StreamIdMask(), structure_->stream_dependency);
EXPECT_EQ(1u, structure_->weight);
EXPECT_FALSE(structure_->is_exclusive);
}
}
TEST_F(Http2PriorityFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2RstStreamFieldsDecoderTest
: public Http2StructureDecoderTest<Http2RstStreamFields> {};
TEST_F(Http2RstStreamFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x00, 0x00, 0x01,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_TRUE(structure_->IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_->error_code);
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_FALSE(structure_->IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_->error_code);
}
}
TEST_F(Http2RstStreamFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2SettingFieldsDecoderTest
: public Http2StructureDecoderTest<Http2SettingFields> {};
TEST_F(Http2SettingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x01,
0x00, 0x00, 0x40, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_TRUE(structure_->IsSupportedParameter());
EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, structure_->parameter);
EXPECT_EQ(1u << 14, structure_->value);
}
{
const unsigned char kData[] = {
0x00, 0x00,
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_FALSE(structure_->IsSupportedParameter());
EXPECT_EQ(static_cast<Http2SettingsParameter>(0), structure_->parameter);
}
}
TEST_F(Http2SettingFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2PushPromiseFieldsDecoderTest
: public Http2StructureDecoderTest<Http2PushPromiseFields> {};
TEST_F(Http2PushPromiseFieldsDecoderTest, DecodesLiteral) {
{
const unsigned char kData[] = {
0x00, 0x01, 0x8a, 0x92,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(101010u, structure_->promised_stream_id);
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(StreamIdMask(), structure_->promised_stream_id);
}
}
TEST_F(Http2PushPromiseFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2PingFieldsDecoderTest
: public Http2StructureDecoderTest<Http2PingFields> {};
TEST_F(Http2PingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));
}
{
const char kData[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(ToStringPiece(kData), ToStringPiece(structure_->opaque_bytes));
}
}
TEST_F(Http2PingFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2GoAwayFieldsDecoderTest
: public Http2StructureDecoderTest<Http2GoAwayFields> {};
TEST_F(Http2GoAwayFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(0u, structure_->last_stream_id);
EXPECT_TRUE(structure_->IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_->error_code);
}
{
const char kData[] = {
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0d,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(1u, structure_->last_stream_id);
EXPECT_TRUE(structure_->IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_->error_code);
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(StreamIdMask(), structure_->last_stream_id);
EXPECT_FALSE(structure_->IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_->error_code);
}
}
TEST_F(Http2GoAwayFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2WindowUpdateFieldsDecoderTest
: public Http2StructureDecoderTest<Http2WindowUpdateFields> {};
TEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x01, 0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(1u << 16, structure_->window_size_increment);
}
{
const char kData[] = {
0x00, 0x00, 0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(0u, structure_->window_size_increment);
}
{
const unsigned char kData[] = {
0xff, 0xff, 0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(StreamIdMask(), structure_->window_size_increment);
}
}
TEST_F(Http2WindowUpdateFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
class Http2AltSvcFieldsDecoderTest
: public Http2StructureDecoderTest<Http2AltSvcFields> {};
TEST_F(Http2AltSvcFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
0x00, 0x00,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(0, structure_->origin_length);
}
{
const char kData[] = {
0x00, 0x14,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(20, structure_->origin_length);
}
{
const unsigned char kData[] = {
0xff, 0xff,
};
ASSERT_TRUE(DecodeLeadingStructure(kData));
EXPECT_EQ(65535, structure_->origin_length);
}
}
TEST_F(Http2AltSvcFieldsDecoderTest, DecodesRandomized) {
EXPECT_TRUE(TestDecodingRandomizedStructures());
}
}
}
} |
417 | cpp | google/quiche | decode_http2_structures | quiche/http2/decoder/decode_http2_structures.cc | quiche/http2/decoder/decode_http2_structures_test.cc | #ifndef QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_
#define QUICHE_HTTP2_DECODER_DECODE_HTTP2_STRUCTURES_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
QUICHE_EXPORT void DoDecode(Http2FrameHeader* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PriorityFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2SettingFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PingFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b);
QUICHE_EXPORT void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b);
}
#endif
#include "quiche/http2/decoder/decode_http2_structures.h"
#include <cstdint>
#include <cstring>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
void DoDecode(Http2FrameHeader* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2FrameHeader::EncodedSize(), b->Remaining());
out->payload_length = b->DecodeUInt24();
out->type = static_cast<Http2FrameType>(b->DecodeUInt8());
out->flags = static_cast<Http2FrameFlag>(b->DecodeUInt8());
out->stream_id = b->DecodeUInt31();
}
void DoDecode(Http2PriorityFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PriorityFields::EncodedSize(), b->Remaining());
uint32_t stream_id_and_flag = b->DecodeUInt32();
out->stream_dependency = stream_id_and_flag & StreamIdMask();
if (out->stream_dependency == stream_id_and_flag) {
out->is_exclusive = false;
} else {
out->is_exclusive = true;
}
out->weight = b->DecodeUInt8() + 1;
}
void DoDecode(Http2RstStreamFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2RstStreamFields::EncodedSize(), b->Remaining());
out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32());
}
void DoDecode(Http2SettingFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2SettingFields::EncodedSize(), b->Remaining());
out->parameter = static_cast<Http2SettingsParameter>(b->DecodeUInt16());
out->value = b->DecodeUInt32();
}
void DoDecode(Http2PushPromiseFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PushPromiseFields::EncodedSize(), b->Remaining());
out->promised_stream_id = b->DecodeUInt31();
}
void DoDecode(Http2PingFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PingFields::EncodedSize(), b->Remaining());
memcpy(out->opaque_bytes, b->cursor(), Http2PingFields::EncodedSize());
b->AdvanceCursor(Http2PingFields::EncodedSize());
}
void DoDecode(Http2GoAwayFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2GoAwayFields::EncodedSize(), b->Remaining());
out->last_stream_id = b->DecodeUInt31();
out->error_code = static_cast<Http2ErrorCode>(b->DecodeUInt32());
}
void DoDecode(Http2WindowUpdateFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2WindowUpdateFields::EncodedSize(), b->Remaining());
out->window_size_increment = b->DecodeUInt31();
}
void DoDecode(Http2PriorityUpdateFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2PriorityUpdateFields::EncodedSize(), b->Remaining());
out->prioritized_stream_id = b->DecodeUInt31();
}
void DoDecode(Http2AltSvcFields* out, DecodeBuffer* b) {
QUICHE_DCHECK_NE(nullptr, out);
QUICHE_DCHECK_NE(nullptr, b);
QUICHE_DCHECK_LE(Http2AltSvcFields::EncodedSize(), b->Remaining());
out->origin_length = b->DecodeUInt16();
}
} | #include "quiche/http2/decoder/decode_http2_structures.h"
#include <stddef.h>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
template <typename T, size_t N>
absl::string_view ToStringPiece(T (&data)[N]) {
return absl::string_view(reinterpret_cast<const char*>(data), N * sizeof(T));
}
template <class S>
std::string SerializeStructure(const S& s) {
Http2FrameBuilder fb;
fb.Append(s);
EXPECT_EQ(S::EncodedSize(), fb.size());
return fb.buffer();
}
template <class S>
class StructureDecoderTest : public quiche::test::QuicheTest {
protected:
typedef S Structure;
StructureDecoderTest() : random_(), random_decode_count_(100) {}
void Randomize(S* p) { ::http2::test::Randomize(p, &random_); }
void DecodeLeadingStructure(const S* expected, absl::string_view data) {
ASSERT_LE(S::EncodedSize(), data.size());
DecodeBuffer db(data);
Randomize(&structure_);
DoDecode(&structure_, &db);
EXPECT_EQ(db.Offset(), S::EncodedSize());
if (expected != nullptr) {
EXPECT_EQ(structure_, *expected);
}
}
template <size_t N>
void DecodeLeadingStructure(const char (&data)[N]) {
DecodeLeadingStructure(nullptr, absl::string_view(data, N));
}
void EncodeThenDecode(const S& in_s) {
std::string bytes = SerializeStructure(in_s);
EXPECT_EQ(S::EncodedSize(), bytes.size());
DecodeLeadingStructure(&in_s, bytes);
}
void TestDecodingRandomizedStructures(size_t count) {
for (size_t i = 0; i < count && !HasFailure(); ++i) {
Structure input;
Randomize(&input);
EncodeThenDecode(input);
}
}
void TestDecodingRandomizedStructures() {
TestDecodingRandomizedStructures(random_decode_count_);
}
Http2Random random_;
const size_t random_decode_count_;
uint32_t decode_offset_ = 0;
S structure_;
size_t fast_decode_count_ = 0;
size_t slow_decode_count_ = 0;
};
class FrameHeaderDecoderTest : public StructureDecoderTest<Http2FrameHeader> {};
TEST_F(FrameHeaderDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x05',
'\x01',
'\x08',
'\x00', '\x00', '\x00', '\x01',
'\x04',
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(5u, structure_.payload_length);
EXPECT_EQ(Http2FrameType::HEADERS, structure_.type);
EXPECT_EQ(Http2FrameFlag::PADDED, structure_.flags);
EXPECT_EQ(1u, structure_.stream_id);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
'\xff',
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ((1u << 24) - 1, structure_.payload_length);
EXPECT_EQ(static_cast<Http2FrameType>(255), structure_.type);
EXPECT_EQ(255, structure_.flags);
EXPECT_EQ(0x7FFFFFFFu, structure_.stream_id);
}
}
}
TEST_F(FrameHeaderDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PriorityFieldsDecoderTest
: public StructureDecoderTest<Http2PriorityFields> {};
TEST_F(PriorityFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x80', '\x00', '\x00', '\x05',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(5u, structure_.stream_dependency);
EXPECT_EQ(256u, structure_.weight);
EXPECT_EQ(true, structure_.is_exclusive);
}
}
{
const char kData[] = {
'\x7f', '\xff',
'\xff', '\xff',
'\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.stream_dependency);
EXPECT_EQ(1u, structure_.weight);
EXPECT_FALSE(structure_.is_exclusive);
}
}
}
TEST_F(PriorityFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class RstStreamFieldsDecoderTest
: public StructureDecoderTest<Http2RstStreamFields> {};
TEST_F(RstStreamFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x01',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, structure_.error_code);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_FALSE(structure_.IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code);
}
}
}
TEST_F(RstStreamFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class SettingFieldsDecoderTest
: public StructureDecoderTest<Http2SettingFields> {};
TEST_F(SettingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01',
'\x00', '\x00', '\x40', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_TRUE(structure_.IsSupportedParameter());
EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE,
structure_.parameter);
EXPECT_EQ(1u << 14, structure_.value);
}
}
{
const char kData[] = {
'\x00', '\x00',
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_FALSE(structure_.IsSupportedParameter());
EXPECT_EQ(static_cast<Http2SettingsParameter>(0), structure_.parameter);
}
}
}
TEST_F(SettingFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PushPromiseFieldsDecoderTest
: public StructureDecoderTest<Http2PushPromiseFields> {};
TEST_F(PushPromiseFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x8a', '\x92',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(101010u, structure_.promised_stream_id);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff',
'\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.promised_stream_id);
}
}
}
TEST_F(PushPromiseFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class PingFieldsDecoderTest : public StructureDecoderTest<Http2PingFields> {};
TEST_F(PingFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(absl::string_view(kData, 8),
ToStringPiece(structure_.opaque_bytes));
}
}
}
TEST_F(PingFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class GoAwayFieldsDecoderTest : public StructureDecoderTest<Http2GoAwayFields> {
};
TEST_F(GoAwayFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0u, structure_.last_stream_id);
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, structure_.error_code);
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x01',
'\x00', '\x00', '\x00', '\x0d',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(1u, structure_.last_stream_id);
EXPECT_TRUE(structure_.IsSupportedErrorCode());
EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, structure_.error_code);
}
}
{
const char kData[] = {
'\xff', '\xff',
'\xff', '\xff',
'\xff', '\xff',
'\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.last_stream_id);
EXPECT_FALSE(structure_.IsSupportedErrorCode());
EXPECT_EQ(static_cast<Http2ErrorCode>(0xffffffff), structure_.error_code);
}
}
}
TEST_F(GoAwayFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class WindowUpdateFieldsDecoderTest
: public StructureDecoderTest<Http2WindowUpdateFields> {};
TEST_F(WindowUpdateFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x01', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(1u << 16, structure_.window_size_increment);
}
}
{
const char kData[] = {
'\x00', '\x00', '\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0u, structure_.window_size_increment);
}
}
{
const char kData[] = {
'\xff', '\xff', '\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(StreamIdMask(), structure_.window_size_increment);
}
}
}
TEST_F(WindowUpdateFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
class AltSvcFieldsDecoderTest : public StructureDecoderTest<Http2AltSvcFields> {
};
TEST_F(AltSvcFieldsDecoderTest, DecodesLiteral) {
{
const char kData[] = {
'\x00', '\x00',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(0, structure_.origin_length);
}
}
{
const char kData[] = {
'\x00', '\x14',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(20, structure_.origin_length);
}
}
{
const char kData[] = {
'\xff', '\xff',
};
DecodeLeadingStructure(kData);
if (!HasFailure()) {
EXPECT_EQ(65535, structure_.origin_length);
}
}
}
TEST_F(AltSvcFieldsDecoderTest, DecodesRandomized) {
TestDecodingRandomizedStructures();
}
}
}
} |
418 | cpp | google/quiche | goaway_payload_decoder | quiche/http2/decoder/payload_decoders/goaway_payload_decoder.cc | quiche/http2/decoder/payload_decoders/goaway_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_GOAWAY_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_GOAWAY_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class GoAwayPayloadDecoderPeer;
}
class QUICHE_EXPORT GoAwayPayloadDecoder {
public:
enum class PayloadState {
kStartDecodingFixedFields,
kHandleFixedFieldsStatus,
kReadOpaqueData,
kResumeDecodingFixedFields,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::GoAwayPayloadDecoderPeer;
Http2GoAwayFields goaway_fields_;
PayloadState payload_state_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
GoAwayPayloadDecoder::PayloadState v) {
switch (v) {
case GoAwayPayloadDecoder::PayloadState::kStartDecodingFixedFields:
return out << "kStartDecodingFixedFields";
case GoAwayPayloadDecoder::PayloadState::kHandleFixedFieldsStatus:
return out << "kHandleFixedFieldsStatus";
case GoAwayPayloadDecoder::PayloadState::kReadOpaqueData:
return out << "kReadOpaqueData";
case GoAwayPayloadDecoder::PayloadState::kResumeDecodingFixedFields:
return out << "kResumeDecodingFixedFields";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_167_1)
<< "Invalid GoAwayPayloadDecoder::PayloadState: " << unknown;
return out << "GoAwayPayloadDecoder::PayloadState(" << unknown << ")";
}
DecodeStatus GoAwayPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "GoAwayPayloadDecoder::StartDecodingPayload: "
<< state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
QUICHE_DCHECK_EQ(0, state->frame_header().flags);
state->InitializeRemainders();
payload_state_ = PayloadState::kStartDecodingFixedFields;
return ResumeDecodingPayload(state, db);
}
DecodeStatus GoAwayPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2)
<< "GoAwayPayloadDecoder::ResumeDecodingPayload: remaining_payload="
<< state->remaining_payload() << ", db->Remaining=" << db->Remaining();
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);
QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_);
DecodeStatus status = DecodeStatus::kDecodeError;
size_t avail;
while (true) {
QUICHE_DVLOG(2)
<< "GoAwayPayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
switch (payload_state_) {
case PayloadState::kStartDecodingFixedFields:
status = state->StartDecodingStructureInPayload(&goaway_fields_, db);
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kHandleFixedFieldsStatus:
if (status == DecodeStatus::kDecodeDone) {
state->listener()->OnGoAwayStart(frame_header, goaway_fields_);
} else {
QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError &&
state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
payload_state_ = PayloadState::kResumeDecodingFixedFields;
return status;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kReadOpaqueData:
avail = db->Remaining();
if (avail > 0) {
state->listener()->OnGoAwayOpaqueData(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() > 0) {
payload_state_ = PayloadState::kReadOpaqueData;
return DecodeStatus::kDecodeInProgress;
}
state->listener()->OnGoAwayEnd();
return DecodeStatus::kDecodeDone;
case PayloadState::kResumeDecodingFixedFields:
status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db);
payload_state_ = PayloadState::kHandleFixedFieldsStatus;
continue;
}
QUICHE_BUG(http2_bug_167_2) << "PayloadState: " << payload_state_;
}
}
} | #include "quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h"
#include <stddef.h>
#include <string>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class GoAwayPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() { return Http2FrameType::GOAWAY; }
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnGoAwayStart(const Http2FrameHeader& header,
const Http2GoAwayFields& goaway) override {
QUICHE_VLOG(1) << "OnGoAwayStart header: " << header
<< "; goaway: " << goaway;
StartFrame(header)->OnGoAwayStart(header, goaway);
}
void OnGoAwayOpaqueData(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnGoAwayOpaqueData: len=" << len;
CurrentFrame()->OnGoAwayOpaqueData(data, len);
}
void OnGoAwayEnd() override {
QUICHE_VLOG(1) << "OnGoAwayEnd";
EndFrame()->OnGoAwayEnd();
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class GoAwayPayloadDecoderTest
: public AbstractPayloadDecoderTest<GoAwayPayloadDecoder,
GoAwayPayloadDecoderPeer, Listener> {};
TEST_F(GoAwayPayloadDecoderTest, Truncated) {
auto approve_size = [](size_t size) {
return size != Http2GoAwayFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(Http2GoAwayFields(123, Http2ErrorCode::ENHANCE_YOUR_CALM));
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
class GoAwayOpaqueDataLengthTests
: public GoAwayPayloadDecoderTest,
public ::testing::WithParamInterface<uint32_t> {
protected:
GoAwayOpaqueDataLengthTests() : length_(GetParam()) {
QUICHE_VLOG(1) << "################ length_=" << length_
<< " ################";
}
const uint32_t length_;
};
INSTANTIATE_TEST_SUITE_P(VariousLengths, GoAwayOpaqueDataLengthTests,
::testing::Values(0, 1, 2, 3, 4, 5, 6));
TEST_P(GoAwayOpaqueDataLengthTests, ValidLength) {
Http2GoAwayFields goaway;
Randomize(&goaway, RandomPtr());
std::string opaque_data = Random().RandString(length_);
Http2FrameBuilder fb;
fb.Append(goaway);
fb.Append(opaque_data);
Http2FrameHeader header(fb.size(), Http2FrameType::GOAWAY, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header, opaque_data);
expected.SetOptGoaway(goaway);
ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
} |
419 | cpp | google/quiche | continuation_payload_decoder | quiche/http2/decoder/payload_decoders/continuation_payload_decoder.cc | quiche/http2/decoder/payload_decoders/continuation_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_CONTINUATION_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_CONTINUATION_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT ContinuationPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus ContinuationPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "ContinuationPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS));
state->InitializeRemainders();
state->listener()->OnContinuationStart(frame_header);
return ResumeDecodingPayload(state, db);
}
DecodeStatus ContinuationPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "ContinuationPayloadDecoder::ResumeDecodingPayload"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, state->frame_header().type);
QUICHE_DCHECK_LE(state->remaining_payload(),
state->frame_header().payload_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());
size_t avail = db->Remaining();
QUICHE_DCHECK_LE(avail, state->remaining_payload());
if (avail > 0) {
state->listener()->OnHpackFragment(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() == 0) {
state->listener()->OnContinuationEnd();
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
}
} | #include "quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h"
#include <stddef.h>
#include <string>
#include <type_traits>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class ContinuationPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::CONTINUATION;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnContinuationStart(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnContinuationStart: " << header;
StartFrame(header)->OnContinuationStart(header);
}
void OnHpackFragment(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnHpackFragment: len=" << len;
CurrentFrame()->OnHpackFragment(data, len);
}
void OnContinuationEnd() override {
QUICHE_VLOG(1) << "OnContinuationEnd";
EndFrame()->OnContinuationEnd();
}
};
class ContinuationPayloadDecoderTest
: public AbstractPayloadDecoderTest<
ContinuationPayloadDecoder, ContinuationPayloadDecoderPeer, Listener>,
public ::testing::WithParamInterface<uint32_t> {
protected:
ContinuationPayloadDecoderTest() : length_(GetParam()) {
QUICHE_VLOG(1) << "################ length_=" << length_
<< " ################";
}
const uint32_t length_;
};
INSTANTIATE_TEST_SUITE_P(VariousLengths, ContinuationPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 5, 6));
TEST_P(ContinuationPayloadDecoderTest, ValidLength) {
std::string hpack_payload = Random().RandString(length_);
Http2FrameHeader frame_header(length_, Http2FrameType::CONTINUATION,
RandFlags(), RandStreamId());
set_frame_header(frame_header);
FrameParts expected(frame_header, hpack_payload);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(hpack_payload, expected));
}
}
}
} |
420 | cpp | google/quiche | ping_payload_decoder | quiche/http2/decoder/payload_decoders/ping_payload_decoder.cc | quiche/http2/decoder/payload_decoders/ping_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PING_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PING_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class PingPayloadDecoderPeer;
}
class QUICHE_EXPORT PingPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::PingPayloadDecoderPeer;
DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);
Http2PingFields ping_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace {
constexpr auto kOpaqueSize = Http2PingFields::EncodedSize();
}
DecodeStatus PingPayloadDecoder::StartDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "PingPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::PING, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK));
if (db->Remaining() == kOpaqueSize && total_length == kOpaqueSize) {
static_assert(sizeof(Http2PingFields) == kOpaqueSize,
"If not, then can't enter this block!");
auto* ping = reinterpret_cast<const Http2PingFields*>(db->cursor());
if (frame_header.IsAck()) {
state->listener()->OnPingAck(frame_header, *ping);
} else {
state->listener()->OnPing(frame_header, *ping);
}
db->AdvanceCursor(kOpaqueSize);
return DecodeStatus::kDecodeDone;
}
state->InitializeRemainders();
return HandleStatus(
state, state->StartDecodingStructureInPayload(&ping_fields_, db));
}
DecodeStatus PingPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db) {
QUICHE_DVLOG(2) << "ResumeDecodingPayload: remaining_payload="
<< state->remaining_payload();
QUICHE_DCHECK_EQ(Http2FrameType::PING, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
return HandleStatus(
state, state->ResumeDecodingStructureInPayload(&ping_fields_, db));
}
DecodeStatus PingPayloadDecoder::HandleStatus(FrameDecoderState* state,
DecodeStatus status) {
QUICHE_DVLOG(2) << "HandleStatus: status=" << status
<< "; remaining_payload=" << state->remaining_payload();
if (status == DecodeStatus::kDecodeDone) {
if (state->remaining_payload() == 0) {
const Http2FrameHeader& frame_header = state->frame_header();
if (frame_header.IsAck()) {
state->listener()->OnPingAck(frame_header, ping_fields_);
} else {
state->listener()->OnPing(frame_header, ping_fields_);
}
return DecodeStatus::kDecodeDone;
}
return state->ReportFrameSizeError();
}
QUICHE_DCHECK(
(status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
return status;
}
} | #include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class PingPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() { return Http2FrameType::PING; }
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnPing(const Http2FrameHeader& header,
const Http2PingFields& ping) override {
QUICHE_VLOG(1) << "OnPing: " << header << "; " << ping;
StartAndEndFrame(header)->OnPing(header, ping);
}
void OnPingAck(const Http2FrameHeader& header,
const Http2PingFields& ping) override {
QUICHE_VLOG(1) << "OnPingAck: " << header << "; " << ping;
StartAndEndFrame(header)->OnPingAck(header, ping);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class PingPayloadDecoderTest
: public AbstractPayloadDecoderTest<PingPayloadDecoder,
PingPayloadDecoderPeer, Listener> {
protected:
Http2PingFields RandPingFields() {
Http2PingFields fields;
test::Randomize(&fields, RandomPtr());
return fields;
}
};
TEST_F(PingPayloadDecoderTest, WrongSize) {
auto approve_size = [](size_t size) {
return size != Http2PingFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(RandPingFields());
fb.Append(RandPingFields());
fb.Append(RandPingFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
TEST_F(PingPayloadDecoderTest, Ping) {
for (int n = 0; n < 100; ++n) {
Http2PingFields fields = RandPingFields();
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::PING,
RandFlags() & ~Http2FrameFlag::ACK, RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetOptPing(fields);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
TEST_F(PingPayloadDecoderTest, PingAck) {
for (int n = 0; n < 100; ++n) {
Http2PingFields fields;
Randomize(&fields, RandomPtr());
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::PING,
RandFlags() | Http2FrameFlag::ACK, RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetOptPing(fields);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
}
} |
421 | cpp | google/quiche | headers_payload_decoder | quiche/http2/decoder/payload_decoders/headers_payload_decoder.cc | quiche/http2/decoder/payload_decoders/headers_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_HEADERS_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_HEADERS_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class HeadersPayloadDecoderPeer;
}
class QUICHE_EXPORT HeadersPayloadDecoder {
public:
enum class PayloadState {
kReadPadLength,
kStartDecodingPriorityFields,
kReadPayload,
kSkipPadding,
kResumeDecodingPriorityFields,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::HeadersPayloadDecoderPeer;
PayloadState payload_state_;
Http2PriorityFields priority_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/headers_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
HeadersPayloadDecoder::PayloadState v) {
switch (v) {
case HeadersPayloadDecoder::PayloadState::kReadPadLength:
return out << "kReadPadLength";
case HeadersPayloadDecoder::PayloadState::kStartDecodingPriorityFields:
return out << "kStartDecodingPriorityFields";
case HeadersPayloadDecoder::PayloadState::kResumeDecodingPriorityFields:
return out << "kResumeDecodingPriorityFields";
case HeadersPayloadDecoder::PayloadState::kReadPayload:
return out << "kReadPayload";
case HeadersPayloadDecoder::PayloadState::kSkipPadding:
return out << "kSkipPadding";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_189_1)
<< "Invalid HeadersPayloadDecoder::PayloadState: " << unknown;
return out << "HeadersPayloadDecoder::PayloadState(" << unknown << ")";
}
DecodeStatus HeadersPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "HeadersPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(
0, frame_header.flags &
~(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS |
Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY));
const auto payload_flags = Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY;
if (!frame_header.HasAnyFlags(payload_flags)) {
QUICHE_DVLOG(2) << "StartDecodingPayload !IsPadded && !HasPriority";
if (db->Remaining() == total_length) {
QUICHE_DVLOG(2) << "StartDecodingPayload all present";
state->listener()->OnHeadersStart(frame_header);
if (total_length > 0) {
state->listener()->OnHpackFragment(db->cursor(), total_length);
db->AdvanceCursor(total_length);
}
state->listener()->OnHeadersEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kReadPayload;
} else if (frame_header.IsPadded()) {
payload_state_ = PayloadState::kReadPadLength;
} else {
QUICHE_DCHECK(frame_header.HasPriority()) << frame_header;
payload_state_ = PayloadState::kStartDecodingPriorityFields;
}
state->InitializeRemainders();
state->listener()->OnHeadersStart(frame_header);
return ResumeDecodingPayload(state, db);
}
DecodeStatus HeadersPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "HeadersPayloadDecoder::ResumeDecodingPayload "
<< "remaining_payload=" << state->remaining_payload()
<< "; db->Remaining=" << db->Remaining();
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type);
QUICHE_DCHECK_LE(state->remaining_payload_and_padding(),
frame_header.payload_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding());
DecodeStatus status;
size_t avail;
while (true) {
QUICHE_DVLOG(2)
<< "HeadersPayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
switch (payload_state_) {
case PayloadState::kReadPadLength:
status = state->ReadPadLength(db, true);
if (status != DecodeStatus::kDecodeDone) {
return status;
}
if (!frame_header.HasPriority()) {
payload_state_ = PayloadState::kReadPayload;
continue;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kStartDecodingPriorityFields:
status = state->StartDecodingStructureInPayload(&priority_fields_, db);
if (status != DecodeStatus::kDecodeDone) {
payload_state_ = PayloadState::kResumeDecodingPriorityFields;
return status;
}
state->listener()->OnHeadersPriority(priority_fields_);
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kReadPayload:
avail = state->AvailablePayload(db);
if (avail > 0) {
state->listener()->OnHpackFragment(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() > 0) {
payload_state_ = PayloadState::kReadPayload;
return DecodeStatus::kDecodeInProgress;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kSkipPadding:
if (state->SkipPadding(db)) {
state->listener()->OnHeadersEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kSkipPadding;
return DecodeStatus::kDecodeInProgress;
case PayloadState::kResumeDecodingPriorityFields:
status = state->ResumeDecodingStructureInPayload(&priority_fields_, db);
if (status != DecodeStatus::kDecodeDone) {
return status;
}
state->listener()->OnHeadersPriority(priority_fields_);
payload_state_ = PayloadState::kReadPayload;
continue;
}
QUICHE_BUG(http2_bug_189_2) << "PayloadState: " << payload_state_;
}
}
} | #include "quiche/http2/decoder/payload_decoders/headers_payload_decoder.h"
#include <stddef.h>
#include <string>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class HeadersPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::HEADERS;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() {
return Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY;
}
};
namespace {
struct Listener : public FramePartsCollector {
void OnHeadersStart(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnHeadersStart: " << header;
StartFrame(header)->OnHeadersStart(header);
}
void OnHeadersPriority(const Http2PriorityFields& priority) override {
QUICHE_VLOG(1) << "OnHeadersPriority: " << priority;
CurrentFrame()->OnHeadersPriority(priority);
}
void OnHpackFragment(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnHpackFragment: len=" << len;
CurrentFrame()->OnHpackFragment(data, len);
}
void OnHeadersEnd() override {
QUICHE_VLOG(1) << "OnHeadersEnd";
EndFrame()->OnHeadersEnd();
}
void OnPadLength(size_t pad_length) override {
QUICHE_VLOG(1) << "OnPadLength: " << pad_length;
CurrentFrame()->OnPadLength(pad_length);
}
void OnPadding(const char* padding, size_t skipped_length) override {
QUICHE_VLOG(1) << "OnPadding: " << skipped_length;
CurrentFrame()->OnPadding(padding, skipped_length);
}
void OnPaddingTooLong(const Http2FrameHeader& header,
size_t missing_length) override {
QUICHE_VLOG(1) << "OnPaddingTooLong: " << header
<< "; missing_length: " << missing_length;
FrameError(header)->OnPaddingTooLong(header, missing_length);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class HeadersPayloadDecoderTest
: public AbstractPaddablePayloadDecoderTest<
HeadersPayloadDecoder, HeadersPayloadDecoderPeer, Listener> {};
INSTANTIATE_TEST_SUITE_P(VariousPadLengths, HeadersPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));
TEST_P(HeadersPayloadDecoderTest, VariousHpackPayloadSizes) {
for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) {
QUICHE_LOG(INFO) << "########### hpack_size = " << hpack_size
<< " ###########";
Http2PriorityFields priority(RandStreamId(), 1 + Random().Rand8(),
Random().OneIn(2));
for (bool has_priority : {false, true}) {
Reset();
ASSERT_EQ(IsPadded() ? 1u : 0u, frame_builder_.size());
uint8_t flags = RandFlags();
if (has_priority) {
flags |= Http2FrameFlag::PRIORITY;
frame_builder_.Append(priority);
}
std::string hpack_payload = Random().RandString(hpack_size);
frame_builder_.Append(hpack_payload);
MaybeAppendTrailingPadding();
Http2FrameHeader frame_header(frame_builder_.size(),
Http2FrameType::HEADERS, flags,
RandStreamId());
set_frame_header(frame_header);
ScrubFlagsOfHeader(&frame_header);
FrameParts expected(frame_header, hpack_payload, total_pad_length_);
if (has_priority) {
expected.SetOptPriority(priority);
}
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(),
expected));
}
}
}
TEST_P(HeadersPayloadDecoderTest, Truncated) {
auto approve_size = [](size_t size) {
return size != Http2PriorityFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(Http2PriorityFields(RandStreamId(), 1 + Random().Rand8(),
Random().OneIn(2)));
EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(
Http2FrameFlag::PRIORITY, fb.buffer(), approve_size, total_pad_length_));
}
TEST_P(HeadersPayloadDecoderTest, PaddingTooLong) {
EXPECT_TRUE(VerifyDetectsPaddingTooLong());
}
}
}
} |
422 | cpp | google/quiche | altsvc_payload_decoder | quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.cc | quiche/http2/decoder/payload_decoders/altsvc_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_ALTSVC_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_ALTSVC_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class AltSvcPayloadDecoderPeer;
}
class QUICHE_EXPORT AltSvcPayloadDecoder {
public:
enum class PayloadState {
kStartDecodingStruct,
kMaybeDecodedStruct,
kDecodingStrings,
kResumeDecodingStruct,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::AltSvcPayloadDecoderPeer;
DecodeStatus DecodeStrings(FrameDecoderState* state, DecodeBuffer* db);
Http2AltSvcFields altsvc_fields_;
PayloadState payload_state_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
AltSvcPayloadDecoder::PayloadState v) {
switch (v) {
case AltSvcPayloadDecoder::PayloadState::kStartDecodingStruct:
return out << "kStartDecodingStruct";
case AltSvcPayloadDecoder::PayloadState::kMaybeDecodedStruct:
return out << "kMaybeDecodedStruct";
case AltSvcPayloadDecoder::PayloadState::kDecodingStrings:
return out << "kDecodingStrings";
case AltSvcPayloadDecoder::PayloadState::kResumeDecodingStruct:
return out << "kResumeDecodingStruct";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_163_1)
<< "Invalid AltSvcPayloadDecoder::PayloadState: " << unknown;
return out << "AltSvcPayloadDecoder::PayloadState(" << unknown << ")";
}
DecodeStatus AltSvcPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::StartDecodingPayload: "
<< state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
QUICHE_DCHECK_EQ(0, state->frame_header().flags);
state->InitializeRemainders();
payload_state_ = PayloadState::kStartDecodingStruct;
return ResumeDecodingPayload(state, db);
}
DecodeStatus AltSvcPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::ResumeDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, frame_header.type);
QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());
QUICHE_DCHECK_NE(PayloadState::kMaybeDecodedStruct, payload_state_);
DecodeStatus status = DecodeStatus::kDecodeError;
while (true) {
QUICHE_DVLOG(2)
<< "AltSvcPayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
switch (payload_state_) {
case PayloadState::kStartDecodingStruct:
status = state->StartDecodingStructureInPayload(&altsvc_fields_, db);
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kMaybeDecodedStruct:
if (status == DecodeStatus::kDecodeDone &&
altsvc_fields_.origin_length <= state->remaining_payload()) {
size_t origin_length = altsvc_fields_.origin_length;
size_t value_length = state->remaining_payload() - origin_length;
state->listener()->OnAltSvcStart(frame_header, origin_length,
value_length);
} else if (status != DecodeStatus::kDecodeDone) {
QUICHE_DCHECK(state->remaining_payload() > 0 ||
status == DecodeStatus::kDecodeError)
<< "\nremaining_payload: " << state->remaining_payload()
<< "\nstatus: " << status << "\nheader: " << frame_header;
payload_state_ = PayloadState::kResumeDecodingStruct;
return status;
} else {
QUICHE_DCHECK_GT(altsvc_fields_.origin_length,
state->remaining_payload());
return state->ReportFrameSizeError();
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kDecodingStrings:
return DecodeStrings(state, db);
case PayloadState::kResumeDecodingStruct:
status = state->ResumeDecodingStructureInPayload(&altsvc_fields_, db);
payload_state_ = PayloadState::kMaybeDecodedStruct;
continue;
}
QUICHE_BUG(http2_bug_163_2) << "PayloadState: " << payload_state_;
}
}
DecodeStatus AltSvcPayloadDecoder::DecodeStrings(FrameDecoderState* state,
DecodeBuffer* db) {
QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::DecodeStrings remaining_payload="
<< state->remaining_payload()
<< ", db->Remaining=" << db->Remaining();
size_t origin_length = altsvc_fields_.origin_length;
size_t value_length = state->frame_header().payload_length - origin_length -
Http2AltSvcFields::EncodedSize();
if (state->remaining_payload() > value_length) {
size_t remaining_origin_length = state->remaining_payload() - value_length;
size_t avail = db->MinLengthRemaining(remaining_origin_length);
state->listener()->OnAltSvcOriginData(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
if (remaining_origin_length > avail) {
payload_state_ = PayloadState::kDecodingStrings;
return DecodeStatus::kDecodeInProgress;
}
}
QUICHE_DCHECK_LE(state->remaining_payload(), value_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());
if (db->HasData()) {
size_t avail = db->Remaining();
state->listener()->OnAltSvcValueData(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() == 0) {
state->listener()->OnAltSvcEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kDecodingStrings;
return DecodeStatus::kDecodeInProgress;
}
} | #include "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h"
#include <stddef.h>
#include <string>
#include <tuple>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class AltSvcPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() { return Http2FrameType::ALTSVC; }
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnAltSvcStart(const Http2FrameHeader& header, size_t origin_length,
size_t value_length) override {
QUICHE_VLOG(1) << "OnAltSvcStart header: " << header
<< "; origin_length=" << origin_length
<< "; value_length=" << value_length;
StartFrame(header)->OnAltSvcStart(header, origin_length, value_length);
}
void OnAltSvcOriginData(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len;
CurrentFrame()->OnAltSvcOriginData(data, len);
}
void OnAltSvcValueData(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len;
CurrentFrame()->OnAltSvcValueData(data, len);
}
void OnAltSvcEnd() override {
QUICHE_VLOG(1) << "OnAltSvcEnd";
EndFrame()->OnAltSvcEnd();
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class AltSvcPayloadDecoderTest
: public AbstractPayloadDecoderTest<AltSvcPayloadDecoder,
AltSvcPayloadDecoderPeer, Listener> {};
TEST_F(AltSvcPayloadDecoderTest, Truncated) {
Http2FrameBuilder fb;
fb.Append(Http2AltSvcFields{0xffff});
fb.Append("Too little origin!");
EXPECT_TRUE(
VerifyDetectsFrameSizeError(0, fb.buffer(), nullptr));
}
class AltSvcPayloadLengthTests
: public AltSvcPayloadDecoderTest,
public ::testing::WithParamInterface<std::tuple<uint16_t, uint32_t>> {
protected:
AltSvcPayloadLengthTests()
: origin_length_(std::get<0>(GetParam())),
value_length_(std::get<1>(GetParam())) {
QUICHE_VLOG(1) << "################ origin_length_=" << origin_length_
<< " value_length_=" << value_length_
<< " ################";
}
const uint16_t origin_length_;
const uint32_t value_length_;
};
INSTANTIATE_TEST_SUITE_P(VariousOriginAndValueLengths, AltSvcPayloadLengthTests,
::testing::Combine(::testing::Values(0, 1, 3, 65535),
::testing::Values(0, 1, 3, 65537)));
TEST_P(AltSvcPayloadLengthTests, ValidOriginAndValueLength) {
std::string origin = Random().RandString(origin_length_);
std::string value = Random().RandString(value_length_);
Http2FrameBuilder fb;
fb.Append(Http2AltSvcFields{origin_length_});
fb.Append(origin);
fb.Append(value);
Http2FrameHeader header(fb.size(), Http2FrameType::ALTSVC, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetAltSvcExpected(origin, value);
ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
} |
423 | cpp | google/quiche | priority_payload_decoder | quiche/http2/decoder/payload_decoders/priority_payload_decoder.cc | quiche/http2/decoder/payload_decoders/priority_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class PriorityPayloadDecoderPeer;
}
class QUICHE_EXPORT PriorityPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::PriorityPayloadDecoderPeer;
DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);
Http2PriorityFields priority_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/priority_payload_decoder.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus PriorityPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "PriorityPayloadDecoder::StartDecodingPayload: "
<< state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
QUICHE_DCHECK_EQ(0, state->frame_header().flags);
state->InitializeRemainders();
return HandleStatus(
state, state->StartDecodingStructureInPayload(&priority_fields_, db));
}
DecodeStatus PriorityPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "PriorityPayloadDecoder::ResumeDecodingPayload"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
return HandleStatus(
state, state->ResumeDecodingStructureInPayload(&priority_fields_, db));
}
DecodeStatus PriorityPayloadDecoder::HandleStatus(FrameDecoderState* state,
DecodeStatus status) {
if (status == DecodeStatus::kDecodeDone) {
if (state->remaining_payload() == 0) {
state->listener()->OnPriorityFrame(state->frame_header(),
priority_fields_);
return DecodeStatus::kDecodeDone;
}
return state->ReportFrameSizeError();
}
QUICHE_DCHECK(
(status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
return status;
}
} | #include "quiche/http2/decoder/payload_decoders/priority_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class PriorityPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::PRIORITY;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnPriorityFrame(const Http2FrameHeader& header,
const Http2PriorityFields& priority_fields) override {
QUICHE_VLOG(1) << "OnPriority: " << header << "; " << priority_fields;
StartAndEndFrame(header)->OnPriorityFrame(header, priority_fields);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class PriorityPayloadDecoderTest
: public AbstractPayloadDecoderTest<PriorityPayloadDecoder,
PriorityPayloadDecoderPeer, Listener> {
protected:
Http2PriorityFields RandPriorityFields() {
Http2PriorityFields fields;
test::Randomize(&fields, RandomPtr());
return fields;
}
};
TEST_F(PriorityPayloadDecoderTest, WrongSize) {
auto approve_size = [](size_t size) {
return size != Http2PriorityFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(RandPriorityFields());
fb.Append(RandPriorityFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
TEST_F(PriorityPayloadDecoderTest, VariousPayloads) {
for (int n = 0; n < 100; ++n) {
Http2PriorityFields fields = RandPriorityFields();
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetOptPriority(fields);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
}
} |
424 | cpp | google/quiche | unknown_payload_decoder | quiche/http2/decoder/payload_decoders/unknown_payload_decoder.cc | quiche/http2/decoder/payload_decoders/unknown_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_UNKNOWN_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_UNKNOWN_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT UnknownPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus UnknownPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DVLOG(2) << "UnknownPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK(!IsSupportedHttp2FrameType(frame_header.type)) << frame_header;
QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);
state->InitializeRemainders();
state->listener()->OnUnknownStart(frame_header);
return ResumeDecodingPayload(state, db);
}
DecodeStatus UnknownPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "UnknownPayloadDecoder::ResumeDecodingPayload "
<< "remaining_payload=" << state->remaining_payload()
<< "; db->Remaining=" << db->Remaining();
QUICHE_DCHECK(!IsSupportedHttp2FrameType(state->frame_header().type))
<< state->frame_header();
QUICHE_DCHECK_LE(state->remaining_payload(),
state->frame_header().payload_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload());
size_t avail = db->Remaining();
if (avail > 0) {
state->listener()->OnUnknownPayload(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() == 0) {
state->listener()->OnUnknownEnd();
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
}
} | #include "quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h"
#include <stddef.h>
#include <string>
#include <type_traits>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
Http2FrameType g_unknown_frame_type;
}
class UnknownPayloadDecoderPeer {
public:
static Http2FrameType FrameType() { return g_unknown_frame_type; }
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnUnknownStart(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnUnknownStart: " << header;
StartFrame(header)->OnUnknownStart(header);
}
void OnUnknownPayload(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnUnknownPayload: len=" << len;
CurrentFrame()->OnUnknownPayload(data, len);
}
void OnUnknownEnd() override {
QUICHE_VLOG(1) << "OnUnknownEnd";
EndFrame()->OnUnknownEnd();
}
};
constexpr bool SupportedFrameType = false;
class UnknownPayloadDecoderTest
: public AbstractPayloadDecoderTest<UnknownPayloadDecoder,
UnknownPayloadDecoderPeer, Listener,
SupportedFrameType>,
public ::testing::WithParamInterface<uint32_t> {
protected:
UnknownPayloadDecoderTest() : length_(GetParam()) {
QUICHE_VLOG(1) << "################ length_=" << length_
<< " ################";
do {
g_unknown_frame_type = static_cast<Http2FrameType>(Random().Rand8());
} while (IsSupportedHttp2FrameType(g_unknown_frame_type));
}
const uint32_t length_;
};
INSTANTIATE_TEST_SUITE_P(VariousLengths, UnknownPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 255, 256));
TEST_P(UnknownPayloadDecoderTest, ValidLength) {
std::string unknown_payload = Random().RandString(length_);
Http2FrameHeader frame_header(length_, g_unknown_frame_type, Random().Rand8(),
RandStreamId());
set_frame_header(frame_header);
FrameParts expected(frame_header, unknown_payload);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(unknown_payload, expected));
}
}
}
} |
425 | cpp | google/quiche | window_update_payload_decoder | quiche/http2/decoder/payload_decoders/window_update_payload_decoder.cc | quiche/http2/decoder/payload_decoders/window_update_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_WINDOW_UPDATE_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_WINDOW_UPDATE_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class WindowUpdatePayloadDecoderPeer;
}
class QUICHE_EXPORT WindowUpdatePayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::WindowUpdatePayloadDecoderPeer;
DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);
Http2WindowUpdateFields window_update_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_http2_structures.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus WindowUpdatePayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "WindowUpdatePayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags);
if (db->Remaining() == Http2WindowUpdateFields::EncodedSize() &&
total_length == Http2WindowUpdateFields::EncodedSize()) {
DoDecode(&window_update_fields_, db);
state->listener()->OnWindowUpdate(
frame_header, window_update_fields_.window_size_increment);
return DecodeStatus::kDecodeDone;
}
state->InitializeRemainders();
return HandleStatus(state, state->StartDecodingStructureInPayload(
&window_update_fields_, db));
}
DecodeStatus WindowUpdatePayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "ResumeDecodingPayload: remaining_payload="
<< state->remaining_payload()
<< "; db->Remaining=" << db->Remaining();
QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
return HandleStatus(state, state->ResumeDecodingStructureInPayload(
&window_update_fields_, db));
}
DecodeStatus WindowUpdatePayloadDecoder::HandleStatus(FrameDecoderState* state,
DecodeStatus status) {
QUICHE_DVLOG(2) << "HandleStatus: status=" << status
<< "; remaining_payload=" << state->remaining_payload();
if (status == DecodeStatus::kDecodeDone) {
if (state->remaining_payload() == 0) {
state->listener()->OnWindowUpdate(
state->frame_header(), window_update_fields_.window_size_increment);
return DecodeStatus::kDecodeDone;
}
return state->ReportFrameSizeError();
}
QUICHE_DCHECK(
(status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
return status;
}
} | #include "quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class WindowUpdatePayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::WINDOW_UPDATE;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnWindowUpdate(const Http2FrameHeader& header,
uint32_t window_size_increment) override {
QUICHE_VLOG(1) << "OnWindowUpdate: " << header
<< "; window_size_increment=" << window_size_increment;
EXPECT_EQ(Http2FrameType::WINDOW_UPDATE, header.type);
StartAndEndFrame(header)->OnWindowUpdate(header, window_size_increment);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class WindowUpdatePayloadDecoderTest
: public AbstractPayloadDecoderTest<WindowUpdatePayloadDecoder,
WindowUpdatePayloadDecoderPeer,
Listener> {
protected:
Http2WindowUpdateFields RandWindowUpdateFields() {
Http2WindowUpdateFields fields;
test::Randomize(&fields, RandomPtr());
QUICHE_VLOG(3) << "RandWindowUpdateFields: " << fields;
return fields;
}
};
TEST_F(WindowUpdatePayloadDecoderTest, WrongSize) {
auto approve_size = [](size_t size) {
return size != Http2WindowUpdateFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(RandWindowUpdateFields());
fb.Append(RandWindowUpdateFields());
fb.Append(RandWindowUpdateFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
TEST_F(WindowUpdatePayloadDecoderTest, VariousPayloads) {
for (int n = 0; n < 100; ++n) {
uint32_t stream_id = n == 0 ? 0 : RandStreamId();
Http2WindowUpdateFields fields = RandWindowUpdateFields();
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::WINDOW_UPDATE,
RandFlags(), stream_id);
set_frame_header(header);
FrameParts expected(header);
expected.SetOptWindowUpdateIncrement(fields.window_size_increment);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
}
} |
426 | cpp | google/quiche | push_promise_payload_decoder | quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.cc | quiche/http2/decoder/payload_decoders/push_promise_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PUSH_PROMISE_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PUSH_PROMISE_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class PushPromisePayloadDecoderPeer;
}
class QUICHE_EXPORT PushPromisePayloadDecoder {
public:
enum class PayloadState {
kReadPadLength,
kStartDecodingPushPromiseFields,
kReadPayload,
kSkipPadding,
kResumeDecodingPushPromiseFields,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::PushPromisePayloadDecoderPeer;
void ReportPushPromise(FrameDecoderState* state);
PayloadState payload_state_;
Http2PushPromiseFields push_promise_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
PushPromisePayloadDecoder::PayloadState v) {
switch (v) {
case PushPromisePayloadDecoder::PayloadState::kReadPadLength:
return out << "kReadPadLength";
case PushPromisePayloadDecoder::PayloadState::
kStartDecodingPushPromiseFields:
return out << "kStartDecodingPushPromiseFields";
case PushPromisePayloadDecoder::PayloadState::kReadPayload:
return out << "kReadPayload";
case PushPromisePayloadDecoder::PayloadState::kSkipPadding:
return out << "kSkipPadding";
case PushPromisePayloadDecoder::PayloadState::
kResumeDecodingPushPromiseFields:
return out << "kResumeDecodingPushPromiseFields";
}
return out << static_cast<int>(v);
}
DecodeStatus PushPromisePayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "PushPromisePayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS |
Http2FrameFlag::PADDED));
if (!frame_header.IsPadded()) {
payload_state_ = PayloadState::kStartDecodingPushPromiseFields;
} else {
payload_state_ = PayloadState::kReadPadLength;
}
state->InitializeRemainders();
return ResumeDecodingPayload(state, db);
}
DecodeStatus PushPromisePayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "UnknownPayloadDecoder::ResumeDecodingPayload"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type);
QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length);
QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);
DecodeStatus status;
while (true) {
QUICHE_DVLOG(2)
<< "PushPromisePayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
switch (payload_state_) {
case PayloadState::kReadPadLength:
QUICHE_DCHECK_EQ(state->remaining_payload(),
frame_header.payload_length);
status = state->ReadPadLength(db, false);
if (status != DecodeStatus::kDecodeDone) {
payload_state_ = PayloadState::kReadPadLength;
return status;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kStartDecodingPushPromiseFields:
status =
state->StartDecodingStructureInPayload(&push_promise_fields_, db);
if (status != DecodeStatus::kDecodeDone) {
payload_state_ = PayloadState::kResumeDecodingPushPromiseFields;
return status;
}
ReportPushPromise(state);
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kReadPayload:
QUICHE_DCHECK_LT(state->remaining_payload(),
frame_header.payload_length);
QUICHE_DCHECK_LE(state->remaining_payload(),
frame_header.payload_length -
Http2PushPromiseFields::EncodedSize());
QUICHE_DCHECK_LE(
state->remaining_payload(),
frame_header.payload_length -
Http2PushPromiseFields::EncodedSize() -
(frame_header.IsPadded() ? (1 + state->remaining_padding())
: 0));
{
size_t avail = state->AvailablePayload(db);
state->listener()->OnHpackFragment(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() > 0) {
payload_state_ = PayloadState::kReadPayload;
return DecodeStatus::kDecodeInProgress;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kSkipPadding:
if (state->SkipPadding(db)) {
state->listener()->OnPushPromiseEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kSkipPadding;
return DecodeStatus::kDecodeInProgress;
case PayloadState::kResumeDecodingPushPromiseFields:
status =
state->ResumeDecodingStructureInPayload(&push_promise_fields_, db);
if (status == DecodeStatus::kDecodeDone) {
ReportPushPromise(state);
payload_state_ = PayloadState::kReadPayload;
continue;
}
payload_state_ = PayloadState::kResumeDecodingPushPromiseFields;
return status;
}
QUICHE_BUG(http2_bug_183_1) << "PayloadState: " << payload_state_;
}
}
void PushPromisePayloadDecoder::ReportPushPromise(FrameDecoderState* state) {
const Http2FrameHeader& frame_header = state->frame_header();
if (frame_header.IsPadded()) {
state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_,
1 + state->remaining_padding());
} else {
state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_,
0);
}
}
} | #include "quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h"
#include <stddef.h>
#include <string>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class PushPromisePayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::PUSH_PROMISE;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() {
return Http2FrameFlag::PADDED;
}
};
namespace {
struct Listener : public FramePartsCollector {
void OnPushPromiseStart(const Http2FrameHeader& header,
const Http2PushPromiseFields& promise,
size_t total_padding_length) override {
QUICHE_VLOG(1) << "OnPushPromiseStart header: " << header
<< " promise: " << promise
<< " total_padding_length: " << total_padding_length;
EXPECT_EQ(Http2FrameType::PUSH_PROMISE, header.type);
StartFrame(header)->OnPushPromiseStart(header, promise,
total_padding_length);
}
void OnHpackFragment(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnHpackFragment: len=" << len;
CurrentFrame()->OnHpackFragment(data, len);
}
void OnPushPromiseEnd() override {
QUICHE_VLOG(1) << "OnPushPromiseEnd";
EndFrame()->OnPushPromiseEnd();
}
void OnPadding(const char* padding, size_t skipped_length) override {
QUICHE_VLOG(1) << "OnPadding: " << skipped_length;
CurrentFrame()->OnPadding(padding, skipped_length);
}
void OnPaddingTooLong(const Http2FrameHeader& header,
size_t missing_length) override {
QUICHE_VLOG(1) << "OnPaddingTooLong: " << header
<< "; missing_length: " << missing_length;
FrameError(header)->OnPaddingTooLong(header, missing_length);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class PushPromisePayloadDecoderTest
: public AbstractPaddablePayloadDecoderTest<
PushPromisePayloadDecoder, PushPromisePayloadDecoderPeer, Listener> {
};
INSTANTIATE_TEST_SUITE_P(VariousPadLengths, PushPromisePayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));
TEST_P(PushPromisePayloadDecoderTest, VariousHpackPayloadSizes) {
for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) {
QUICHE_LOG(INFO) << "########### hpack_size = " << hpack_size
<< " ###########";
Reset();
std::string hpack_payload = Random().RandString(hpack_size);
Http2PushPromiseFields push_promise{RandStreamId()};
frame_builder_.Append(push_promise);
frame_builder_.Append(hpack_payload);
MaybeAppendTrailingPadding();
Http2FrameHeader frame_header(frame_builder_.size(),
Http2FrameType::PUSH_PROMISE, RandFlags(),
RandStreamId());
set_frame_header(frame_header);
FrameParts expected(frame_header, hpack_payload, total_pad_length_);
expected.SetOptPushPromise(push_promise);
EXPECT_TRUE(
DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected));
}
}
TEST_P(PushPromisePayloadDecoderTest, Truncated) {
auto approve_size = [](size_t size) {
return size != Http2PushPromiseFields::EncodedSize();
};
Http2PushPromiseFields push_promise{RandStreamId()};
Http2FrameBuilder fb;
fb.Append(push_promise);
EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(0, fb.buffer(), approve_size,
total_pad_length_));
}
TEST_P(PushPromisePayloadDecoderTest, PaddingTooLong) {
EXPECT_TRUE(VerifyDetectsPaddingTooLong());
}
}
}
} |
427 | cpp | google/quiche | priority_update_payload_decoder | quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.cc | quiche/http2/decoder/payload_decoders/priority_update_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_UPDATE_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_PRIORITY_UPDATE_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class PriorityUpdatePayloadDecoderPeer;
}
class QUICHE_EXPORT PriorityUpdatePayloadDecoder {
public:
enum class PayloadState {
kStartDecodingFixedFields,
kResumeDecodingFixedFields,
kHandleFixedFieldsStatus,
kReadPriorityFieldValue,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::PriorityUpdatePayloadDecoderPeer;
Http2PriorityUpdateFields priority_update_fields_;
PayloadState payload_state_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
PriorityUpdatePayloadDecoder::PayloadState v) {
switch (v) {
case PriorityUpdatePayloadDecoder::PayloadState::kStartDecodingFixedFields:
return out << "kStartDecodingFixedFields";
case PriorityUpdatePayloadDecoder::PayloadState::kResumeDecodingFixedFields:
return out << "kResumeDecodingFixedFields";
case PriorityUpdatePayloadDecoder::PayloadState::kHandleFixedFieldsStatus:
return out << "kHandleFixedFieldsStatus";
case PriorityUpdatePayloadDecoder::PayloadState::kReadPriorityFieldValue:
return out << "kReadPriorityFieldValue";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_173_1)
<< "Invalid PriorityUpdatePayloadDecoder::PayloadState: " << unknown;
return out << "PriorityUpdatePayloadDecoder::PayloadState(" << unknown << ")";
}
DecodeStatus PriorityUpdatePayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "PriorityUpdatePayloadDecoder::StartDecodingPayload: "
<< state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
QUICHE_DCHECK_EQ(0, state->frame_header().flags);
state->InitializeRemainders();
payload_state_ = PayloadState::kStartDecodingFixedFields;
return ResumeDecodingPayload(state, db);
}
DecodeStatus PriorityUpdatePayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "PriorityUpdatePayloadDecoder::ResumeDecodingPayload: "
"remaining_payload="
<< state->remaining_payload()
<< ", db->Remaining=" << db->Remaining();
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length);
QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_);
DecodeStatus status = DecodeStatus::kDecodeError;
size_t avail;
while (true) {
QUICHE_DVLOG(2)
<< "PriorityUpdatePayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
switch (payload_state_) {
case PayloadState::kStartDecodingFixedFields:
status = state->StartDecodingStructureInPayload(
&priority_update_fields_, db);
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kHandleFixedFieldsStatus:
if (status == DecodeStatus::kDecodeDone) {
state->listener()->OnPriorityUpdateStart(frame_header,
priority_update_fields_);
} else {
QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError &&
state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
payload_state_ = PayloadState::kResumeDecodingFixedFields;
return status;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kReadPriorityFieldValue:
avail = db->Remaining();
if (avail > 0) {
state->listener()->OnPriorityUpdatePayload(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() > 0) {
payload_state_ = PayloadState::kReadPriorityFieldValue;
return DecodeStatus::kDecodeInProgress;
}
state->listener()->OnPriorityUpdateEnd();
return DecodeStatus::kDecodeDone;
case PayloadState::kResumeDecodingFixedFields:
status = state->ResumeDecodingStructureInPayload(
&priority_update_fields_, db);
payload_state_ = PayloadState::kHandleFixedFieldsStatus;
continue;
}
QUICHE_BUG(http2_bug_173_2) << "PayloadState: " << payload_state_;
}
}
} | #include "quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h"
#include <stddef.h>
#include <string>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class PriorityUpdatePayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::PRIORITY_UPDATE;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnPriorityUpdateStart(
const Http2FrameHeader& header,
const Http2PriorityUpdateFields& priority_update) override {
QUICHE_VLOG(1) << "OnPriorityUpdateStart header: " << header
<< "; priority_update: " << priority_update;
StartFrame(header)->OnPriorityUpdateStart(header, priority_update);
}
void OnPriorityUpdatePayload(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnPriorityUpdatePayload: len=" << len;
CurrentFrame()->OnPriorityUpdatePayload(data, len);
}
void OnPriorityUpdateEnd() override {
QUICHE_VLOG(1) << "OnPriorityUpdateEnd";
EndFrame()->OnPriorityUpdateEnd();
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class PriorityUpdatePayloadDecoderTest
: public AbstractPayloadDecoderTest<PriorityUpdatePayloadDecoder,
PriorityUpdatePayloadDecoderPeer,
Listener> {};
TEST_F(PriorityUpdatePayloadDecoderTest, Truncated) {
auto approve_size = [](size_t size) {
return size != Http2PriorityUpdateFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(Http2PriorityUpdateFields(123));
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
class PriorityUpdatePayloadLengthTests
: public AbstractPayloadDecoderTest<PriorityUpdatePayloadDecoder,
PriorityUpdatePayloadDecoderPeer,
Listener>,
public ::testing::WithParamInterface<uint32_t> {
protected:
PriorityUpdatePayloadLengthTests() : length_(GetParam()) {
QUICHE_VLOG(1) << "################ length_=" << length_
<< " ################";
}
const uint32_t length_;
};
INSTANTIATE_TEST_SUITE_P(VariousLengths, PriorityUpdatePayloadLengthTests,
::testing::Values(0, 1, 2, 3, 4, 5, 6));
TEST_P(PriorityUpdatePayloadLengthTests, ValidLength) {
Http2PriorityUpdateFields priority_update;
Randomize(&priority_update, RandomPtr());
std::string priority_field_value = Random().RandString(length_);
Http2FrameBuilder fb;
fb.Append(priority_update);
fb.Append(priority_field_value);
Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY_UPDATE,
RandFlags(), RandStreamId());
set_frame_header(header);
FrameParts expected(header, priority_field_value);
expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{priority_update});
ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
} |
428 | cpp | google/quiche | rst_stream_payload_decoder | quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.cc | quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_RST_STREAM_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_RST_STREAM_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class RstStreamPayloadDecoderPeer;
}
class QUICHE_EXPORT RstStreamPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::RstStreamPayloadDecoderPeer;
DecodeStatus HandleStatus(FrameDecoderState* state, DecodeStatus status);
Http2RstStreamFields rst_stream_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus RstStreamPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "RstStreamPayloadDecoder::StartDecodingPayload: "
<< state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
QUICHE_DCHECK_EQ(0, state->frame_header().flags);
state->InitializeRemainders();
return HandleStatus(
state, state->StartDecodingStructureInPayload(&rst_stream_fields_, db));
}
DecodeStatus RstStreamPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "RstStreamPayloadDecoder::ResumeDecodingPayload"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
return HandleStatus(
state, state->ResumeDecodingStructureInPayload(&rst_stream_fields_, db));
}
DecodeStatus RstStreamPayloadDecoder::HandleStatus(FrameDecoderState* state,
DecodeStatus status) {
QUICHE_DVLOG(2) << "HandleStatus: status=" << status
<< "; remaining_payload=" << state->remaining_payload();
if (status == DecodeStatus::kDecodeDone) {
if (state->remaining_payload() == 0) {
state->listener()->OnRstStream(state->frame_header(),
rst_stream_fields_.error_code);
return DecodeStatus::kDecodeDone;
}
return state->ReportFrameSizeError();
}
QUICHE_DCHECK(
(status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload();
return status;
}
} | #include "quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h"
#include <stddef.h>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_constants_test_util.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class RstStreamPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::RST_STREAM;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; }
};
namespace {
struct Listener : public FramePartsCollector {
void OnRstStream(const Http2FrameHeader& header,
Http2ErrorCode error_code) override {
QUICHE_VLOG(1) << "OnRstStream: " << header
<< "; error_code=" << error_code;
StartAndEndFrame(header)->OnRstStream(header, error_code);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class RstStreamPayloadDecoderTest
: public AbstractPayloadDecoderTest<RstStreamPayloadDecoder,
RstStreamPayloadDecoderPeer, Listener> {
protected:
Http2RstStreamFields RandRstStreamFields() {
Http2RstStreamFields fields;
test::Randomize(&fields, RandomPtr());
return fields;
}
};
TEST_F(RstStreamPayloadDecoderTest, WrongSize) {
auto approve_size = [](size_t size) {
return size != Http2RstStreamFields::EncodedSize();
};
Http2FrameBuilder fb;
fb.Append(RandRstStreamFields());
fb.Append(RandRstStreamFields());
fb.Append(RandRstStreamFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
TEST_F(RstStreamPayloadDecoderTest, AllErrors) {
for (auto error_code : AllHttp2ErrorCodes()) {
Http2RstStreamFields fields{error_code};
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::RST_STREAM, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.SetOptRstStreamErrorCode(error_code);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
}
} |
429 | cpp | google/quiche | data_payload_decoder | quiche/http2/decoder/payload_decoders/data_payload_decoder.cc | quiche/http2/decoder/payload_decoders/data_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_DATA_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_DATA_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class DataPayloadDecoderPeer;
}
class QUICHE_EXPORT DataPayloadDecoder {
public:
enum class PayloadState {
kReadPadLength,
kReadPayload,
kSkipPadding,
};
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::DataPayloadDecoderPeer;
PayloadState payload_state_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/data_payload_decoder.h"
#include <stddef.h>
#include <ostream>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
DataPayloadDecoder::PayloadState v) {
switch (v) {
case DataPayloadDecoder::PayloadState::kReadPadLength:
return out << "kReadPadLength";
case DataPayloadDecoder::PayloadState::kReadPayload:
return out << "kReadPayload";
case DataPayloadDecoder::PayloadState::kSkipPadding:
return out << "kSkipPadding";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_174_1)
<< "Invalid DataPayloadDecoder::PayloadState: " << unknown;
return out << "DataPayloadDecoder::PayloadState(" << unknown << ")";
}
DecodeStatus DataPayloadDecoder::StartDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "DataPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_STREAM |
Http2FrameFlag::PADDED));
QUICHE_DVLOG(2) << "StartDecodingPayload total_length=" << total_length;
if (!frame_header.IsPadded()) {
QUICHE_DVLOG(2) << "StartDecodingPayload !IsPadded";
if (db->Remaining() == total_length) {
QUICHE_DVLOG(2) << "StartDecodingPayload all present";
state->listener()->OnDataStart(frame_header);
if (total_length > 0) {
state->listener()->OnDataPayload(db->cursor(), total_length);
db->AdvanceCursor(total_length);
}
state->listener()->OnDataEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kReadPayload;
} else {
payload_state_ = PayloadState::kReadPadLength;
}
state->InitializeRemainders();
state->listener()->OnDataStart(frame_header);
return ResumeDecodingPayload(state, db);
}
DecodeStatus DataPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db) {
QUICHE_DVLOG(2) << "DataPayloadDecoder::ResumeDecodingPayload payload_state_="
<< payload_state_;
const Http2FrameHeader& frame_header = state->frame_header();
QUICHE_DCHECK_EQ(Http2FrameType::DATA, frame_header.type);
QUICHE_DCHECK_LE(state->remaining_payload_and_padding(),
frame_header.payload_length);
QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding());
DecodeStatus status;
size_t avail;
switch (payload_state_) {
case PayloadState::kReadPadLength:
status = state->ReadPadLength(db, true);
if (status != DecodeStatus::kDecodeDone) {
return status;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kReadPayload:
avail = state->AvailablePayload(db);
if (avail > 0) {
state->listener()->OnDataPayload(db->cursor(), avail);
db->AdvanceCursor(avail);
state->ConsumePayload(avail);
}
if (state->remaining_payload() > 0) {
payload_state_ = PayloadState::kReadPayload;
return DecodeStatus::kDecodeInProgress;
}
ABSL_FALLTHROUGH_INTENDED;
case PayloadState::kSkipPadding:
if (state->SkipPadding(db)) {
state->listener()->OnDataEnd();
return DecodeStatus::kDecodeDone;
}
payload_state_ = PayloadState::kSkipPadding;
return DecodeStatus::kDecodeInProgress;
}
QUICHE_BUG(http2_bug_174_2) << "PayloadState: " << payload_state_;
return DecodeStatus::kDecodeError;
}
} | #include "quiche/http2/decoder/payload_decoders/data_payload_decoder.h"
#include <stddef.h>
#include <string>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class DataPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() { return Http2FrameType::DATA; }
static constexpr uint8_t FlagsAffectingPayloadDecoding() {
return Http2FrameFlag::PADDED;
}
};
namespace {
struct Listener : public FramePartsCollector {
void OnDataStart(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnDataStart: " << header;
StartFrame(header)->OnDataStart(header);
}
void OnDataPayload(const char* data, size_t len) override {
QUICHE_VLOG(1) << "OnDataPayload: len=" << len;
CurrentFrame()->OnDataPayload(data, len);
}
void OnDataEnd() override {
QUICHE_VLOG(1) << "OnDataEnd";
EndFrame()->OnDataEnd();
}
void OnPadLength(size_t pad_length) override {
QUICHE_VLOG(1) << "OnPadLength: " << pad_length;
CurrentFrame()->OnPadLength(pad_length);
}
void OnPadding(const char* padding, size_t skipped_length) override {
QUICHE_VLOG(1) << "OnPadding: " << skipped_length;
CurrentFrame()->OnPadding(padding, skipped_length);
}
void OnPaddingTooLong(const Http2FrameHeader& header,
size_t missing_length) override {
QUICHE_VLOG(1) << "OnPaddingTooLong: " << header
<< " missing_length: " << missing_length;
EndFrame()->OnPaddingTooLong(header, missing_length);
}
};
class DataPayloadDecoderTest
: public AbstractPaddablePayloadDecoderTest<
DataPayloadDecoder, DataPayloadDecoderPeer, Listener> {
protected:
AssertionResult CreateAndDecodeDataOfSize(size_t data_size) {
Reset();
uint8_t flags = RandFlags();
std::string data_payload = Random().RandString(data_size);
frame_builder_.Append(data_payload);
MaybeAppendTrailingPadding();
Http2FrameHeader frame_header(frame_builder_.size(), Http2FrameType::DATA,
flags, RandStreamId());
set_frame_header(frame_header);
ScrubFlagsOfHeader(&frame_header);
FrameParts expected(frame_header, data_payload, total_pad_length_);
return DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(),
expected);
}
};
INSTANTIATE_TEST_SUITE_P(VariousPadLengths, DataPayloadDecoderTest,
::testing::Values(0, 1, 2, 3, 4, 254, 255, 256));
TEST_P(DataPayloadDecoderTest, VariousDataPayloadSizes) {
for (size_t data_size : {0, 1, 2, 3, 255, 256, 1024}) {
EXPECT_TRUE(CreateAndDecodeDataOfSize(data_size));
}
}
}
}
} |
430 | cpp | google/quiche | settings_payload_decoder | quiche/http2/decoder/payload_decoders/settings_payload_decoder.cc | quiche/http2/decoder/payload_decoders/settings_payload_decoder_test.cc | #ifndef QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_SETTINGS_PAYLOAD_DECODER_H_
#define QUICHE_HTTP2_DECODER_PAYLOAD_DECODERS_SETTINGS_PAYLOAD_DECODER_H_
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/decoder/frame_decoder_state.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class SettingsPayloadDecoderPeer;
}
class QUICHE_EXPORT SettingsPayloadDecoder {
public:
DecodeStatus StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db);
DecodeStatus ResumeDecodingPayload(FrameDecoderState* state,
DecodeBuffer* db);
private:
friend class test::SettingsPayloadDecoderPeer;
DecodeStatus StartDecodingSettings(FrameDecoderState* state,
DecodeBuffer* db);
DecodeStatus HandleNotDone(FrameDecoderState* state, DecodeBuffer* db,
DecodeStatus status);
Http2SettingFields setting_fields_;
};
}
#endif
#include "quiche/http2/decoder/payload_decoders/settings_payload_decoder.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus SettingsPayloadDecoder::StartDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
const Http2FrameHeader& frame_header = state->frame_header();
const uint32_t total_length = frame_header.payload_length;
QUICHE_DVLOG(2) << "SettingsPayloadDecoder::StartDecodingPayload: "
<< frame_header;
QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, frame_header.type);
QUICHE_DCHECK_LE(db->Remaining(), total_length);
QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK));
if (frame_header.IsAck()) {
if (total_length == 0) {
state->listener()->OnSettingsAck(frame_header);
return DecodeStatus::kDecodeDone;
} else {
state->InitializeRemainders();
return state->ReportFrameSizeError();
}
} else {
state->InitializeRemainders();
state->listener()->OnSettingsStart(frame_header);
return StartDecodingSettings(state, db);
}
}
DecodeStatus SettingsPayloadDecoder::ResumeDecodingPayload(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "SettingsPayloadDecoder::ResumeDecodingPayload"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, state->frame_header().type);
QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
DecodeStatus status =
state->ResumeDecodingStructureInPayload(&setting_fields_, db);
if (status == DecodeStatus::kDecodeDone) {
state->listener()->OnSetting(setting_fields_);
return StartDecodingSettings(state, db);
}
return HandleNotDone(state, db, status);
}
DecodeStatus SettingsPayloadDecoder::StartDecodingSettings(
FrameDecoderState* state, DecodeBuffer* db) {
QUICHE_DVLOG(2) << "SettingsPayloadDecoder::StartDecodingSettings"
<< " remaining_payload=" << state->remaining_payload()
<< " db->Remaining=" << db->Remaining();
while (state->remaining_payload() > 0) {
DecodeStatus status =
state->StartDecodingStructureInPayload(&setting_fields_, db);
if (status == DecodeStatus::kDecodeDone) {
state->listener()->OnSetting(setting_fields_);
continue;
}
return HandleNotDone(state, db, status);
}
QUICHE_DVLOG(2) << "LEAVING SettingsPayloadDecoder::StartDecodingSettings"
<< "\n\tdb->Remaining=" << db->Remaining()
<< "\n\t remaining_payload=" << state->remaining_payload();
state->listener()->OnSettingsEnd();
return DecodeStatus::kDecodeDone;
}
DecodeStatus SettingsPayloadDecoder::HandleNotDone(FrameDecoderState* state,
DecodeBuffer* db,
DecodeStatus status) {
QUICHE_DCHECK(
(status == DecodeStatus::kDecodeInProgress &&
state->remaining_payload() > 0) ||
(status == DecodeStatus::kDecodeError && state->remaining_payload() == 0))
<< "\n status=" << status
<< "; remaining_payload=" << state->remaining_payload()
<< "; db->Remaining=" << db->Remaining();
return status;
}
} | #include "quiche/http2/decoder/payload_decoders/settings_payload_decoder.h"
#include <stddef.h>
#include <vector>
#include "quiche/http2/decoder/http2_frame_decoder_listener.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/frame_parts.h"
#include "quiche/http2/test_tools/frame_parts_collector.h"
#include "quiche/http2/test_tools/http2_constants_test_util.h"
#include "quiche/http2/test_tools/http2_frame_builder.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/http2_structures_test_util.h"
#include "quiche/http2/test_tools/payload_decoder_base_test_util.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class SettingsPayloadDecoderPeer {
public:
static constexpr Http2FrameType FrameType() {
return Http2FrameType::SETTINGS;
}
static constexpr uint8_t FlagsAffectingPayloadDecoding() {
return Http2FrameFlag::ACK;
}
};
namespace {
struct Listener : public FramePartsCollector {
void OnSettingsStart(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnSettingsStart: " << header;
EXPECT_EQ(Http2FrameType::SETTINGS, header.type) << header;
EXPECT_EQ(Http2FrameFlag(), header.flags) << header;
StartFrame(header)->OnSettingsStart(header);
}
void OnSetting(const Http2SettingFields& setting_fields) override {
QUICHE_VLOG(1) << "Http2SettingFields: setting_fields=" << setting_fields;
CurrentFrame()->OnSetting(setting_fields);
}
void OnSettingsEnd() override {
QUICHE_VLOG(1) << "OnSettingsEnd";
EndFrame()->OnSettingsEnd();
}
void OnSettingsAck(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnSettingsAck: " << header;
StartAndEndFrame(header)->OnSettingsAck(header);
}
void OnFrameSizeError(const Http2FrameHeader& header) override {
QUICHE_VLOG(1) << "OnFrameSizeError: " << header;
FrameError(header)->OnFrameSizeError(header);
}
};
class SettingsPayloadDecoderTest
: public AbstractPayloadDecoderTest<SettingsPayloadDecoder,
SettingsPayloadDecoderPeer, Listener> {
protected:
Http2SettingFields RandSettingsFields() {
Http2SettingFields fields;
test::Randomize(&fields, RandomPtr());
return fields;
}
};
TEST_F(SettingsPayloadDecoderTest, SettingsWrongSize) {
auto approve_size = [](size_t size) {
return 0 != (size % Http2SettingFields::EncodedSize());
};
Http2FrameBuilder fb;
fb.Append(RandSettingsFields());
fb.Append(RandSettingsFields());
fb.Append(RandSettingsFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size));
}
TEST_F(SettingsPayloadDecoderTest, SettingsAkcWrongSize) {
auto approve_size = [](size_t size) { return size != 0; };
Http2FrameBuilder fb;
fb.Append(RandSettingsFields());
fb.Append(RandSettingsFields());
fb.Append(RandSettingsFields());
EXPECT_TRUE(VerifyDetectsFrameSizeError(Http2FrameFlag::ACK, fb.buffer(),
approve_size));
}
TEST_F(SettingsPayloadDecoderTest, SettingsAck) {
for (int stream_id = 0; stream_id < 3; ++stream_id) {
Http2FrameHeader header(0, Http2FrameType::SETTINGS,
RandFlags() | Http2FrameFlag::ACK, stream_id);
set_frame_header(header);
FrameParts expected(header);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays("", expected));
}
}
TEST_F(SettingsPayloadDecoderTest, OneRealSetting) {
std::vector<uint32_t> values = {0, 1, 0xffffffff, Random().Rand32()};
for (auto param : AllHttp2SettingsParameters()) {
for (uint32_t value : values) {
Http2SettingFields fields(param, value);
Http2FrameBuilder fb;
fb.Append(fields);
Http2FrameHeader header(fb.size(), Http2FrameType::SETTINGS, RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
expected.AppendSetting(fields);
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
TEST_F(SettingsPayloadDecoderTest, ManySettings) {
const size_t num_settings = 100;
const size_t size = Http2SettingFields::EncodedSize() * num_settings;
Http2FrameHeader header(size, Http2FrameType::SETTINGS,
RandFlags(),
RandStreamId());
set_frame_header(header);
FrameParts expected(header);
Http2FrameBuilder fb;
for (size_t n = 0; n < num_settings; ++n) {
Http2SettingFields fields(static_cast<Http2SettingsParameter>(n),
Random().Rand32());
fb.Append(fields);
expected.AppendSetting(fields);
}
ASSERT_EQ(size, fb.size());
EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected));
}
}
}
} |
431 | cpp | google/quiche | http2_hpack_constants | quiche/http2/hpack/http2_hpack_constants.cc | quiche/http2/hpack/http2_hpack_constants_test.cc | #ifndef QUICHE_HTTP2_HPACK_HTTP2_HPACK_CONSTANTS_H_
#define QUICHE_HTTP2_HPACK_HTTP2_HPACK_CONSTANTS_H_
#include <ostream>
#include <string>
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
const size_t kFirstDynamicTableIndex = 62;
enum class HpackEntryType {
kIndexedHeader,
kIndexedLiteralHeader,
kUnindexedLiteralHeader,
kNeverIndexedLiteralHeader,
kDynamicTableSizeUpdate,
};
QUICHE_EXPORT std::string HpackEntryTypeToString(HpackEntryType v);
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, HpackEntryType v);
}
#endif
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
namespace http2 {
std::string HpackEntryTypeToString(HpackEntryType v) {
switch (v) {
case HpackEntryType::kIndexedHeader:
return "kIndexedHeader";
case HpackEntryType::kDynamicTableSizeUpdate:
return "kDynamicTableSizeUpdate";
case HpackEntryType::kIndexedLiteralHeader:
return "kIndexedLiteralHeader";
case HpackEntryType::kUnindexedLiteralHeader:
return "kUnindexedLiteralHeader";
case HpackEntryType::kNeverIndexedLiteralHeader:
return "kNeverIndexedLiteralHeader";
}
return absl::StrCat("UnknownHpackEntryType(", static_cast<int>(v), ")");
}
std::ostream& operator<<(std::ostream& out, HpackEntryType v) {
return out << HpackEntryTypeToString(v);
}
} | #include "quiche/http2/hpack/http2_hpack_constants.h"
#include <sstream>
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
TEST(HpackEntryTypeTest, HpackEntryTypeToString) {
EXPECT_EQ("kIndexedHeader",
HpackEntryTypeToString(HpackEntryType::kIndexedHeader));
EXPECT_EQ("kDynamicTableSizeUpdate",
HpackEntryTypeToString(HpackEntryType::kDynamicTableSizeUpdate));
EXPECT_EQ("kIndexedLiteralHeader",
HpackEntryTypeToString(HpackEntryType::kIndexedLiteralHeader));
EXPECT_EQ("kUnindexedLiteralHeader",
HpackEntryTypeToString(HpackEntryType::kUnindexedLiteralHeader));
EXPECT_EQ("kNeverIndexedLiteralHeader",
HpackEntryTypeToString(HpackEntryType::kNeverIndexedLiteralHeader));
EXPECT_EQ("UnknownHpackEntryType(12321)",
HpackEntryTypeToString(static_cast<HpackEntryType>(12321)));
}
TEST(HpackEntryTypeTest, OutputHpackEntryType) {
{
std::stringstream log;
log << HpackEntryType::kIndexedHeader;
EXPECT_EQ("kIndexedHeader", log.str());
}
{
std::stringstream log;
log << HpackEntryType::kDynamicTableSizeUpdate;
EXPECT_EQ("kDynamicTableSizeUpdate", log.str());
}
{
std::stringstream log;
log << HpackEntryType::kIndexedLiteralHeader;
EXPECT_EQ("kIndexedLiteralHeader", log.str());
}
{
std::stringstream log;
log << HpackEntryType::kUnindexedLiteralHeader;
EXPECT_EQ("kUnindexedLiteralHeader", log.str());
}
{
std::stringstream log;
log << HpackEntryType::kNeverIndexedLiteralHeader;
EXPECT_EQ("kNeverIndexedLiteralHeader", log.str());
}
{
std::stringstream log;
log << static_cast<HpackEntryType>(1234321);
EXPECT_EQ("UnknownHpackEntryType(1234321)", log.str());
}
}
}
}
} |
432 | cpp | google/quiche | hpack_entry_type_decoder | quiche/http2/hpack/decoder/hpack_entry_type_decoder.cc | quiche/http2/hpack/decoder/hpack_entry_type_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_TYPE_DECODER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_TYPE_DECODER_H_
#include <cstdint>
#include <string>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
class QUICHE_EXPORT HpackEntryTypeDecoder {
public:
DecodeStatus Start(DecodeBuffer* db);
DecodeStatus Resume(DecodeBuffer* db) { return varint_decoder_.Resume(db); }
HpackEntryType entry_type() const { return entry_type_; }
uint64_t varint() const { return varint_decoder_.value(); }
std::string DebugString() const;
private:
HpackVarintDecoder varint_decoder_;
HpackEntryType entry_type_ = HpackEntryType::kIndexedHeader;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackEntryTypeDecoder& v);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_entry_type_decoder.h"
#include <ios>
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::string HpackEntryTypeDecoder::DebugString() const {
return absl::StrCat(
"HpackEntryTypeDecoder(varint_decoder=", varint_decoder_.DebugString(),
", entry_type=", entry_type_, ")");
}
std::ostream& operator<<(std::ostream& out, const HpackEntryTypeDecoder& v) {
return out << v.DebugString();
}
DecodeStatus HpackEntryTypeDecoder::Start(DecodeBuffer* db) {
QUICHE_DCHECK(db != nullptr);
QUICHE_DCHECK(db->HasData());
uint8_t byte = db->DecodeUInt8();
switch (byte) {
case 0b00000000:
case 0b00000001:
case 0b00000010:
case 0b00000011:
case 0b00000100:
case 0b00000101:
case 0b00000110:
case 0b00000111:
case 0b00001000:
case 0b00001001:
case 0b00001010:
case 0b00001011:
case 0b00001100:
case 0b00001101:
case 0b00001110:
entry_type_ = HpackEntryType::kUnindexedLiteralHeader;
varint_decoder_.set_value(byte);
return DecodeStatus::kDecodeDone;
case 0b00001111:
entry_type_ = HpackEntryType::kUnindexedLiteralHeader;
return varint_decoder_.StartExtended(4, db);
case 0b00010000:
case 0b00010001:
case 0b00010010:
case 0b00010011:
case 0b00010100:
case 0b00010101:
case 0b00010110:
case 0b00010111:
case 0b00011000:
case 0b00011001:
case 0b00011010:
case 0b00011011:
case 0b00011100:
case 0b00011101:
case 0b00011110:
entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader;
varint_decoder_.set_value(byte & 0x0f);
return DecodeStatus::kDecodeDone;
case 0b00011111:
entry_type_ = HpackEntryType::kNeverIndexedLiteralHeader;
return varint_decoder_.StartExtended(4, db);
case 0b00100000:
case 0b00100001:
case 0b00100010:
case 0b00100011:
case 0b00100100:
case 0b00100101:
case 0b00100110:
case 0b00100111:
case 0b00101000:
case 0b00101001:
case 0b00101010:
case 0b00101011:
case 0b00101100:
case 0b00101101:
case 0b00101110:
case 0b00101111:
case 0b00110000:
case 0b00110001:
case 0b00110010:
case 0b00110011:
case 0b00110100:
case 0b00110101:
case 0b00110110:
case 0b00110111:
case 0b00111000:
case 0b00111001:
case 0b00111010:
case 0b00111011:
case 0b00111100:
case 0b00111101:
case 0b00111110:
entry_type_ = HpackEntryType::kDynamicTableSizeUpdate;
varint_decoder_.set_value(byte & 0x01f);
return DecodeStatus::kDecodeDone;
case 0b00111111:
entry_type_ = HpackEntryType::kDynamicTableSizeUpdate;
return varint_decoder_.StartExtended(5, db);
case 0b01000000:
case 0b01000001:
case 0b01000010:
case 0b01000011:
case 0b01000100:
case 0b01000101:
case 0b01000110:
case 0b01000111:
case 0b01001000:
case 0b01001001:
case 0b01001010:
case 0b01001011:
case 0b01001100:
case 0b01001101:
case 0b01001110:
case 0b01001111:
case 0b01010000:
case 0b01010001:
case 0b01010010:
case 0b01010011:
case 0b01010100:
case 0b01010101:
case 0b01010110:
case 0b01010111:
case 0b01011000:
case 0b01011001:
case 0b01011010:
case 0b01011011:
case 0b01011100:
case 0b01011101:
case 0b01011110:
case 0b01011111:
case 0b01100000:
case 0b01100001:
case 0b01100010:
case 0b01100011:
case 0b01100100:
case 0b01100101:
case 0b01100110:
case 0b01100111:
case 0b01101000:
case 0b01101001:
case 0b01101010:
case 0b01101011:
case 0b01101100:
case 0b01101101:
case 0b01101110:
case 0b01101111:
case 0b01110000:
case 0b01110001:
case 0b01110010:
case 0b01110011:
case 0b01110100:
case 0b01110101:
case 0b01110110:
case 0b01110111:
case 0b01111000:
case 0b01111001:
case 0b01111010:
case 0b01111011:
case 0b01111100:
case 0b01111101:
case 0b01111110:
entry_type_ = HpackEntryType::kIndexedLiteralHeader;
varint_decoder_.set_value(byte & 0x03f);
return DecodeStatus::kDecodeDone;
case 0b01111111:
entry_type_ = HpackEntryType::kIndexedLiteralHeader;
return varint_decoder_.StartExtended(6, db);
case 0b10000000:
case 0b10000001:
case 0b10000010:
case 0b10000011:
case 0b10000100:
case 0b10000101:
case 0b10000110:
case 0b10000111:
case 0b10001000:
case 0b10001001:
case 0b10001010:
case 0b10001011:
case 0b10001100:
case 0b10001101:
case 0b10001110:
case 0b10001111:
case 0b10010000:
case 0b10010001:
case 0b10010010:
case 0b10010011:
case 0b10010100:
case 0b10010101:
case 0b10010110:
case 0b10010111:
case 0b10011000:
case 0b10011001:
case 0b10011010:
case 0b10011011:
case 0b10011100:
case 0b10011101:
case 0b10011110:
case 0b10011111:
case 0b10100000:
case 0b10100001:
case 0b10100010:
case 0b10100011:
case 0b10100100:
case 0b10100101:
case 0b10100110:
case 0b10100111:
case 0b10101000:
case 0b10101001:
case 0b10101010:
case 0b10101011:
case 0b10101100:
case 0b10101101:
case 0b10101110:
case 0b10101111:
case 0b10110000:
case 0b10110001:
case 0b10110010:
case 0b10110011:
case 0b10110100:
case 0b10110101:
case 0b10110110:
case 0b10110111:
case 0b10111000:
case 0b10111001:
case 0b10111010:
case 0b10111011:
case 0b10111100:
case 0b10111101:
case 0b10111110:
case 0b10111111:
case 0b11000000:
case 0b11000001:
case 0b11000010:
case 0b11000011:
case 0b11000100:
case 0b11000101:
case 0b11000110:
case 0b11000111:
case 0b11001000:
case 0b11001001:
case 0b11001010:
case 0b11001011:
case 0b11001100:
case 0b11001101:
case 0b11001110:
case 0b11001111:
case 0b11010000:
case 0b11010001:
case 0b11010010:
case 0b11010011:
case 0b11010100:
case 0b11010101:
case 0b11010110:
case 0b11010111:
case 0b11011000:
case 0b11011001:
case 0b11011010:
case 0b11011011:
case 0b11011100:
case 0b11011101:
case 0b11011110:
case 0b11011111:
case 0b11100000:
case 0b11100001:
case 0b11100010:
case 0b11100011:
case 0b11100100:
case 0b11100101:
case 0b11100110:
case 0b11100111:
case 0b11101000:
case 0b11101001:
case 0b11101010:
case 0b11101011:
case 0b11101100:
case 0b11101101:
case 0b11101110:
case 0b11101111:
case 0b11110000:
case 0b11110001:
case 0b11110010:
case 0b11110011:
case 0b11110100:
case 0b11110101:
case 0b11110110:
case 0b11110111:
case 0b11111000:
case 0b11111001:
case 0b11111010:
case 0b11111011:
case 0b11111100:
case 0b11111101:
case 0b11111110:
entry_type_ = HpackEntryType::kIndexedHeader;
varint_decoder_.set_value(byte & 0x07f);
return DecodeStatus::kDecodeDone;
case 0b11111111:
entry_type_ = HpackEntryType::kIndexedHeader;
return varint_decoder_.StartExtended(7, db);
}
QUICHE_BUG(http2_bug_66_1)
<< "Unreachable, byte=" << std::hex << static_cast<uint32_t>(byte);
QUICHE_CODE_COUNT_N(decompress_failure_3, 17, 23);
return DecodeStatus::kDecodeError;
}
} | #include "quiche/http2/hpack/decoder/hpack_entry_type_decoder.h"
#include <vector>
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
namespace {
const bool kReturnNonZeroOnFirst = true;
class HpackEntryTypeDecoderTest : public RandomDecoderTest {
protected:
DecodeStatus StartDecoding(DecodeBuffer* b) override {
QUICHE_CHECK_LT(0u, b->Remaining());
return decoder_.Start(b);
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
return decoder_.Resume(b);
}
HpackEntryTypeDecoder decoder_;
};
TEST_F(HpackEntryTypeDecoderTest, DynamicTableSizeUpdate) {
for (uint32_t size = 0; size < 1000 * 1000; size += 256) {
HpackBlockBuilder bb;
bb.AppendDynamicTableSizeUpdate(size);
DecodeBuffer db(bb.buffer());
auto validator = [size, this]() -> AssertionResult {
HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate,
decoder_.entry_type());
HTTP2_VERIFY_EQ(size, decoder_.varint());
return AssertionSuccess();
};
EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst,
ValidateDoneAndEmpty(validator)))
<< "\nentry_type=kDynamicTableSizeUpdate, size=" << size;
EXPECT_TRUE(validator());
}
}
TEST_F(HpackEntryTypeDecoderTest, HeaderWithIndex) {
std::vector<HpackEntryType> entry_types = {
HpackEntryType::kIndexedHeader,
HpackEntryType::kIndexedLiteralHeader,
HpackEntryType::kUnindexedLiteralHeader,
HpackEntryType::kNeverIndexedLiteralHeader,
};
for (const HpackEntryType entry_type : entry_types) {
const uint32_t first = entry_type == HpackEntryType::kIndexedHeader ? 1 : 0;
for (uint32_t index = first; index < 1000; ++index) {
HpackBlockBuilder bb;
bb.AppendEntryTypeAndVarint(entry_type, index);
DecodeBuffer db(bb.buffer());
auto validator = [entry_type, index, this]() -> AssertionResult {
HTTP2_VERIFY_EQ(entry_type, decoder_.entry_type());
HTTP2_VERIFY_EQ(index, decoder_.varint());
return AssertionSuccess();
};
EXPECT_TRUE(DecodeAndValidateSeveralWays(&db, kReturnNonZeroOnFirst,
ValidateDoneAndEmpty(validator)))
<< "\nentry_type=" << entry_type << ", index=" << index;
EXPECT_TRUE(validator());
}
}
}
}
}
} |
433 | cpp | google/quiche | hpack_string_decoder | quiche/http2/hpack/decoder/hpack_string_decoder.cc | quiche/http2/hpack/decoder/hpack_string_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_STRING_DECODER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_STRING_DECODER_H_
#include <stddef.h>
#include <algorithm>
#include <cstdint>
#include <string>
#include "absl/base/macros.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
class QUICHE_EXPORT HpackStringDecoder {
public:
enum StringDecoderState {
kStartDecodingLength,
kDecodingString,
kResumeDecodingLength,
};
template <class Listener>
DecodeStatus Start(DecodeBuffer* db, Listener* cb) {
if (db->HasData() && (*db->cursor() & 0x7f) != 0x7f) {
uint8_t h_and_prefix = db->DecodeUInt8();
uint8_t length = h_and_prefix & 0x7f;
bool huffman_encoded = (h_and_prefix & 0x80) == 0x80;
cb->OnStringStart(huffman_encoded, length);
if (length <= db->Remaining()) {
cb->OnStringData(db->cursor(), length);
db->AdvanceCursor(length);
cb->OnStringEnd();
return DecodeStatus::kDecodeDone;
}
huffman_encoded_ = huffman_encoded;
remaining_ = length;
state_ = kDecodingString;
return Resume(db, cb);
}
state_ = kStartDecodingLength;
return Resume(db, cb);
}
template <class Listener>
DecodeStatus Resume(DecodeBuffer* db, Listener* cb) {
DecodeStatus status;
while (true) {
switch (state_) {
case kStartDecodingLength:
QUICHE_DVLOG(2) << "kStartDecodingLength: db->Remaining="
<< db->Remaining();
if (!StartDecodingLength(db, cb, &status)) {
return status;
}
ABSL_FALLTHROUGH_INTENDED;
case kDecodingString:
QUICHE_DVLOG(2) << "kDecodingString: db->Remaining="
<< db->Remaining() << " remaining_=" << remaining_;
return DecodeString(db, cb);
case kResumeDecodingLength:
QUICHE_DVLOG(2) << "kResumeDecodingLength: db->Remaining="
<< db->Remaining();
if (!ResumeDecodingLength(db, cb, &status)) {
return status;
}
}
}
}
std::string DebugString() const;
private:
static std::string StateToString(StringDecoderState v);
template <class Listener>
bool StartDecodingLength(DecodeBuffer* db, Listener* cb,
DecodeStatus* status) {
if (db->Empty()) {
*status = DecodeStatus::kDecodeInProgress;
state_ = kStartDecodingLength;
return false;
}
uint8_t h_and_prefix = db->DecodeUInt8();
huffman_encoded_ = (h_and_prefix & 0x80) == 0x80;
*status = length_decoder_.Start(h_and_prefix, 7, db);
if (*status == DecodeStatus::kDecodeDone) {
OnStringStart(cb, status);
return true;
}
state_ = kResumeDecodingLength;
return false;
}
template <class Listener>
bool ResumeDecodingLength(DecodeBuffer* db, Listener* cb,
DecodeStatus* status) {
QUICHE_DCHECK_EQ(state_, kResumeDecodingLength);
*status = length_decoder_.Resume(db);
if (*status == DecodeStatus::kDecodeDone) {
state_ = kDecodingString;
OnStringStart(cb, status);
return true;
}
return false;
}
template <class Listener>
void OnStringStart(Listener* cb, DecodeStatus* ) {
remaining_ = static_cast<size_t>(length_decoder_.value());
cb->OnStringStart(huffman_encoded_, remaining_);
}
template <class Listener>
DecodeStatus DecodeString(DecodeBuffer* db, Listener* cb) {
size_t len = std::min(remaining_, db->Remaining());
if (len > 0) {
cb->OnStringData(db->cursor(), len);
db->AdvanceCursor(len);
remaining_ -= len;
}
if (remaining_ == 0) {
cb->OnStringEnd();
return DecodeStatus::kDecodeDone;
}
state_ = kDecodingString;
return DecodeStatus::kDecodeInProgress;
}
HpackVarintDecoder length_decoder_;
size_t remaining_ = 0;
StringDecoderState state_ = kStartDecodingLength;
bool huffman_encoded_ = false;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackStringDecoder& v);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_string_decoder.h"
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
namespace http2 {
std::string HpackStringDecoder::DebugString() const {
return absl::StrCat("HpackStringDecoder(state=", StateToString(state_),
", length=", length_decoder_.DebugString(),
", remaining=", remaining_,
", huffman=", huffman_encoded_ ? "true)" : "false)");
}
std::string HpackStringDecoder::StateToString(StringDecoderState v) {
switch (v) {
case kStartDecodingLength:
return "kStartDecodingLength";
case kDecodingString:
return "kDecodingString";
case kResumeDecodingLength:
return "kResumeDecodingLength";
}
return absl::StrCat("UNKNOWN_STATE(", static_cast<uint32_t>(v), ")");
}
std::ostream& operator<<(std::ostream& out, const HpackStringDecoder& v) {
return out << v.DebugString();
}
} | #include "quiche/http2/hpack/decoder/hpack_string_decoder.h"
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/decoder/hpack_string_decoder_listener.h"
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_string_collector.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
const bool kMayReturnZeroOnFirst = false;
const bool kCompressed = true;
const bool kUncompressed = false;
class HpackStringDecoderTest : public RandomDecoderTest {
protected:
HpackStringDecoderTest() : listener_(&collector_) {}
DecodeStatus StartDecoding(DecodeBuffer* b) override {
++start_decoding_calls_;
collector_.Clear();
return decoder_.Start(b, &listener_);
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
QUICHE_VLOG(1) << decoder_.DebugString();
QUICHE_VLOG(2) << collector_;
return decoder_.Resume(b, &listener_);
}
AssertionResult Collected(absl::string_view s, bool huffman_encoded) {
QUICHE_VLOG(1) << collector_;
return collector_.Collected(s, huffman_encoded);
}
Validator MakeValidator(const std::string& expected_str,
bool expected_huffman) {
return [expected_str, expected_huffman, this](
const DecodeBuffer& ,
DecodeStatus ) -> AssertionResult {
AssertionResult result = Collected(expected_str, expected_huffman);
if (result) {
HTTP2_VERIFY_EQ(collector_,
HpackStringCollector(expected_str, expected_huffman));
} else {
HTTP2_VERIFY_NE(collector_,
HpackStringCollector(expected_str, expected_huffman));
}
QUICHE_VLOG(2) << collector_.ToString();
collector_.Clear();
QUICHE_VLOG(2) << collector_;
return result;
};
}
HpackStringDecoder decoder_;
HpackStringCollector collector_;
HpackStringDecoderVLoggingListener listener_;
size_t start_decoding_calls_ = 0;
};
TEST_F(HpackStringDecoderTest, DecodeEmptyString) {
{
Validator validator = ValidateDoneAndEmpty(MakeValidator("", kCompressed));
const char kData[] = {'\x80'};
DecodeBuffer b(kData);
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));
}
{
Validator validator =
ValidateDoneAndOffset(1, MakeValidator("", kUncompressed));
const char kData[] = {'\x00', '\xff'};
DecodeBuffer b(kData);
EXPECT_EQ(2u, b.Remaining());
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));
EXPECT_EQ(1u, b.Remaining());
}
}
TEST_F(HpackStringDecoderTest, DecodeShortString) {
{
Validator validator =
ValidateDoneAndOffset(11, MakeValidator("start end.", kCompressed));
const char kData[] = "\x8astart end.Don't peek at this.";
DecodeBuffer b(kData);
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));
}
{
Validator validator =
ValidateDoneAndOffset(11, MakeValidator("start end.", kUncompressed));
absl::string_view data("\x0astart end.");
DecodeBuffer b(data);
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, kMayReturnZeroOnFirst, validator));
}
}
TEST_F(HpackStringDecoderTest, DecodeLongStrings) {
std::string name = Random().RandString(1024);
std::string value = Random().RandString(65536);
HpackBlockBuilder hbb;
hbb.AppendString(false, name);
uint32_t offset_after_name = hbb.size();
EXPECT_EQ(3 + name.size(), offset_after_name);
hbb.AppendString(true, value);
uint32_t offset_after_value = hbb.size();
EXPECT_EQ(3 + name.size() + 4 + value.size(), offset_after_value);
DecodeBuffer b(hbb.buffer());
EXPECT_TRUE(DecodeAndValidateSeveralWays(
&b, kMayReturnZeroOnFirst,
ValidateDoneAndOffset(offset_after_name,
MakeValidator(name, kUncompressed))));
EXPECT_EQ(offset_after_name, b.Offset());
EXPECT_EQ(offset_after_value - offset_after_name, b.Remaining());
EXPECT_TRUE(DecodeAndValidateSeveralWays(
&b, kMayReturnZeroOnFirst,
ValidateDoneAndOffset(offset_after_value - offset_after_name,
MakeValidator(value, kCompressed))));
EXPECT_EQ(offset_after_value, b.Offset());
EXPECT_EQ(0u, b.Remaining());
}
}
}
} |
434 | cpp | google/quiche | hpack_decoder_string_buffer | quiche/http2/hpack/decoder/hpack_decoder_string_buffer.cc | quiche/http2/hpack/decoder/hpack_decoder_string_buffer_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STRING_BUFFER_H_
#include <stddef.h>
#include <ostream>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT HpackDecoderStringBuffer {
public:
enum class State : uint8_t { RESET, COLLECTING, COMPLETE };
enum class Backing : uint8_t { RESET, UNBUFFERED, BUFFERED };
HpackDecoderStringBuffer();
~HpackDecoderStringBuffer();
HpackDecoderStringBuffer(const HpackDecoderStringBuffer&) = delete;
HpackDecoderStringBuffer& operator=(const HpackDecoderStringBuffer&) = delete;
void Reset();
void OnStart(bool huffman_encoded, size_t len);
bool OnData(const char* data, size_t len);
bool OnEnd();
void BufferStringIfUnbuffered();
bool IsBuffered() const;
size_t BufferedLength() const;
absl::string_view str() const;
absl::string_view GetStringIfComplete() const;
std::string ReleaseString();
State state_for_testing() const { return state_; }
Backing backing_for_testing() const { return backing_; }
void OutputDebugStringTo(std::ostream& out) const;
private:
std::string buffer_;
absl::string_view value_;
HpackHuffmanDecoder decoder_;
size_t remaining_len_;
bool is_huffman_encoded_;
State state_;
Backing backing_;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer& v);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <ostream>
#include <string>
#include <utility>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::State v) {
switch (v) {
case HpackDecoderStringBuffer::State::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::State::COLLECTING:
return out << "COLLECTING";
case HpackDecoderStringBuffer::State::COMPLETE:
return out << "COMPLETE";
}
int unknown = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_1)
<< "Invalid HpackDecoderStringBuffer::State: " << unknown;
return out << "HpackDecoderStringBuffer::State(" << unknown << ")";
}
std::ostream& operator<<(std::ostream& out,
const HpackDecoderStringBuffer::Backing v) {
switch (v) {
case HpackDecoderStringBuffer::Backing::RESET:
return out << "RESET";
case HpackDecoderStringBuffer::Backing::UNBUFFERED:
return out << "UNBUFFERED";
case HpackDecoderStringBuffer::Backing::BUFFERED:
return out << "BUFFERED";
}
auto v2 = static_cast<int>(v);
QUICHE_BUG(http2_bug_50_2)
<< "Invalid HpackDecoderStringBuffer::Backing: " << v2;
return out << "HpackDecoderStringBuffer::Backing(" << v2 << ")";
}
HpackDecoderStringBuffer::HpackDecoderStringBuffer()
: remaining_len_(0),
is_huffman_encoded_(false),
state_(State::RESET),
backing_(Backing::RESET) {}
HpackDecoderStringBuffer::~HpackDecoderStringBuffer() = default;
void HpackDecoderStringBuffer::Reset() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::Reset";
state_ = State::RESET;
}
void HpackDecoderStringBuffer::OnStart(bool huffman_encoded, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnStart";
QUICHE_DCHECK_EQ(state_, State::RESET);
remaining_len_ = len;
is_huffman_encoded_ = huffman_encoded;
state_ = State::COLLECTING;
if (huffman_encoded) {
decoder_.Reset();
buffer_.clear();
backing_ = Backing::BUFFERED;
len = len * 8 / 5;
if (buffer_.capacity() < len) {
buffer_.reserve(len);
}
} else {
backing_ = Backing::RESET;
value_ = absl::string_view();
}
}
bool HpackDecoderStringBuffer::OnData(const char* data, size_t len) {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnData state=" << state_
<< ", backing=" << backing_;
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_LE(len, remaining_len_);
remaining_len_ -= len;
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
return decoder_.Decode(absl::string_view(data, len), &buffer_);
}
if (backing_ == Backing::RESET) {
if (remaining_len_ == 0) {
value_ = absl::string_view(data, len);
backing_ = Backing::UNBUFFERED;
return true;
}
backing_ = Backing::BUFFERED;
buffer_.reserve(remaining_len_ + len);
buffer_.assign(data, len);
return true;
}
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
buffer_.append(data, len);
return true;
}
bool HpackDecoderStringBuffer::OnEnd() {
QUICHE_DVLOG(2) << "HpackDecoderStringBuffer::OnEnd";
QUICHE_DCHECK_EQ(state_, State::COLLECTING);
QUICHE_DCHECK_EQ(0u, remaining_len_);
if (is_huffman_encoded_) {
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (!decoder_.InputProperlyTerminated()) {
return false;
}
value_ = buffer_;
} else if (backing_ == Backing::BUFFERED) {
value_ = buffer_;
}
state_ = State::COMPLETE;
return true;
}
void HpackDecoderStringBuffer::BufferStringIfUnbuffered() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferStringIfUnbuffered state="
<< state_ << ", backing=" << backing_;
if (state_ != State::RESET && backing_ == Backing::UNBUFFERED) {
QUICHE_DVLOG(2)
<< "HpackDecoderStringBuffer buffering std::string of length "
<< value_.size();
buffer_.assign(value_.data(), value_.size());
if (state_ == State::COMPLETE) {
value_ = buffer_;
}
backing_ = Backing::BUFFERED;
}
}
bool HpackDecoderStringBuffer::IsBuffered() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::IsBuffered";
return state_ != State::RESET && backing_ == Backing::BUFFERED;
}
size_t HpackDecoderStringBuffer::BufferedLength() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::BufferedLength";
return IsBuffered() ? buffer_.size() : 0;
}
absl::string_view HpackDecoderStringBuffer::str() const {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::str";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
return value_;
}
absl::string_view HpackDecoderStringBuffer::GetStringIfComplete() const {
if (state_ != State::COMPLETE) {
return {};
}
return str();
}
std::string HpackDecoderStringBuffer::ReleaseString() {
QUICHE_DVLOG(3) << "HpackDecoderStringBuffer::ReleaseString";
QUICHE_DCHECK_EQ(state_, State::COMPLETE);
QUICHE_DCHECK_EQ(backing_, Backing::BUFFERED);
if (state_ == State::COMPLETE) {
state_ = State::RESET;
if (backing_ == Backing::BUFFERED) {
return std::move(buffer_);
} else {
return std::string(value_);
}
}
return "";
}
void HpackDecoderStringBuffer::OutputDebugStringTo(std::ostream& out) const {
out << "{state=" << state_;
if (state_ != State::RESET) {
out << ", backing=" << backing_;
out << ", remaining_len=" << remaining_len_;
out << ", is_huffman_encoded=" << is_huffman_encoded_;
if (backing_ == Backing::BUFFERED) {
out << ", buffer: " << buffer_;
} else {
out << ", value: " << value_;
}
}
out << "}";
}
std::ostream& operator<<(std::ostream& out, const HpackDecoderStringBuffer& v) {
v.OutputDebugStringTo(out);
return out;
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include <initializer_list>
#include <sstream>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::HasSubstr;
namespace http2 {
namespace test {
namespace {
class HpackDecoderStringBufferTest : public quiche::test::QuicheTest {
protected:
typedef HpackDecoderStringBuffer::State State;
typedef HpackDecoderStringBuffer::Backing Backing;
State state() const { return buf_.state_for_testing(); }
Backing backing() const { return buf_.backing_for_testing(); }
AssertionResult VerifyLogHasSubstrs(std::initializer_list<std::string> strs) {
QUICHE_VLOG(1) << buf_;
std::ostringstream ss;
buf_.OutputDebugStringTo(ss);
std::string dbg_str(ss.str());
for (const auto& expected : strs) {
HTTP2_VERIFY_TRUE(absl::StrContains(dbg_str, expected));
}
return AssertionSuccess();
}
HpackDecoderStringBuffer buf_;
};
TEST_F(HpackDecoderStringBufferTest, PlainWhole) {
absl::string_view data("some text.");
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(data.data(), data.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::UNBUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=UNBUFFERED", "value: some text."}));
EXPECT_EQ(data.data(), buf_.str().data());
buf_.BufferStringIfUnbuffered();
QUICHE_LOG(INFO) << buf_;
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(data, buf_.str());
EXPECT_NE(data.data(), buf_.str().data());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"state=COMPLETE", "backing=BUFFERED", "buffer: some text."}));
}
TEST_F(HpackDecoderStringBufferTest, PlainSplit) {
absl::string_view data("some text.");
absl::string_view part1 = data.substr(0, 1);
absl::string_view part2 = data.substr(1);
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( false, data.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::RESET);
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), part1.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
QUICHE_LOG(INFO) << buf_;
absl::string_view buffered = buf_.str();
EXPECT_EQ(data, buffered);
EXPECT_NE(data.data(), buffered.data());
buf_.BufferStringIfUnbuffered();
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), data.size());
EXPECT_EQ(buffered, buf_.str());
EXPECT_EQ(buffered.data(), buf_.str().data());
}
TEST_F(HpackDecoderStringBufferTest, HuffmanWhole) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
EXPECT_TRUE(VerifyLogHasSubstrs(
{"{state=COMPLETE", "backing=BUFFERED", "buffer: www.example.com}"}));
std::string s = buf_.ReleaseString();
EXPECT_EQ(s, decoded);
EXPECT_EQ(state(), State::RESET);
}
TEST_F(HpackDecoderStringBufferTest, HuffmanSplit) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("f1e3c2e5f23a6ba0ab90f4ff", &encoded));
std::string part1 = encoded.substr(0, 5);
std::string part2 = encoded.substr(5);
absl::string_view decoded("www.example.com");
EXPECT_EQ(state(), State::RESET);
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(0u, buf_.BufferedLength());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part1.data(), part1.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_GT(buf_.BufferedLength(), 0u);
EXPECT_LT(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnData(part2.data(), part2.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
QUICHE_LOG(INFO) << buf_;
EXPECT_TRUE(buf_.OnEnd());
EXPECT_EQ(state(), State::COMPLETE);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_EQ(buf_.BufferedLength(), decoded.size());
EXPECT_EQ(decoded, buf_.str());
QUICHE_LOG(INFO) << buf_;
buf_.Reset();
EXPECT_EQ(state(), State::RESET);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnData) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("ffffffff", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_FALSE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
QUICHE_LOG(INFO) << buf_;
}
TEST_F(HpackDecoderStringBufferTest, InvalidHuffmanOnEnd) {
std::string encoded;
ASSERT_TRUE(absl::HexStringToBytes("00", &encoded));
buf_.OnStart( true, encoded.size());
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_TRUE(buf_.OnData(encoded.data(), encoded.size()));
EXPECT_EQ(state(), State::COLLECTING);
EXPECT_EQ(backing(), Backing::BUFFERED);
EXPECT_FALSE(buf_.OnEnd());
QUICHE_LOG(INFO) << buf_;
}
}
}
} |
435 | cpp | google/quiche | hpack_decoder_state | quiche/http2/hpack/decoder/hpack_decoder_state.cc | quiche/http2/hpack/decoder/hpack_decoder_state_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STATE_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_STATE_H_
#include <stddef.h>
#include <cstdint>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_listener.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h"
#include "quiche/http2/hpack/decoder/hpack_decoding_error.h"
#include "quiche/http2/hpack/decoder/hpack_whole_entry_listener.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class HpackDecoderStatePeer;
}
class QUICHE_EXPORT HpackDecoderState : public HpackWholeEntryListener {
public:
explicit HpackDecoderState(HpackDecoderListener* listener);
~HpackDecoderState() override;
HpackDecoderState(const HpackDecoderState&) = delete;
HpackDecoderState& operator=(const HpackDecoderState&) = delete;
HpackDecoderListener* listener() const { return listener_; }
void ApplyHeaderTableSizeSetting(uint32_t max_header_table_size);
size_t GetCurrentHeaderTableSizeSetting() const {
return final_header_table_size_;
}
void OnHeaderBlockStart();
void OnIndexedHeader(size_t index) override;
void OnNameIndexAndLiteralValue(
HpackEntryType entry_type, size_t name_index,
HpackDecoderStringBuffer* value_buffer) override;
void OnLiteralNameAndValue(HpackEntryType entry_type,
HpackDecoderStringBuffer* name_buffer,
HpackDecoderStringBuffer* value_buffer) override;
void OnDynamicTableSizeUpdate(size_t size) override;
void OnHpackDecodeError(HpackDecodingError error) override;
void OnHeaderBlockEnd();
HpackDecodingError error() const { return error_; }
size_t GetDynamicTableSize() const {
return decoder_tables_.current_header_table_size();
}
const HpackDecoderTables& decoder_tables_for_test() const {
return decoder_tables_;
}
private:
friend class test::HpackDecoderStatePeer;
void ReportError(HpackDecodingError error);
HpackDecoderTables decoder_tables_;
HpackDecoderListener* listener_;
uint32_t final_header_table_size_;
uint32_t lowest_header_table_size_;
bool require_dynamic_table_size_update_;
bool allow_dynamic_table_size_update_;
bool saw_dynamic_table_size_update_;
HpackDecodingError error_;
};
}
#endif
#include "quiche/http2/hpack/decoder/hpack_decoder_state.h"
#include <string>
#include <utility>
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace {
std::string ExtractString(HpackDecoderStringBuffer* string_buffer) {
if (string_buffer->IsBuffered()) {
return string_buffer->ReleaseString();
} else {
auto result = std::string(string_buffer->str());
string_buffer->Reset();
return result;
}
}
}
HpackDecoderState::HpackDecoderState(HpackDecoderListener* listener)
: listener_(listener),
final_header_table_size_(Http2SettingsInfo::DefaultHeaderTableSize()),
lowest_header_table_size_(final_header_table_size_),
require_dynamic_table_size_update_(false),
allow_dynamic_table_size_update_(true),
saw_dynamic_table_size_update_(false),
error_(HpackDecodingError::kOk) {
QUICHE_CHECK(listener_);
}
HpackDecoderState::~HpackDecoderState() = default;
void HpackDecoderState::ApplyHeaderTableSizeSetting(
uint32_t header_table_size) {
QUICHE_DVLOG(2) << "HpackDecoderState::ApplyHeaderTableSizeSetting("
<< header_table_size << ")";
QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);
if (header_table_size < lowest_header_table_size_) {
lowest_header_table_size_ = header_table_size;
}
final_header_table_size_ = header_table_size;
QUICHE_DVLOG(2) << "low water mark: " << lowest_header_table_size_;
QUICHE_DVLOG(2) << "final limit: " << final_header_table_size_;
}
void HpackDecoderState::OnHeaderBlockStart() {
QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderBlockStart";
QUICHE_DCHECK(error_ == HpackDecodingError::kOk)
<< HpackDecodingErrorToString(error_);
QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);
allow_dynamic_table_size_update_ = true;
saw_dynamic_table_size_update_ = false;
require_dynamic_table_size_update_ =
(lowest_header_table_size_ <
decoder_tables_.current_header_table_size() ||
final_header_table_size_ < decoder_tables_.header_table_size_limit());
QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderListStart "
<< "require_dynamic_table_size_update_="
<< require_dynamic_table_size_update_;
listener_->OnHeaderListStart();
}
void HpackDecoderState::OnIndexedHeader(size_t index) {
QUICHE_DVLOG(2) << "HpackDecoderState::OnIndexedHeader: " << index;
if (error_ != HpackDecodingError::kOk) {
return;
}
if (require_dynamic_table_size_update_) {
ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);
return;
}
allow_dynamic_table_size_update_ = false;
const HpackStringPair* entry = decoder_tables_.Lookup(index);
if (entry != nullptr) {
listener_->OnHeader(entry->name, entry->value);
} else {
ReportError(HpackDecodingError::kInvalidIndex);
}
}
void HpackDecoderState::OnNameIndexAndLiteralValue(
HpackEntryType entry_type, size_t name_index,
HpackDecoderStringBuffer* value_buffer) {
QUICHE_DVLOG(2) << "HpackDecoderState::OnNameIndexAndLiteralValue "
<< entry_type << ", " << name_index << ", "
<< value_buffer->str();
if (error_ != HpackDecodingError::kOk) {
return;
}
if (require_dynamic_table_size_update_) {
ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);
return;
}
allow_dynamic_table_size_update_ = false;
const HpackStringPair* entry = decoder_tables_.Lookup(name_index);
if (entry != nullptr) {
std::string value(ExtractString(value_buffer));
listener_->OnHeader(entry->name, value);
if (entry_type == HpackEntryType::kIndexedLiteralHeader) {
decoder_tables_.Insert(entry->name, std::move(value));
}
} else {
ReportError(HpackDecodingError::kInvalidNameIndex);
}
}
void HpackDecoderState::OnLiteralNameAndValue(
HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer,
HpackDecoderStringBuffer* value_buffer) {
QUICHE_DVLOG(2) << "HpackDecoderState::OnLiteralNameAndValue " << entry_type
<< ", " << name_buffer->str() << ", " << value_buffer->str();
if (error_ != HpackDecodingError::kOk) {
return;
}
if (require_dynamic_table_size_update_) {
ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);
return;
}
allow_dynamic_table_size_update_ = false;
std::string name(ExtractString(name_buffer));
std::string value(ExtractString(value_buffer));
listener_->OnHeader(name, value);
if (entry_type == HpackEntryType::kIndexedLiteralHeader) {
decoder_tables_.Insert(std::move(name), std::move(value));
}
}
void HpackDecoderState::OnDynamicTableSizeUpdate(size_t size_limit) {
QUICHE_DVLOG(2) << "HpackDecoderState::OnDynamicTableSizeUpdate "
<< size_limit << ", required="
<< (require_dynamic_table_size_update_ ? "true" : "false")
<< ", allowed="
<< (allow_dynamic_table_size_update_ ? "true" : "false");
if (error_ != HpackDecodingError::kOk) {
return;
}
QUICHE_DCHECK_LE(lowest_header_table_size_, final_header_table_size_);
if (!allow_dynamic_table_size_update_) {
ReportError(HpackDecodingError::kDynamicTableSizeUpdateNotAllowed);
return;
}
if (require_dynamic_table_size_update_) {
if (size_limit > lowest_header_table_size_) {
ReportError(HpackDecodingError::
kInitialDynamicTableSizeUpdateIsAboveLowWaterMark);
return;
}
require_dynamic_table_size_update_ = false;
} else if (size_limit > final_header_table_size_) {
ReportError(
HpackDecodingError::kDynamicTableSizeUpdateIsAboveAcknowledgedSetting);
return;
}
decoder_tables_.DynamicTableSizeUpdate(size_limit);
if (saw_dynamic_table_size_update_) {
allow_dynamic_table_size_update_ = false;
} else {
saw_dynamic_table_size_update_ = true;
}
lowest_header_table_size_ = final_header_table_size_;
}
void HpackDecoderState::OnHpackDecodeError(HpackDecodingError error) {
QUICHE_DVLOG(2) << "HpackDecoderState::OnHpackDecodeError "
<< HpackDecodingErrorToString(error);
if (error_ == HpackDecodingError::kOk) {
ReportError(error);
}
}
void HpackDecoderState::OnHeaderBlockEnd() {
QUICHE_DVLOG(2) << "HpackDecoderState::OnHeaderBlockEnd";
if (error_ != HpackDecodingError::kOk) {
return;
}
if (require_dynamic_table_size_update_) {
ReportError(HpackDecodingError::kMissingDynamicTableSizeUpdate);
} else {
listener_->OnHeaderListEnd();
}
}
void HpackDecoderState::ReportError(HpackDecodingError error) {
QUICHE_DVLOG(2) << "HpackDecoderState::ReportError is new="
<< (error_ == HpackDecodingError::kOk ? "true" : "false")
<< ", error: " << HpackDecodingErrorToString(error);
if (error_ == HpackDecodingError::kOk) {
listener_->OnHeaderErrorDetected(HpackDecodingErrorToString(error));
error_ = error;
}
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder_state.h"
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::Eq;
using ::testing::Mock;
using ::testing::StrictMock;
namespace http2 {
namespace test {
class HpackDecoderStatePeer {
public:
static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) {
return &state->decoder_tables_;
}
};
namespace {
class MockHpackDecoderListener : public HpackDecoderListener {
public:
MOCK_METHOD(void, OnHeaderListStart, (), (override));
MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value),
(override));
MOCK_METHOD(void, OnHeaderListEnd, (), (override));
MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message),
(override));
};
enum StringBacking { UNBUFFERED, BUFFERED };
class HpackDecoderStateTest : public quiche::test::QuicheTest {
protected:
HpackDecoderStateTest() : decoder_state_(&listener_) {}
HpackDecoderTables* GetDecoderTables() {
return HpackDecoderStatePeer::GetDecoderTables(&decoder_state_);
}
const HpackStringPair* Lookup(size_t index) {
return GetDecoderTables()->Lookup(index);
}
size_t current_header_table_size() {
return GetDecoderTables()->current_header_table_size();
}
size_t header_table_size_limit() {
return GetDecoderTables()->header_table_size_limit();
}
void set_header_table_size_limit(size_t size) {
GetDecoderTables()->DynamicTableSizeUpdate(size);
}
void SetStringBuffer(absl::string_view s, StringBacking backing,
HpackDecoderStringBuffer* string_buffer) {
string_buffer->OnStart(false, s.size());
EXPECT_TRUE(string_buffer->OnData(s.data(), s.size()));
EXPECT_TRUE(string_buffer->OnEnd());
if (backing == BUFFERED) {
string_buffer->BufferStringIfUnbuffered();
}
}
void SetName(absl::string_view s, StringBacking backing) {
SetStringBuffer(s, backing, &name_buffer_);
}
void SetValue(absl::string_view s, StringBacking backing) {
SetStringBuffer(s, backing, &value_buffer_);
}
void SendStartAndVerifyCallback() {
EXPECT_CALL(listener_, OnHeaderListStart());
decoder_state_.OnHeaderBlockStart();
Mock::VerifyAndClearExpectations(&listener_);
}
void SendSizeUpdate(size_t size) {
decoder_state_.OnDynamicTableSizeUpdate(size);
Mock::VerifyAndClearExpectations(&listener_);
}
void SendIndexAndVerifyCallback(size_t index,
HpackEntryType ,
absl::string_view expected_name,
absl::string_view expected_value) {
EXPECT_CALL(listener_, OnHeader(Eq(expected_name), Eq(expected_value)));
decoder_state_.OnIndexedHeader(index);
Mock::VerifyAndClearExpectations(&listener_);
}
void SendValueAndVerifyCallback(size_t name_index, HpackEntryType entry_type,
absl::string_view name,
absl::string_view value,
StringBacking value_backing) {
SetValue(value, value_backing);
EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value)));
decoder_state_.OnNameIndexAndLiteralValue(entry_type, name_index,
&value_buffer_);
Mock::VerifyAndClearExpectations(&listener_);
}
void SendNameAndValueAndVerifyCallback(HpackEntryType entry_type,
absl::string_view name,
StringBacking name_backing,
absl::string_view value,
StringBacking value_backing) {
SetName(name, name_backing);
SetValue(value, value_backing);
EXPECT_CALL(listener_, OnHeader(Eq(name), Eq(value)));
decoder_state_.OnLiteralNameAndValue(entry_type, &name_buffer_,
&value_buffer_);
Mock::VerifyAndClearExpectations(&listener_);
}
void SendEndAndVerifyCallback() {
EXPECT_CALL(listener_, OnHeaderListEnd());
decoder_state_.OnHeaderBlockEnd();
Mock::VerifyAndClearExpectations(&listener_);
}
AssertionResult VerifyEntry(size_t dynamic_index, absl::string_view name,
absl::string_view value) {
const HpackStringPair* entry =
Lookup(dynamic_index + kFirstDynamicTableIndex - 1);
HTTP2_VERIFY_NE(entry, nullptr);
HTTP2_VERIFY_EQ(entry->name, name);
HTTP2_VERIFY_EQ(entry->value, value);
return AssertionSuccess();
}
AssertionResult VerifyNoEntry(size_t dynamic_index) {
const HpackStringPair* entry =
Lookup(dynamic_index + kFirstDynamicTableIndex - 1);
HTTP2_VERIFY_EQ(entry, nullptr);
return AssertionSuccess();
}
AssertionResult VerifyDynamicTableContents(
const std::vector<std::pair<absl::string_view, absl::string_view>>&
entries) {
size_t index = 1;
for (const auto& entry : entries) {
HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second));
++index;
}
HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index));
return AssertionSuccess();
}
StrictMock<MockHpackDecoderListener> listener_;
HpackDecoderState decoder_state_;
HpackDecoderStringBuffer name_buffer_, value_buffer_;
};
TEST_F(HpackDecoderStateTest, C3_RequestExamples) {
SendStartAndVerifyCallback();
SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method",
"GET");
SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, ":scheme",
"http");
SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, ":path", "/");
SendValueAndVerifyCallback(1, HpackEntryType::kIndexedLiteralHeader,
":authority", "www.example.com", UNBUFFERED);
SendEndAndVerifyCallback();
ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}}));
ASSERT_EQ(57u, current_header_table_size());
SendStartAndVerifyCallback();
SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method",
"GET");
SendIndexAndVerifyCallback(6, HpackEntryType::kIndexedHeader, ":scheme",
"http");
SendIndexAndVerifyCallback(4, HpackEntryType::kIndexedHeader, ":path", "/");
SendIndexAndVerifyCallback(62, HpackEntryType::kIndexedHeader, ":authority",
"www.example.com");
SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader,
"cache-control", "no-cache", UNBUFFERED);
SendEndAndVerifyCallback();
ASSERT_TRUE(VerifyDynamicTableContents(
{{"cache-control", "no-cache"}, {":authority", "www.example.com"}}));
ASSERT_EQ(110u, current_header_table_size());
SendStartAndVerifyCallback();
SendIndexAndVerifyCallback(2, HpackEntryType::kIndexedHeader, ":method",
"GET");
SendIndexAndVerifyCallback(7, HpackEntryType::kIndexedHeader, ":scheme",
"https");
SendIndexAndVerifyCallback(5, HpackEntryType::kIndexedHeader, ":path",
"/index.html");
SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, ":authority",
"www.example.com");
SendNameAndValueAndVerifyCallback(HpackEntryType::kIndexedLiteralHeader,
"custom-key", UNBUFFERED, "custom-value",
UNBUFFERED);
SendEndAndVerifyCallback();
ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"},
{"cache-control", "no-cache"},
{":authority", "www.example.com"}}));
ASSERT_EQ(164u, current_header_table_size());
}
TEST_F(HpackDecoderStateTest, C5_ResponseExamples) {
set_header_table_size_limit(256);
SendStartAndVerifyCallback();
SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader,
":status", "302", BUFFERED);
SendValueAndVerifyCallback(24, HpackEntryType::kIndexedLiteralHeader,
"cache-control", "private", UNBUFFERED);
SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, "date",
"Mon, 21 Oct 2013 20:13:21 GMT", UNBUFFERED);
SendValueAndVerifyCallback(46, HpackEntryType::kIndexedLiteralHeader,
"location", "https:
SendEndAndVerifyCallback();
ASSERT_TRUE(
VerifyDynamicTableContents({{"location", "https:
{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
{"cache-control", "private"},
{":status", "302"}}));
ASSERT_EQ(222u, current_header_table_size());
SendStartAndVerifyCallback();
SendValueAndVerifyCallback(8, HpackEntryType::kIndexedLiteralHeader,
":status", "307", BUFFERED);
SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader,
"cache-control", "private");
SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, "date",
"Mon, 21 Oct 2013 20:13:21 GMT");
SendIndexAndVerifyCallback(63, HpackEntryType::kIndexedHeader, "location",
"https:
SendEndAndVerifyCallback();
ASSERT_TRUE(
VerifyDynamicTableContents({{":status", "307"},
{"location", "https:
{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
{"cache-control", "private"}}));
ASSERT_EQ(222u, current_header_table_size());
SendStartAndVerifyCallback();
SendIndexAndVerifyCallback(8, HpackEntryType::kIndexedHeader, ":status",
"200");
SendIndexAndVerifyCallback(65, HpackEntryType::kIndexedHeader,
"cache-control", "private");
SendValueAndVerifyCallback(33, HpackEntryType::kIndexedLiteralHeader, "date",
"Mon, 21 Oct 2013 20:13:22 GMT", BUFFERED);
SendIndexAndVerifyCallback(64, HpackEntryType::kIndexedHeader, "location",
"https:
SendValueAndVerifyCallback(26, HpackEntryType::kIndexedLiteralHeader,
"content-encoding", "gzip", UNBUFFERED);
SendValueAndVerifyCallback(
55, HpackEntryType::kIndexedLiteralHeader, "set-cookie",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", BUFFERED);
SendEndAndVerifyCallback();
ASSERT_TRUE(VerifyDynamicTableContents(
{{"set-cookie",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"},
{"content-encoding", "gzip"},
{"date", "Mon, 21 Oct 2013 20:13:22 GMT"}}));
ASSERT_EQ(215u, current_header_table_size());
}
TEST_F(HpackDecoderStateTest, OptionalTableSizeChanges) {
SendStartAndVerifyCallback();
EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),
header_table_size_limit());
SendSizeUpdate(1024);
EXPECT_EQ(1024u, header_table_size_limit());
SendSizeUpdate(0);
EXPECT_EQ(0u, header_table_size_limit());
EXPECT_CALL(listener_, OnHeaderErrorDetected(
Eq("Dynamic table size update not allowed")));
SendSizeUpdate(0);
}
TEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeHeader) {
EXPECT_EQ(4096u, decoder_state_.GetCurrentHeaderTableSizeSetting());
decoder_state_.ApplyHeaderTableSizeSetting(1024);
decoder_state_.ApplyHeaderTableSizeSetting(2048);
EXPECT_EQ(2048u, decoder_state_.GetCurrentHeaderTableSizeSetting());
SendStartAndVerifyCallback();
EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),
header_table_size_limit());
SendSizeUpdate(1024);
EXPECT_EQ(1024u, header_table_size_limit());
SendSizeUpdate(1500);
EXPECT_EQ(1500u, header_table_size_limit());
SendEndAndVerifyCallback();
decoder_state_.ApplyHeaderTableSizeSetting(1024);
EXPECT_EQ(1024u, decoder_state_.GetCurrentHeaderTableSizeSetting());
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(Eq("Missing dynamic table size update")));
decoder_state_.OnIndexedHeader(1);
decoder_state_.OnIndexedHeader(1);
decoder_state_.OnDynamicTableSizeUpdate(1);
SetValue("value", UNBUFFERED);
decoder_state_.OnNameIndexAndLiteralValue(
HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_);
SetName("name", UNBUFFERED);
decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,
&name_buffer_, &value_buffer_);
decoder_state_.OnHeaderBlockEnd();
decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError);
}
TEST_F(HpackDecoderStateTest, InvalidRequiredSizeUpdate) {
decoder_state_.ApplyHeaderTableSizeSetting(1024);
SendStartAndVerifyCallback();
EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),
header_table_size_limit());
EXPECT_CALL(
listener_,
OnHeaderErrorDetected(
Eq("Initial dynamic table size update is above low water mark")));
SendSizeUpdate(2048);
}
TEST_F(HpackDecoderStateTest, RequiredTableSizeChangeBeforeEnd) {
decoder_state_.ApplyHeaderTableSizeSetting(1024);
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(Eq("Missing dynamic table size update")));
decoder_state_.OnHeaderBlockEnd();
}
TEST_F(HpackDecoderStateTest, InvalidOptionalSizeUpdate) {
SendStartAndVerifyCallback();
EXPECT_EQ(Http2SettingsInfo::DefaultHeaderTableSize(),
header_table_size_limit());
EXPECT_CALL(listener_,
OnHeaderErrorDetected(Eq(
"Dynamic table size update is above acknowledged setting")));
SendSizeUpdate(Http2SettingsInfo::DefaultHeaderTableSize() + 1);
}
TEST_F(HpackDecoderStateTest, InvalidStaticIndex) {
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(
Eq("Invalid index in indexed header field representation")));
decoder_state_.OnIndexedHeader(0);
}
TEST_F(HpackDecoderStateTest, InvalidDynamicIndex) {
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(
Eq("Invalid index in indexed header field representation")));
decoder_state_.OnIndexedHeader(kFirstDynamicTableIndex);
}
TEST_F(HpackDecoderStateTest, InvalidNameIndex) {
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(Eq("Invalid index in literal header field "
"with indexed name representation")));
SetValue("value", UNBUFFERED);
decoder_state_.OnNameIndexAndLiteralValue(
HpackEntryType::kIndexedLiteralHeader, kFirstDynamicTableIndex,
&value_buffer_);
}
TEST_F(HpackDecoderStateTest, ErrorsSuppressCallbacks) {
SendStartAndVerifyCallback();
EXPECT_CALL(listener_,
OnHeaderErrorDetected(Eq("Name Huffman encoding error")));
decoder_state_.OnHpackDecodeError(HpackDecodingError::kNameHuffmanError);
decoder_state_.OnIndexedHeader(1);
decoder_state_.OnDynamicTableSizeUpdate(1);
SetValue("value", UNBUFFERED);
decoder_state_.OnNameIndexAndLiteralValue(
HpackEntryType::kIndexedLiteralHeader, 4, &value_buffer_);
SetName("name", UNBUFFERED);
decoder_state_.OnLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,
&name_buffer_, &value_buffer_);
decoder_state_.OnHeaderBlockEnd();
decoder_state_.OnHpackDecodeError(HpackDecodingError::kIndexVarintError);
}
}
}
} |
436 | cpp | google/quiche | hpack_block_decoder | quiche/http2/hpack/decoder/hpack_block_decoder.cc | quiche/http2/hpack/decoder/hpack_block_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_BLOCK_DECODER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_BLOCK_DECODER_H_
#include <string>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/hpack/decoder/hpack_decoding_error.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
class QUICHE_EXPORT HpackBlockDecoder {
public:
explicit HpackBlockDecoder(HpackEntryDecoderListener* listener)
: listener_(listener) {
QUICHE_DCHECK_NE(listener_, nullptr);
}
~HpackBlockDecoder() {}
HpackBlockDecoder(const HpackBlockDecoder&) = delete;
HpackBlockDecoder& operator=(const HpackBlockDecoder&) = delete;
void Reset() {
QUICHE_DVLOG(2) << "HpackBlockDecoder::Reset";
before_entry_ = true;
}
DecodeStatus Decode(DecodeBuffer* db);
bool before_entry() const { return before_entry_; }
HpackDecodingError error() const { return entry_decoder_.error(); }
std::string DebugString() const;
private:
HpackEntryDecoder entry_decoder_;
HpackEntryDecoderListener* const listener_;
bool before_entry_ = true;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackBlockDecoder& v);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_block_decoder.h"
#include <cstdint>
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
DecodeStatus HpackBlockDecoder::Decode(DecodeBuffer* db) {
if (!before_entry_) {
QUICHE_DVLOG(2) << "HpackBlockDecoder::Decode resume entry, db->Remaining="
<< db->Remaining();
DecodeStatus status = entry_decoder_.Resume(db, listener_);
switch (status) {
case DecodeStatus::kDecodeDone:
before_entry_ = true;
break;
case DecodeStatus::kDecodeInProgress:
QUICHE_DCHECK_EQ(0u, db->Remaining());
return DecodeStatus::kDecodeInProgress;
case DecodeStatus::kDecodeError:
QUICHE_CODE_COUNT_N(decompress_failure_3, 1, 23);
return DecodeStatus::kDecodeError;
}
}
QUICHE_DCHECK(before_entry_);
while (db->HasData()) {
QUICHE_DVLOG(2) << "HpackBlockDecoder::Decode start entry, db->Remaining="
<< db->Remaining();
DecodeStatus status = entry_decoder_.Start(db, listener_);
switch (status) {
case DecodeStatus::kDecodeDone:
continue;
case DecodeStatus::kDecodeInProgress:
QUICHE_DCHECK_EQ(0u, db->Remaining());
before_entry_ = false;
return DecodeStatus::kDecodeInProgress;
case DecodeStatus::kDecodeError:
QUICHE_CODE_COUNT_N(decompress_failure_3, 2, 23);
return DecodeStatus::kDecodeError;
}
QUICHE_DCHECK(false);
}
QUICHE_DCHECK(before_entry_);
return DecodeStatus::kDecodeDone;
}
std::string HpackBlockDecoder::DebugString() const {
return absl::StrCat(
"HpackBlockDecoder(", entry_decoder_.DebugString(), ", listener@",
absl::Hex(reinterpret_cast<intptr_t>(listener_)),
(before_entry_ ? ", between entries)" : ", in an entry)"));
}
std::ostream& operator<<(std::ostream& out, const HpackBlockDecoder& v) {
return out << v.DebugString();
}
} | #include "quiche/http2/hpack/decoder/hpack_block_decoder.h"
#include <cstdint>
#include <sstream>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_block_collector.h"
#include "quiche/http2/test_tools/hpack_example.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
class HpackBlockDecoderTest : public RandomDecoderTest {
protected:
HpackBlockDecoderTest() : listener_(&collector_), decoder_(&listener_) {
stop_decode_on_done_ = false;
decoder_.Reset();
std::ostringstream strm;
strm << decoder_;
}
DecodeStatus StartDecoding(DecodeBuffer* db) override {
collector_.Clear();
decoder_.Reset();
return ResumeDecoding(db);
}
DecodeStatus ResumeDecoding(DecodeBuffer* db) override {
DecodeStatus status = decoder_.Decode(db);
std::ostringstream strm;
strm << decoder_;
return status;
}
AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db,
const Validator& validator) {
bool return_non_zero_on_first = false;
return RandomDecoderTest::DecodeAndValidateSeveralWays(
db, return_non_zero_on_first, validator);
}
AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb,
const Validator& validator) {
DecodeBuffer db(hbb.buffer());
return DecodeAndValidateSeveralWays(&db, validator);
}
AssertionResult DecodeHpackExampleAndValidateSeveralWays(
absl::string_view hpack_example, Validator validator) {
std::string input = HpackExampleToStringOrDie(hpack_example);
DecodeBuffer db(input);
return DecodeAndValidateSeveralWays(&db, validator);
}
uint8_t Rand8() { return Random().Rand8(); }
std::string Rand8String() { return Random().RandString(Rand8()); }
HpackBlockCollector collector_;
HpackEntryDecoderVLoggingListener listener_;
HpackBlockDecoder decoder_;
};
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_1) {
auto do_check = [this]() {
return collector_.ValidateSoleLiteralNameValueHeader(
HpackEntryType::kIndexedLiteralHeader, false, "custom-key", false,
"custom-header");
};
const char hpack_example[] = R"(
40 | == Literal indexed ==
0a | Literal name (len = 10)
6375 7374 6f6d 2d6b 6579 | custom-key
0d | Literal value (len = 13)
6375 7374 6f6d 2d68 6561 6465 72 | custom-header
| -> custom-key:
| custom-header
)";
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
hpack_example, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_2) {
auto do_check = [this]() {
return collector_.ValidateSoleLiteralValueHeader(
HpackEntryType::kUnindexedLiteralHeader, 4, false, "/sample/path");
};
const char hpack_example[] = R"(
04 | == Literal not indexed ==
| Indexed name (idx = 4)
| :path
0c | Literal value (len = 12)
2f73 616d 706c 652f 7061 7468 | /sample/path
| -> :path: /sample/path
)";
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
hpack_example, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_3) {
auto do_check = [this]() {
return collector_.ValidateSoleLiteralNameValueHeader(
HpackEntryType::kNeverIndexedLiteralHeader, false, "password", false,
"secret");
};
const char hpack_example[] = R"(
10 | == Literal never indexed ==
08 | Literal name (len = 8)
7061 7373 776f 7264 | password
06 | Literal value (len = 6)
7365 6372 6574 | secret
| -> password: secret
)";
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
hpack_example, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackBlockDecoderTest, SpecExample_C_2_4) {
auto do_check = [this]() { return collector_.ValidateSoleIndexedHeader(2); };
const char hpack_example[] = R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
)";
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
hpack_example, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackBlockDecoderTest, SpecExample_C_3_1) {
std::string example = R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
86 | == Indexed - Add ==
| idx = 6
| -> :scheme: http
84 | == Indexed - Add ==
| idx = 4
| -> :path: /
41 | == Literal indexed ==
| Indexed name (idx = 1)
| :authority
0f | Literal value (len = 15)
7777 772e 6578 616d 706c 652e 636f 6d | www.example.com
| -> :authority:
| www.example.com
)";
HpackBlockCollector expected;
expected.ExpectIndexedHeader(2);
expected.ExpectIndexedHeader(6);
expected.ExpectIndexedHeader(4);
expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
1, false, "www.example.com");
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
example,
ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));
EXPECT_TRUE(collector_.VerifyEq(expected));
}
TEST_F(HpackBlockDecoderTest, SpecExample_C_5_1) {
std::string example = R"(
48 | == Literal indexed ==
| Indexed name (idx = 8)
| :status
03 | Literal value (len = 3)
3330 32 | 302
| -> :status: 302
58 | == Literal indexed ==
| Indexed name (idx = 24)
| cache-control
07 | Literal value (len = 7)
7072 6976 6174 65 | private
| -> cache-control: private
61 | == Literal indexed ==
| Indexed name (idx = 33)
| date
1d | Literal value (len = 29)
4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013
2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT
| -> date: Mon, 21 Oct 2013
| 20:13:21 GMT
6e | == Literal indexed ==
| Indexed name (idx = 46)
| location
17 | Literal value (len = 23)
6874 7470 733a 2f2f 7777 772e 6578 616d | https:
706c 652e 636f 6d | ple.com
| -> location:
| https:
)";
HpackBlockCollector expected;
expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
8, false, "302");
expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
24, false, "private");
expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
33, false,
"Mon, 21 Oct 2013 20:13:21 GMT");
expected.ExpectNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader,
46, false, "https:
EXPECT_TRUE(DecodeHpackExampleAndValidateSeveralWays(
example,
ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));
EXPECT_TRUE(collector_.VerifyEq(expected));
}
TEST_F(HpackBlockDecoderTest, Computed) {
HpackBlockCollector expected;
expected.ExpectIndexedHeader(0);
expected.ExpectIndexedHeader(1);
expected.ExpectIndexedHeader(126);
expected.ExpectIndexedHeader(127);
expected.ExpectIndexedHeader(128);
expected.ExpectDynamicTableSizeUpdate(0);
expected.ExpectDynamicTableSizeUpdate(1);
expected.ExpectDynamicTableSizeUpdate(14);
expected.ExpectDynamicTableSizeUpdate(15);
expected.ExpectDynamicTableSizeUpdate(30);
expected.ExpectDynamicTableSizeUpdate(31);
expected.ExpectDynamicTableSizeUpdate(4095);
expected.ExpectDynamicTableSizeUpdate(4096);
expected.ExpectDynamicTableSizeUpdate(8192);
for (auto type : {HpackEntryType::kIndexedLiteralHeader,
HpackEntryType::kUnindexedLiteralHeader,
HpackEntryType::kNeverIndexedLiteralHeader}) {
for (bool value_huffman : {false, true}) {
expected.ExpectNameIndexAndLiteralValue(type, Rand8() + 1, value_huffman,
Rand8String());
expected.ExpectLiteralNameAndValue(type, false, Rand8String(),
value_huffman, Rand8String());
expected.ExpectLiteralNameAndValue(type, true, Rand8String(),
value_huffman, Rand8String());
}
}
expected.ShuffleEntries(RandomPtr());
HpackBlockBuilder hbb;
expected.AppendToHpackBlockBuilder(&hbb);
EXPECT_TRUE(DecodeAndValidateSeveralWays(
hbb,
ValidateDoneAndEmpty([&] { return collector_.VerifyEq(expected); })));
EXPECT_TRUE(collector_.VerifyEq(expected));
}
}
}
} |
437 | cpp | google/quiche | hpack_decoder | quiche/http2/hpack/decoder/hpack_decoder.cc | quiche/http2/hpack/decoder/hpack_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_H_
#include <stddef.h>
#include <cstdint>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/hpack/decoder/hpack_block_decoder.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_listener.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_state.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h"
#include "quiche/http2/hpack/decoder/hpack_decoding_error.h"
#include "quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class HpackDecoderPeer;
}
class QUICHE_EXPORT HpackDecoder {
public:
HpackDecoder(HpackDecoderListener* listener, size_t max_string_size);
virtual ~HpackDecoder();
HpackDecoder(const HpackDecoder&) = delete;
HpackDecoder& operator=(const HpackDecoder&) = delete;
void set_max_string_size_bytes(size_t max_string_size_bytes);
void ApplyHeaderTableSizeSetting(uint32_t max_header_table_size);
size_t GetCurrentHeaderTableSizeSetting() const {
return decoder_state_.GetCurrentHeaderTableSizeSetting();
}
bool StartDecodingBlock();
bool DecodeFragment(DecodeBuffer* db);
bool EndDecodingBlock();
bool DetectError();
size_t GetDynamicTableSize() const {
return decoder_state_.GetDynamicTableSize();
}
HpackDecodingError error() const { return error_; }
private:
friend class test::HpackDecoderPeer;
void ReportError(HpackDecodingError error);
HpackDecoderState decoder_state_;
HpackWholeEntryBuffer entry_buffer_;
HpackBlockDecoder block_decoder_;
HpackDecodingError error_;
};
}
#endif
#include "quiche/http2/hpack/decoder/hpack_decoder.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
HpackDecoder::HpackDecoder(HpackDecoderListener* listener,
size_t max_string_size)
: decoder_state_(listener),
entry_buffer_(&decoder_state_, max_string_size),
block_decoder_(&entry_buffer_),
error_(HpackDecodingError::kOk) {}
HpackDecoder::~HpackDecoder() = default;
void HpackDecoder::set_max_string_size_bytes(size_t max_string_size_bytes) {
entry_buffer_.set_max_string_size_bytes(max_string_size_bytes);
}
void HpackDecoder::ApplyHeaderTableSizeSetting(uint32_t max_header_table_size) {
decoder_state_.ApplyHeaderTableSizeSetting(max_header_table_size);
}
bool HpackDecoder::StartDecodingBlock() {
QUICHE_DVLOG(3) << "HpackDecoder::StartDecodingBlock, error_detected="
<< (DetectError() ? "true" : "false");
if (DetectError()) {
return false;
}
block_decoder_.Reset();
decoder_state_.OnHeaderBlockStart();
return true;
}
bool HpackDecoder::DecodeFragment(DecodeBuffer* db) {
QUICHE_DVLOG(3) << "HpackDecoder::DecodeFragment, error_detected="
<< (DetectError() ? "true" : "false")
<< ", size=" << db->Remaining();
if (DetectError()) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 3, 23);
return false;
}
DecodeStatus status = block_decoder_.Decode(db);
if (status == DecodeStatus::kDecodeError) {
ReportError(block_decoder_.error());
QUICHE_CODE_COUNT_N(decompress_failure_3, 4, 23);
return false;
} else if (DetectError()) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 5, 23);
return false;
}
QUICHE_DCHECK_EQ(block_decoder_.before_entry(),
status == DecodeStatus::kDecodeDone)
<< status;
if (!block_decoder_.before_entry()) {
entry_buffer_.BufferStringsIfUnbuffered();
}
return true;
}
bool HpackDecoder::EndDecodingBlock() {
QUICHE_DVLOG(3) << "HpackDecoder::EndDecodingBlock, error_detected="
<< (DetectError() ? "true" : "false");
if (DetectError()) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 6, 23);
return false;
}
if (!block_decoder_.before_entry()) {
ReportError(HpackDecodingError::kTruncatedBlock);
QUICHE_CODE_COUNT_N(decompress_failure_3, 7, 23);
return false;
}
decoder_state_.OnHeaderBlockEnd();
if (DetectError()) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 8, 23);
return false;
}
return true;
}
bool HpackDecoder::DetectError() {
if (error_ != HpackDecodingError::kOk) {
return true;
}
if (decoder_state_.error() != HpackDecodingError::kOk) {
QUICHE_DVLOG(2) << "Error detected in decoder_state_";
QUICHE_CODE_COUNT_N(decompress_failure_3, 10, 23);
error_ = decoder_state_.error();
}
return error_ != HpackDecodingError::kOk;
}
void HpackDecoder::ReportError(HpackDecodingError error) {
QUICHE_DVLOG(3) << "HpackDecoder::ReportError is new="
<< (error_ == HpackDecodingError::kOk ? "true" : "false")
<< ", error: " << HpackDecodingErrorToString(error);
if (error_ == HpackDecodingError::kOk) {
error_ = error;
decoder_state_.listener()->OnHeaderErrorDetected(
HpackDecodingErrorToString(error));
}
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder.h"
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_listener.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_state.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_example.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_util.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
using ::testing::ElementsAreArray;
using ::testing::Eq;
namespace http2 {
namespace test {
class HpackDecoderStatePeer {
public:
static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) {
return &state->decoder_tables_;
}
static void set_listener(HpackDecoderState* state,
HpackDecoderListener* listener) {
state->listener_ = listener;
}
};
class HpackDecoderPeer {
public:
static HpackDecoderState* GetDecoderState(HpackDecoder* decoder) {
return &decoder->decoder_state_;
}
static HpackDecoderTables* GetDecoderTables(HpackDecoder* decoder) {
return HpackDecoderStatePeer::GetDecoderTables(GetDecoderState(decoder));
}
};
namespace {
typedef std::pair<std::string, std::string> HpackHeaderEntry;
typedef std::vector<HpackHeaderEntry> HpackHeaderEntries;
class MockHpackDecoderListener : public HpackDecoderListener {
public:
MOCK_METHOD(void, OnHeaderListStart, (), (override));
MOCK_METHOD(void, OnHeader, (absl::string_view name, absl::string_view value),
(override));
MOCK_METHOD(void, OnHeaderListEnd, (), (override));
MOCK_METHOD(void, OnHeaderErrorDetected, (absl::string_view error_message),
(override));
};
class HpackDecoderTest : public quiche::test::QuicheTestWithParam<bool>,
public HpackDecoderListener {
protected:
HpackDecoderTest() : decoder_(this, 4096) {
fragment_the_hpack_block_ = GetParam();
}
~HpackDecoderTest() override = default;
void OnHeaderListStart() override {
ASSERT_FALSE(saw_start_);
ASSERT_FALSE(saw_end_);
saw_start_ = true;
header_entries_.clear();
}
void OnHeader(absl::string_view name, absl::string_view value) override {
ASSERT_TRUE(saw_start_);
ASSERT_FALSE(saw_end_);
header_entries_.emplace_back(name, value);
}
void OnHeaderListEnd() override {
ASSERT_TRUE(saw_start_);
ASSERT_FALSE(saw_end_);
ASSERT_TRUE(error_messages_.empty());
saw_end_ = true;
}
void OnHeaderErrorDetected(absl::string_view error_message) override {
ASSERT_TRUE(saw_start_);
error_messages_.push_back(std::string(error_message));
HpackDecoderStatePeer::set_listener(
HpackDecoderPeer::GetDecoderState(&decoder_), &mock_listener_);
}
AssertionResult DecodeBlock(absl::string_view block) {
QUICHE_VLOG(1) << "HpackDecoderTest::DecodeBlock";
HTTP2_VERIFY_FALSE(decoder_.DetectError());
HTTP2_VERIFY_TRUE(error_messages_.empty());
HTTP2_VERIFY_FALSE(saw_start_);
HTTP2_VERIFY_FALSE(saw_end_);
header_entries_.clear();
HTTP2_VERIFY_FALSE(decoder_.DetectError());
HTTP2_VERIFY_TRUE(decoder_.StartDecodingBlock());
HTTP2_VERIFY_FALSE(decoder_.DetectError());
if (fragment_the_hpack_block_) {
while (!block.empty()) {
size_t fragment_size = random_.RandomSizeSkewedLow(block.size());
DecodeBuffer db(block.substr(0, fragment_size));
HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db));
HTTP2_VERIFY_EQ(0u, db.Remaining());
block.remove_prefix(fragment_size);
}
} else {
DecodeBuffer db(block);
HTTP2_VERIFY_TRUE(decoder_.DecodeFragment(&db));
HTTP2_VERIFY_EQ(0u, db.Remaining());
}
HTTP2_VERIFY_FALSE(decoder_.DetectError());
HTTP2_VERIFY_TRUE(decoder_.EndDecodingBlock());
if (saw_end_) {
HTTP2_VERIFY_FALSE(decoder_.DetectError());
HTTP2_VERIFY_TRUE(error_messages_.empty());
} else {
HTTP2_VERIFY_TRUE(decoder_.DetectError());
HTTP2_VERIFY_FALSE(error_messages_.empty());
}
saw_start_ = saw_end_ = false;
return AssertionSuccess();
}
const HpackDecoderTables& GetDecoderTables() {
return *HpackDecoderPeer::GetDecoderTables(&decoder_);
}
const HpackStringPair* Lookup(size_t index) {
return GetDecoderTables().Lookup(index);
}
size_t current_header_table_size() {
return GetDecoderTables().current_header_table_size();
}
size_t header_table_size_limit() {
return GetDecoderTables().header_table_size_limit();
}
void set_header_table_size_limit(size_t size) {
HpackDecoderPeer::GetDecoderTables(&decoder_)->DynamicTableSizeUpdate(size);
}
AssertionResult VerifyEntry(size_t dynamic_index, const char* name,
const char* value) {
const HpackStringPair* entry =
Lookup(dynamic_index + kFirstDynamicTableIndex - 1);
HTTP2_VERIFY_NE(entry, nullptr);
HTTP2_VERIFY_EQ(entry->name, name);
HTTP2_VERIFY_EQ(entry->value, value);
return AssertionSuccess();
}
AssertionResult VerifyNoEntry(size_t dynamic_index) {
const HpackStringPair* entry =
Lookup(dynamic_index + kFirstDynamicTableIndex - 1);
HTTP2_VERIFY_EQ(entry, nullptr);
return AssertionSuccess();
}
AssertionResult VerifyDynamicTableContents(
const std::vector<std::pair<const char*, const char*>>& entries) {
size_t index = 1;
for (const auto& entry : entries) {
HTTP2_VERIFY_SUCCESS(VerifyEntry(index, entry.first, entry.second));
++index;
}
HTTP2_VERIFY_SUCCESS(VerifyNoEntry(index));
return AssertionSuccess();
}
Http2Random random_;
HpackDecoder decoder_;
testing::StrictMock<MockHpackDecoderListener> mock_listener_;
HpackHeaderEntries header_entries_;
std::vector<std::string> error_messages_;
bool fragment_the_hpack_block_;
bool saw_start_ = false;
bool saw_end_ = false;
};
INSTANTIATE_TEST_SUITE_P(AllWays, HpackDecoderTest, ::testing::Bool());
TEST_P(HpackDecoderTest, C3_RequestExamples) {
std::string hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
86 | == Indexed - Add ==
| idx = 6
| -> :scheme: http
84 | == Indexed - Add ==
| idx = 4
| -> :path: /
41 | == Literal indexed ==
| Indexed name (idx = 1)
| :authority
0f | Literal value (len = 15)
7777 772e 6578 616d 706c 652e 636f 6d | www.example.com
| -> :authority:
| www.example.com
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "http"},
HpackHeaderEntry{":path", "/"},
HpackHeaderEntry{":authority", "www.example.com"},
}));
ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}}));
ASSERT_EQ(57u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
86 | == Indexed - Add ==
| idx = 6
| -> :scheme: http
84 | == Indexed - Add ==
| idx = 4
| -> :path: /
be | == Indexed - Add ==
| idx = 62
| -> :authority:
| www.example.com
58 | == Literal indexed ==
| Indexed name (idx = 24)
| cache-control
08 | Literal value (len = 8)
6e6f 2d63 6163 6865 | no-cache
| -> cache-control: no-cache
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "http"},
HpackHeaderEntry{":path", "/"},
HpackHeaderEntry{":authority", "www.example.com"},
HpackHeaderEntry{"cache-control", "no-cache"},
}));
ASSERT_TRUE(VerifyDynamicTableContents(
{{"cache-control", "no-cache"}, {":authority", "www.example.com"}}));
ASSERT_EQ(110u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
87 | == Indexed - Add ==
| idx = 7
| -> :scheme: https
85 | == Indexed - Add ==
| idx = 5
| -> :path: /index.html
bf | == Indexed - Add ==
| idx = 63
| -> :authority:
| www.example.com
40 | == Literal indexed ==
0a | Literal name (len = 10)
6375 7374 6f6d 2d6b 6579 | custom-key
0c | Literal value (len = 12)
6375 7374 6f6d 2d76 616c 7565 | custom-value
| -> custom-key:
| custom-value
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "https"},
HpackHeaderEntry{":path", "/index.html"},
HpackHeaderEntry{":authority", "www.example.com"},
HpackHeaderEntry{"custom-key", "custom-value"},
}));
ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"},
{"cache-control", "no-cache"},
{":authority", "www.example.com"}}));
ASSERT_EQ(164u, current_header_table_size());
}
TEST_P(HpackDecoderTest, C4_RequestExamplesWithHuffmanEncoding) {
std::string hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
86 | == Indexed - Add ==
| idx = 6
| -> :scheme: http
84 | == Indexed - Add ==
| idx = 4
| -> :path: /
41 | == Literal indexed ==
| Indexed name (idx = 1)
| :authority
8c | Literal value (len = 12)
| Huffman encoded:
f1e3 c2e5 f23a 6ba0 ab90 f4ff | .....:k.....
| Decoded:
| www.example.com
| -> :authority:
| www.example.com
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "http"},
HpackHeaderEntry{":path", "/"},
HpackHeaderEntry{":authority", "www.example.com"},
}));
ASSERT_TRUE(VerifyDynamicTableContents({{":authority", "www.example.com"}}));
ASSERT_EQ(57u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
86 | == Indexed - Add ==
| idx = 6
| -> :scheme: http
84 | == Indexed - Add ==
| idx = 4
| -> :path: /
be | == Indexed - Add ==
| idx = 62
| -> :authority:
| www.example.com
58 | == Literal indexed ==
| Indexed name (idx = 24)
| cache-control
86 | Literal value (len = 6)
| Huffman encoded:
a8eb 1064 9cbf | ...d..
| Decoded:
| no-cache
| -> cache-control: no-cache
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "http"},
HpackHeaderEntry{":path", "/"},
HpackHeaderEntry{":authority", "www.example.com"},
HpackHeaderEntry{"cache-control", "no-cache"},
}));
ASSERT_TRUE(VerifyDynamicTableContents(
{{"cache-control", "no-cache"}, {":authority", "www.example.com"}}));
ASSERT_EQ(110u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
82 | == Indexed - Add ==
| idx = 2
| -> :method: GET
87 | == Indexed - Add ==
| idx = 7
| -> :scheme: https
85 | == Indexed - Add ==
| idx = 5
| -> :path: /index.html
bf | == Indexed - Add ==
| idx = 63
| -> :authority:
| www.example.com
40 | == Literal indexed ==
88 | Literal name (len = 8)
| Huffman encoded:
25a8 49e9 5ba9 7d7f | %.I.[.}.
| Decoded:
| custom-key
89 | Literal value (len = 9)
| Huffman encoded:
25a8 49e9 5bb8 e8b4 bf | %.I.[....
| Decoded:
| custom-value
| -> custom-key:
| custom-value
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":method", "GET"},
HpackHeaderEntry{":scheme", "https"},
HpackHeaderEntry{":path", "/index.html"},
HpackHeaderEntry{":authority", "www.example.com"},
HpackHeaderEntry{"custom-key", "custom-value"},
}));
ASSERT_TRUE(VerifyDynamicTableContents({{"custom-key", "custom-value"},
{"cache-control", "no-cache"},
{":authority", "www.example.com"}}));
ASSERT_EQ(164u, current_header_table_size());
}
TEST_P(HpackDecoderTest, C5_ResponseExamples) {
set_header_table_size_limit(256);
std::string hpack_block = HpackExampleToStringOrDie(R"(
48 | == Literal indexed ==
| Indexed name (idx = 8)
| :status
03 | Literal value (len = 3)
3330 32 | 302
| -> :status: 302
58 | == Literal indexed ==
| Indexed name (idx = 24)
| cache-control
07 | Literal value (len = 7)
7072 6976 6174 65 | private
| -> cache-control: private
61 | == Literal indexed ==
| Indexed name (idx = 33)
| date
1d | Literal value (len = 29)
4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013
2032 303a 3133 3a32 3120 474d 54 | 20:13:21 GMT
| -> date: Mon, 21 Oct 2013
| 20:13:21 GMT
6e | == Literal indexed ==
| Indexed name (idx = 46)
| location
17 | Literal value (len = 23)
6874 7470 733a 2f2f 7777 772e 6578 616d | https:
706c 652e 636f 6d | ple.com
| -> location:
| https:
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":status", "302"},
HpackHeaderEntry{"cache-control", "private"},
HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
HpackHeaderEntry{"location", "https:
}));
ASSERT_TRUE(
VerifyDynamicTableContents({{"location", "https:
{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
{"cache-control", "private"},
{":status", "302"}}));
ASSERT_EQ(222u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
48 | == Literal indexed ==
| Indexed name (idx = 8)
| :status
03 | Literal value (len = 3)
3330 37 | 307
| - evict: :status: 302
| -> :status: 307
c1 | == Indexed - Add ==
| idx = 65
| -> cache-control: private
c0 | == Indexed - Add ==
| idx = 64
| -> date: Mon, 21 Oct 2013
| 20:13:21 GMT
bf | == Indexed - Add ==
| idx = 63
| -> location:
| https:
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(header_entries_,
ElementsAreArray({
HpackHeaderEntry{":status", "307"},
HpackHeaderEntry{"cache-control", "private"},
HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
HpackHeaderEntry{"location", "https:
}));
ASSERT_TRUE(
VerifyDynamicTableContents({{":status", "307"},
{"location", "https:
{"date", "Mon, 21 Oct 2013 20:13:21 GMT"},
{"cache-control", "private"}}));
ASSERT_EQ(222u, current_header_table_size());
hpack_block = HpackExampleToStringOrDie(R"(
88 | == Indexed - Add ==
| idx = 8
| -> :status: 200
c1 | == Indexed - Add ==
| idx = 65
| -> cache-control: private
61 | == Literal indexed ==
| Indexed name (idx = 33)
| date
1d | Literal value (len = 29)
4d6f 6e2c 2032 3120 4f63 7420 3230 3133 | Mon, 21 Oct 2013
2032 303a 3133 3a32 3220 474d 54 | 20:13:22 GMT
| - evict: cache-control:
| private
| -> date: Mon, 21 Oct 2013
| 20:13:22 GMT
c0 | == Indexed - Add ==
| idx = 64
| -> location:
| https:
5a | == Literal indexed ==
| Indexed name (idx = 26)
| content-encoding
04 | Literal value (len = 4)
677a 6970 | gzip
| - evict: date: Mon, 21 Oct
| 2013 20:13:21 GMT
| -> content-encoding: gzip
77 | == Literal indexed ==
| Indexed name (idx = 55)
| set-cookie
38 | Literal value (len = 56)
666f 6f3d 4153 444a 4b48 514b 425a 584f | foo=ASDJKHQKBZXO
5157 454f 5049 5541 5851 5745 4f49 553b | QWEOPIUAXQWEOIU;
206d 6178 2d61 6765 3d33 3630 303b 2076 | max-age=3600; v
6572 7369 6f6e 3d31 | ersion=1
| - evict: location:
| https:
| - evict: :status: 307
| -> set-cookie: foo=ASDJKHQ
| KBZXOQWEOPIUAXQWEOIU; ma
| x-age=3600; version=1
)");
EXPECT_TRUE(DecodeBlock(hpack_block));
ASSERT_THAT(
header_entries_,
ElementsAreArray({
HpackHeaderEntry{":status", "200"},
HpackHeaderEntry{"cache-control", "private"},
HpackHeaderEntry{"date", "Mon, 21 Oct 2013 20:13:22 GMT"},
HpackHeaderEntry{"location", "https:
HpackHeaderEntry{"content-encoding", "gzip"},
HpackHeaderEntry{
"set-cookie",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"},
}));
ASSERT_TRUE(VerifyDynamicTableContents(
{{"set-cookie",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"},
{"content-encoding", "gzip"},
{"date", "Mon, 21 Oct 2013 20:13:22 GMT"}}));
ASSERT_EQ(215u, current_header_table_size());
}
TEST_P(HpackDecoderTest, C6_ResponseExamplesWithHuffmanEncoding) {
set_header_table_size_limit(256); |
438 | cpp | google/quiche | hpack_decoder_tables | quiche/http2/hpack/decoder/hpack_decoder_tables.cc | quiche/http2/hpack/decoder/hpack_decoder_tables_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_TABLES_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_DECODER_TABLES_H_
#include <stddef.h>
#include <cstdint>
#include <iosfwd>
#include <string>
#include <utility>
#include <vector>
#include "quiche/http2/http2_constants.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_circular_deque.h"
namespace http2 {
namespace test {
class HpackDecoderTablesPeer;
}
struct QUICHE_EXPORT HpackStringPair {
HpackStringPair(std::string name, std::string value);
~HpackStringPair();
size_t size() const { return 32 + name.size() + value.size(); }
std::string DebugString() const;
const std::string name;
const std::string value;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
const HpackStringPair& p);
class QUICHE_EXPORT HpackDecoderStaticTable {
public:
explicit HpackDecoderStaticTable(const std::vector<HpackStringPair>* table);
HpackDecoderStaticTable();
const HpackStringPair* Lookup(size_t index) const;
private:
friend class test::HpackDecoderTablesPeer;
const std::vector<HpackStringPair>* const table_;
};
class QUICHE_EXPORT HpackDecoderDynamicTable {
public:
HpackDecoderDynamicTable();
~HpackDecoderDynamicTable();
HpackDecoderDynamicTable(const HpackDecoderDynamicTable&) = delete;
HpackDecoderDynamicTable& operator=(const HpackDecoderDynamicTable&) = delete;
void DynamicTableSizeUpdate(size_t size_limit);
void Insert(std::string name, std::string value);
const HpackStringPair* Lookup(size_t index) const;
size_t size_limit() const { return size_limit_; }
size_t current_size() const { return current_size_; }
private:
friend class test::HpackDecoderTablesPeer;
void EnsureSizeNoMoreThan(size_t limit);
void RemoveLastEntry();
quiche::QuicheCircularDeque<HpackStringPair> table_;
size_t size_limit_ = Http2SettingsInfo::DefaultHeaderTableSize();
size_t current_size_ = 0;
size_t insert_count_;
};
class QUICHE_EXPORT HpackDecoderTables {
public:
HpackDecoderTables();
~HpackDecoderTables();
HpackDecoderTables(const HpackDecoderTables&) = delete;
HpackDecoderTables& operator=(const HpackDecoderTables&) = delete;
void DynamicTableSizeUpdate(size_t size_limit) {
dynamic_table_.DynamicTableSizeUpdate(size_limit);
}
void Insert(std::string name, std::string value) {
dynamic_table_.Insert(std::move(name), std::move(value));
}
const HpackStringPair* Lookup(size_t index) const;
size_t header_table_size_limit() const { return dynamic_table_.size_limit(); }
size_t current_header_table_size() const {
return dynamic_table_.current_size();
}
private:
friend class test::HpackDecoderTablesPeer;
HpackDecoderStaticTable static_table_;
HpackDecoderDynamicTable dynamic_table_;
};
}
#endif
#include "quiche/http2/hpack/decoder/hpack_decoder_tables.h"
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace {
std::vector<HpackStringPair>* MakeStaticTable() {
auto* ptr = new std::vector<HpackStringPair>();
ptr->reserve(kFirstDynamicTableIndex);
ptr->emplace_back("", "");
#define STATIC_TABLE_ENTRY(name, value, index) \
QUICHE_DCHECK_EQ(ptr->size(), static_cast<size_t>(index)); \
ptr->emplace_back(name, value)
#include "quiche/http2/hpack/hpack_static_table_entries.inc"
#undef STATIC_TABLE_ENTRY
return ptr;
}
const std::vector<HpackStringPair>* GetStaticTable() {
static const std::vector<HpackStringPair>* const g_static_table =
MakeStaticTable();
return g_static_table;
}
}
HpackStringPair::HpackStringPair(std::string name, std::string value)
: name(std::move(name)), value(std::move(value)) {
QUICHE_DVLOG(3) << DebugString() << " ctor";
}
HpackStringPair::~HpackStringPair() {
QUICHE_DVLOG(3) << DebugString() << " dtor";
}
std::string HpackStringPair::DebugString() const {
return absl::StrCat("HpackStringPair(name=", name, ", value=", value, ")");
}
std::ostream& operator<<(std::ostream& os, const HpackStringPair& p) {
os << p.DebugString();
return os;
}
HpackDecoderStaticTable::HpackDecoderStaticTable(
const std::vector<HpackStringPair>* table)
: table_(table) {}
HpackDecoderStaticTable::HpackDecoderStaticTable() : table_(GetStaticTable()) {}
const HpackStringPair* HpackDecoderStaticTable::Lookup(size_t index) const {
if (0 < index && index < kFirstDynamicTableIndex) {
return &((*table_)[index]);
}
return nullptr;
}
HpackDecoderDynamicTable::HpackDecoderDynamicTable()
: insert_count_(kFirstDynamicTableIndex - 1) {}
HpackDecoderDynamicTable::~HpackDecoderDynamicTable() = default;
void HpackDecoderDynamicTable::DynamicTableSizeUpdate(size_t size_limit) {
QUICHE_DVLOG(3) << "HpackDecoderDynamicTable::DynamicTableSizeUpdate "
<< size_limit;
EnsureSizeNoMoreThan(size_limit);
QUICHE_DCHECK_LE(current_size_, size_limit);
size_limit_ = size_limit;
}
void HpackDecoderDynamicTable::Insert(std::string name, std::string value) {
HpackStringPair entry(std::move(name), std::move(value));
size_t entry_size = entry.size();
QUICHE_DVLOG(2) << "InsertEntry of size=" << entry_size
<< "\n name: " << entry.name
<< "\n value: " << entry.value;
if (entry_size > size_limit_) {
QUICHE_DVLOG(2) << "InsertEntry: entry larger than table, removing "
<< table_.size() << " entries, of total size "
<< current_size_ << " bytes.";
table_.clear();
current_size_ = 0;
return;
}
++insert_count_;
size_t insert_limit = size_limit_ - entry_size;
EnsureSizeNoMoreThan(insert_limit);
table_.push_front(std::move(entry));
current_size_ += entry_size;
QUICHE_DVLOG(2) << "InsertEntry: current_size_=" << current_size_;
QUICHE_DCHECK_GE(current_size_, entry_size);
QUICHE_DCHECK_LE(current_size_, size_limit_);
}
const HpackStringPair* HpackDecoderDynamicTable::Lookup(size_t index) const {
if (index < table_.size()) {
return &table_[index];
}
return nullptr;
}
void HpackDecoderDynamicTable::EnsureSizeNoMoreThan(size_t limit) {
QUICHE_DVLOG(2) << "EnsureSizeNoMoreThan limit=" << limit
<< ", current_size_=" << current_size_;
while (current_size_ > limit) {
RemoveLastEntry();
}
QUICHE_DCHECK_LE(current_size_, limit);
}
void HpackDecoderDynamicTable::RemoveLastEntry() {
QUICHE_DCHECK(!table_.empty());
if (!table_.empty()) {
QUICHE_DVLOG(2) << "RemoveLastEntry current_size_=" << current_size_
<< ", last entry size=" << table_.back().size();
QUICHE_DCHECK_GE(current_size_, table_.back().size());
current_size_ -= table_.back().size();
table_.pop_back();
QUICHE_DCHECK_EQ(table_.empty(), current_size_ == 0);
}
}
HpackDecoderTables::HpackDecoderTables() = default;
HpackDecoderTables::~HpackDecoderTables() = default;
const HpackStringPair* HpackDecoderTables::Lookup(size_t index) const {
if (index < kFirstDynamicTableIndex) {
return static_table_.Lookup(index);
} else {
return dynamic_table_.Lookup(index - kFirstDynamicTableIndex);
}
}
} | #include "quiche/http2/hpack/decoder/hpack_decoder_tables.h"
#include <algorithm>
#include <string>
#include <tuple>
#include <vector>
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_util.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
class HpackDecoderTablesPeer {
public:
static size_t num_dynamic_entries(const HpackDecoderTables& tables) {
return tables.dynamic_table_.table_.size();
}
};
namespace {
struct StaticEntry {
const char* name;
const char* value;
size_t index;
};
std::vector<StaticEntry> MakeSpecStaticEntries() {
std::vector<StaticEntry> static_entries;
#define STATIC_TABLE_ENTRY(name, value, index) \
QUICHE_DCHECK_EQ(static_entries.size() + 1, static_cast<size_t>(index)); \
static_entries.push_back({name, value, index});
#include "quiche/http2/hpack/hpack_static_table_entries.inc"
#undef STATIC_TABLE_ENTRY
return static_entries;
}
template <class C>
void ShuffleCollection(C* collection, Http2Random* r) {
std::shuffle(collection->begin(), collection->end(), *r);
}
class HpackDecoderStaticTableTest : public quiche::test::QuicheTest {
protected:
HpackDecoderStaticTableTest() = default;
std::vector<StaticEntry> shuffled_static_entries() {
std::vector<StaticEntry> entries = MakeSpecStaticEntries();
ShuffleCollection(&entries, &random_);
return entries;
}
AssertionResult VerifyStaticTableContents() {
for (const auto& expected : shuffled_static_entries()) {
const HpackStringPair* found = Lookup(expected.index);
HTTP2_VERIFY_NE(found, nullptr);
HTTP2_VERIFY_EQ(expected.name, found->name) << expected.index;
HTTP2_VERIFY_EQ(expected.value, found->value) << expected.index;
}
HTTP2_VERIFY_EQ(nullptr, Lookup(0));
return AssertionSuccess();
}
virtual const HpackStringPair* Lookup(size_t index) {
return static_table_.Lookup(index);
}
Http2Random* RandomPtr() { return &random_; }
Http2Random random_;
private:
HpackDecoderStaticTable static_table_;
};
TEST_F(HpackDecoderStaticTableTest, StaticTableContents) {
EXPECT_TRUE(VerifyStaticTableContents());
}
size_t Size(const std::string& name, const std::string& value) {
return name.size() + value.size() + 32;
}
typedef std::tuple<std::string, std::string, size_t> FakeHpackEntry;
const std::string& Name(const FakeHpackEntry& entry) {
return std::get<0>(entry);
}
const std::string& Value(const FakeHpackEntry& entry) {
return std::get<1>(entry);
}
size_t Size(const FakeHpackEntry& entry) { return std::get<2>(entry); }
class HpackDecoderTablesTest : public HpackDecoderStaticTableTest {
protected:
const HpackStringPair* Lookup(size_t index) override {
return tables_.Lookup(index);
}
size_t dynamic_size_limit() const {
return tables_.header_table_size_limit();
}
size_t current_dynamic_size() const {
return tables_.current_header_table_size();
}
size_t num_dynamic_entries() const {
return HpackDecoderTablesPeer::num_dynamic_entries(tables_);
}
void FakeInsert(const std::string& name, const std::string& value) {
FakeHpackEntry entry(name, value, Size(name, value));
fake_dynamic_table_.insert(fake_dynamic_table_.begin(), entry);
}
size_t FakeSize() {
size_t sz = 0;
for (const auto& entry : fake_dynamic_table_) {
sz += Size(entry);
}
return sz;
}
size_t FakeTrim(size_t limit) {
size_t original_size = FakeSize();
size_t total_size = 0;
for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) {
total_size += Size(fake_dynamic_table_[ndx]);
if (total_size > limit) {
fake_dynamic_table_.erase(fake_dynamic_table_.begin() + ndx,
fake_dynamic_table_.end());
return original_size - FakeSize();
}
}
return 0;
}
AssertionResult VerifyDynamicTableContents() {
HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());
HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size());
for (size_t ndx = 0; ndx < fake_dynamic_table_.size(); ++ndx) {
const HpackStringPair* found = Lookup(ndx + kFirstDynamicTableIndex);
HTTP2_VERIFY_NE(found, nullptr);
const auto& expected = fake_dynamic_table_[ndx];
HTTP2_VERIFY_EQ(Name(expected), found->name);
HTTP2_VERIFY_EQ(Value(expected), found->value);
}
HTTP2_VERIFY_EQ(
nullptr, Lookup(fake_dynamic_table_.size() + kFirstDynamicTableIndex));
return AssertionSuccess();
}
AssertionResult DynamicTableSizeUpdate(size_t size_limit) {
HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());
if (size_limit < current_dynamic_size()) {
tables_.DynamicTableSizeUpdate(size_limit);
FakeTrim(size_limit);
return VerifyDynamicTableContents();
}
tables_.DynamicTableSizeUpdate(size_limit);
return VerifyDynamicTableContents();
}
AssertionResult Insert(const std::string& name, const std::string& value) {
size_t old_count = num_dynamic_entries();
tables_.Insert(name, value);
FakeInsert(name, value);
HTTP2_VERIFY_EQ(old_count + 1, fake_dynamic_table_.size());
FakeTrim(dynamic_size_limit());
HTTP2_VERIFY_EQ(current_dynamic_size(), FakeSize());
HTTP2_VERIFY_EQ(num_dynamic_entries(), fake_dynamic_table_.size());
return VerifyDynamicTableContents();
}
private:
HpackDecoderTables tables_;
std::vector<FakeHpackEntry> fake_dynamic_table_;
};
TEST_F(HpackDecoderTablesTest, StaticTableContents) {
EXPECT_TRUE(VerifyStaticTableContents());
}
TEST_F(HpackDecoderTablesTest, RandomDynamicTable) {
EXPECT_EQ(0u, current_dynamic_size());
EXPECT_TRUE(VerifyStaticTableContents());
EXPECT_TRUE(VerifyDynamicTableContents());
std::vector<size_t> table_sizes;
table_sizes.push_back(dynamic_size_limit());
table_sizes.push_back(0);
table_sizes.push_back(dynamic_size_limit() / 2);
table_sizes.push_back(dynamic_size_limit());
table_sizes.push_back(dynamic_size_limit() / 2);
table_sizes.push_back(0);
table_sizes.push_back(dynamic_size_limit());
for (size_t limit : table_sizes) {
ASSERT_TRUE(DynamicTableSizeUpdate(limit));
for (int insert_count = 0; insert_count < 100; ++insert_count) {
std::string name =
GenerateHttp2HeaderName(random_.UniformInRange(2, 40), RandomPtr());
std::string value =
GenerateWebSafeString(random_.UniformInRange(2, 600), RandomPtr());
ASSERT_TRUE(Insert(name, value));
}
EXPECT_TRUE(VerifyStaticTableContents());
}
}
}
}
} |
439 | cpp | google/quiche | hpack_entry_decoder | quiche/http2/hpack/decoder/hpack_entry_decoder.cc | quiche/http2/hpack/decoder/hpack_entry_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_DECODER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_ENTRY_DECODER_H_
#include <string>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/hpack/decoder/hpack_decoding_error.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h"
#include "quiche/http2/hpack/decoder/hpack_entry_type_decoder.h"
#include "quiche/http2/hpack/decoder/hpack_string_decoder.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
class QUICHE_EXPORT HpackEntryDecoder {
public:
enum class EntryDecoderState {
kResumeDecodingType,
kDecodedType,
kStartDecodingName,
kResumeDecodingName,
kStartDecodingValue,
kResumeDecodingValue,
};
DecodeStatus Start(DecodeBuffer* db, HpackEntryDecoderListener* listener);
DecodeStatus Resume(DecodeBuffer* db, HpackEntryDecoderListener* listener);
HpackDecodingError error() const { return error_; }
std::string DebugString() const;
void OutputDebugString(std::ostream& out) const;
private:
bool DispatchOnType(HpackEntryDecoderListener* listener);
HpackEntryTypeDecoder entry_type_decoder_;
HpackStringDecoder string_decoder_;
EntryDecoderState state_ = EntryDecoderState();
HpackDecodingError error_ = HpackDecodingError::kOk;
};
QUICHE_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackEntryDecoder& v);
QUICHE_EXPORT std::ostream& operator<<(
std::ostream& out, HpackEntryDecoder::EntryDecoderState state);
}
#endif
#include "quiche/http2/hpack/decoder/hpack_entry_decoder.h"
#include <stddef.h>
#include <cstdint>
#include <ostream>
#include <sstream>
#include <string>
#include "absl/base/macros.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace {
class NameDecoderListener {
public:
explicit NameDecoderListener(HpackEntryDecoderListener* listener)
: listener_(listener) {}
bool OnStringStart(bool huffman_encoded, size_t len) {
listener_->OnNameStart(huffman_encoded, len);
return true;
}
void OnStringData(const char* data, size_t len) {
listener_->OnNameData(data, len);
}
void OnStringEnd() { listener_->OnNameEnd(); }
private:
HpackEntryDecoderListener* listener_;
};
class ValueDecoderListener {
public:
explicit ValueDecoderListener(HpackEntryDecoderListener* listener)
: listener_(listener) {}
bool OnStringStart(bool huffman_encoded, size_t len) {
listener_->OnValueStart(huffman_encoded, len);
return true;
}
void OnStringData(const char* data, size_t len) {
listener_->OnValueData(data, len);
}
void OnStringEnd() { listener_->OnValueEnd(); }
private:
HpackEntryDecoderListener* listener_;
};
}
DecodeStatus HpackEntryDecoder::Start(DecodeBuffer* db,
HpackEntryDecoderListener* listener) {
QUICHE_DCHECK(db != nullptr);
QUICHE_DCHECK(listener != nullptr);
QUICHE_DCHECK(db->HasData());
DecodeStatus status = entry_type_decoder_.Start(db);
switch (status) {
case DecodeStatus::kDecodeDone:
if (entry_type_decoder_.entry_type() == HpackEntryType::kIndexedHeader) {
listener->OnIndexedHeader(entry_type_decoder_.varint());
return DecodeStatus::kDecodeDone;
}
state_ = EntryDecoderState::kDecodedType;
return Resume(db, listener);
case DecodeStatus::kDecodeInProgress:
QUICHE_DCHECK_EQ(0u, db->Remaining());
state_ = EntryDecoderState::kResumeDecodingType;
return status;
case DecodeStatus::kDecodeError:
QUICHE_CODE_COUNT_N(decompress_failure_3, 11, 23);
error_ = HpackDecodingError::kIndexVarintError;
return status;
}
QUICHE_BUG(http2_bug_63_1) << "Unreachable";
return DecodeStatus::kDecodeError;
}
DecodeStatus HpackEntryDecoder::Resume(DecodeBuffer* db,
HpackEntryDecoderListener* listener) {
QUICHE_DCHECK(db != nullptr);
QUICHE_DCHECK(listener != nullptr);
DecodeStatus status;
do {
switch (state_) {
case EntryDecoderState::kResumeDecodingType:
QUICHE_DVLOG(1) << "kResumeDecodingType: db->Remaining="
<< db->Remaining();
status = entry_type_decoder_.Resume(db);
if (status == DecodeStatus::kDecodeError) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 12, 23);
error_ = HpackDecodingError::kIndexVarintError;
}
if (status != DecodeStatus::kDecodeDone) {
return status;
}
state_ = EntryDecoderState::kDecodedType;
ABSL_FALLTHROUGH_INTENDED;
case EntryDecoderState::kDecodedType:
QUICHE_DVLOG(1) << "kDecodedType: db->Remaining=" << db->Remaining();
if (DispatchOnType(listener)) {
return DecodeStatus::kDecodeDone;
}
continue;
case EntryDecoderState::kStartDecodingName:
QUICHE_DVLOG(1) << "kStartDecodingName: db->Remaining="
<< db->Remaining();
{
NameDecoderListener ncb(listener);
status = string_decoder_.Start(db, &ncb);
}
if (status != DecodeStatus::kDecodeDone) {
state_ = EntryDecoderState::kResumeDecodingName;
if (status == DecodeStatus::kDecodeError) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 13, 23);
error_ = HpackDecodingError::kNameLengthVarintError;
}
return status;
}
state_ = EntryDecoderState::kStartDecodingValue;
ABSL_FALLTHROUGH_INTENDED;
case EntryDecoderState::kStartDecodingValue:
QUICHE_DVLOG(1) << "kStartDecodingValue: db->Remaining="
<< db->Remaining();
{
ValueDecoderListener vcb(listener);
status = string_decoder_.Start(db, &vcb);
}
if (status == DecodeStatus::kDecodeError) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 14, 23);
error_ = HpackDecodingError::kValueLengthVarintError;
}
if (status == DecodeStatus::kDecodeDone) {
return status;
}
state_ = EntryDecoderState::kResumeDecodingValue;
return status;
case EntryDecoderState::kResumeDecodingName:
QUICHE_DVLOG(1) << "kResumeDecodingName: db->Remaining="
<< db->Remaining();
{
NameDecoderListener ncb(listener);
status = string_decoder_.Resume(db, &ncb);
}
if (status != DecodeStatus::kDecodeDone) {
state_ = EntryDecoderState::kResumeDecodingName;
if (status == DecodeStatus::kDecodeError) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 15, 23);
error_ = HpackDecodingError::kNameLengthVarintError;
}
return status;
}
state_ = EntryDecoderState::kStartDecodingValue;
break;
case EntryDecoderState::kResumeDecodingValue:
QUICHE_DVLOG(1) << "kResumeDecodingValue: db->Remaining="
<< db->Remaining();
{
ValueDecoderListener vcb(listener);
status = string_decoder_.Resume(db, &vcb);
}
if (status == DecodeStatus::kDecodeError) {
QUICHE_CODE_COUNT_N(decompress_failure_3, 16, 23);
error_ = HpackDecodingError::kValueLengthVarintError;
}
if (status == DecodeStatus::kDecodeDone) {
return status;
}
state_ = EntryDecoderState::kResumeDecodingValue;
return status;
}
} while (true);
}
bool HpackEntryDecoder::DispatchOnType(HpackEntryDecoderListener* listener) {
const HpackEntryType entry_type = entry_type_decoder_.entry_type();
const uint32_t varint = static_cast<uint32_t>(entry_type_decoder_.varint());
switch (entry_type) {
case HpackEntryType::kIndexedHeader:
listener->OnIndexedHeader(varint);
return true;
case HpackEntryType::kIndexedLiteralHeader:
case HpackEntryType::kUnindexedLiteralHeader:
case HpackEntryType::kNeverIndexedLiteralHeader:
listener->OnStartLiteralHeader(entry_type, varint);
if (varint == 0) {
state_ = EntryDecoderState::kStartDecodingName;
} else {
state_ = EntryDecoderState::kStartDecodingValue;
}
return false;
case HpackEntryType::kDynamicTableSizeUpdate:
listener->OnDynamicTableSizeUpdate(varint);
return true;
}
QUICHE_BUG(http2_bug_63_2) << "Unreachable, entry_type=" << entry_type;
return true;
}
void HpackEntryDecoder::OutputDebugString(std::ostream& out) const {
out << "HpackEntryDecoder(state=" << state_ << ", " << entry_type_decoder_
<< ", " << string_decoder_ << ")";
}
std::string HpackEntryDecoder::DebugString() const {
std::stringstream s;
s << *this;
return s.str();
}
std::ostream& operator<<(std::ostream& out, const HpackEntryDecoder& v) {
v.OutputDebugString(out);
return out;
}
std::ostream& operator<<(std::ostream& out,
HpackEntryDecoder::EntryDecoderState state) {
typedef HpackEntryDecoder::EntryDecoderState EntryDecoderState;
switch (state) {
case EntryDecoderState::kResumeDecodingType:
return out << "kResumeDecodingType";
case EntryDecoderState::kDecodedType:
return out << "kDecodedType";
case EntryDecoderState::kStartDecodingName:
return out << "kStartDecodingName";
case EntryDecoderState::kResumeDecodingName:
return out << "kResumeDecodingName";
case EntryDecoderState::kStartDecodingValue:
return out << "kStartDecodingValue";
case EntryDecoderState::kResumeDecodingValue:
return out << "kResumeDecodingValue";
}
return out << static_cast<int>(state);
}
} | #include "quiche/http2/hpack/decoder/hpack_entry_decoder.h"
#include <cstdint>
#include <string>
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_entry_collector.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
class HpackEntryDecoderTest : public RandomDecoderTest {
protected:
HpackEntryDecoderTest() : listener_(&collector_) {}
DecodeStatus StartDecoding(DecodeBuffer* b) override {
collector_.Clear();
return decoder_.Start(b, &listener_);
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
return decoder_.Resume(b, &listener_);
}
AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* db,
const Validator& validator) {
bool return_non_zero_on_first = true;
return RandomDecoderTest::DecodeAndValidateSeveralWays(
db, return_non_zero_on_first, validator);
}
AssertionResult DecodeAndValidateSeveralWays(const HpackBlockBuilder& hbb,
const Validator& validator) {
DecodeBuffer db(hbb.buffer());
return DecodeAndValidateSeveralWays(&db, validator);
}
HpackEntryDecoder decoder_;
HpackEntryCollector collector_;
HpackEntryDecoderVLoggingListener listener_;
};
TEST_F(HpackEntryDecoderTest, IndexedHeader_Literals) {
{
const char input[] = {'\x82'};
DecodeBuffer b(input);
auto do_check = [this]() { return collector_.ValidateIndexedHeader(2); };
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
collector_.Clear();
{
const char input[] = {'\xfe'};
DecodeBuffer b(input);
auto do_check = [this]() { return collector_.ValidateIndexedHeader(126); };
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
collector_.Clear();
{
const char input[] = {'\xff', '\x00'};
DecodeBuffer b(input);
auto do_check = [this]() { return collector_.ValidateIndexedHeader(127); };
EXPECT_TRUE(
DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
}
TEST_F(HpackEntryDecoderTest, IndexedHeader_Various) {
for (const uint32_t ndx : {1, 2, 61, 62, 63, 126, 127, 254, 255, 256}) {
HpackBlockBuilder hbb;
hbb.AppendIndexedHeader(ndx);
auto do_check = [this, ndx]() {
return collector_.ValidateIndexedHeader(ndx);
};
EXPECT_TRUE(
DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
}
TEST_F(HpackEntryDecoderTest, IndexedLiteralValue_Literal) {
const char input[] =
"\x7f"
"\x01"
"\x0d"
"custom-header";
DecodeBuffer b(input, sizeof input - 1);
auto do_check = [this]() {
return collector_.ValidateLiteralValueHeader(
HpackEntryType::kIndexedLiteralHeader, 0x40, false, "custom-header");
};
EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackEntryDecoderTest, IndexedLiteralNameValue_Literal) {
const char input[] =
"\x40"
"\x0a"
"custom-key"
"\x0d"
"custom-header";
DecodeBuffer b(input, sizeof input - 1);
auto do_check = [this]() {
return collector_.ValidateLiteralNameValueHeader(
HpackEntryType::kIndexedLiteralHeader, false, "custom-key", false,
"custom-header");
};
EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
TEST_F(HpackEntryDecoderTest, DynamicTableSizeUpdate_Literal) {
const char input[] = "\x3f\x00";
DecodeBuffer b(input, 2);
auto do_check = [this]() {
return collector_.ValidateDynamicTableSizeUpdate(31);
};
EXPECT_TRUE(DecodeAndValidateSeveralWays(&b, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
class HpackLiteralEntryDecoderTest
: public HpackEntryDecoderTest,
public ::testing::WithParamInterface<HpackEntryType> {
protected:
HpackLiteralEntryDecoderTest() : entry_type_(GetParam()) {}
const HpackEntryType entry_type_;
};
INSTANTIATE_TEST_SUITE_P(
AllLiteralTypes, HpackLiteralEntryDecoderTest,
testing::Values(HpackEntryType::kIndexedLiteralHeader,
HpackEntryType::kUnindexedLiteralHeader,
HpackEntryType::kNeverIndexedLiteralHeader));
TEST_P(HpackLiteralEntryDecoderTest, RandNameIndexAndLiteralValue) {
for (int n = 0; n < 10; n++) {
const uint32_t ndx = 1 + Random().Rand8();
const bool value_is_huffman_encoded = (n % 2) == 0;
const std::string value = Random().RandString(Random().Rand8());
HpackBlockBuilder hbb;
hbb.AppendNameIndexAndLiteralValue(entry_type_, ndx,
value_is_huffman_encoded, value);
auto do_check = [this, ndx, value_is_huffman_encoded,
value]() -> AssertionResult {
return collector_.ValidateLiteralValueHeader(
entry_type_, ndx, value_is_huffman_encoded, value);
};
EXPECT_TRUE(
DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
}
TEST_P(HpackLiteralEntryDecoderTest, RandLiteralNameAndValue) {
for (int n = 0; n < 10; n++) {
const bool name_is_huffman_encoded = (n & 1) == 0;
const int name_len = 1 + Random().Rand8();
const std::string name = Random().RandString(name_len);
const bool value_is_huffman_encoded = (n & 2) == 0;
const int value_len = Random().Skewed(10);
const std::string value = Random().RandString(value_len);
HpackBlockBuilder hbb;
hbb.AppendLiteralNameAndValue(entry_type_, name_is_huffman_encoded, name,
value_is_huffman_encoded, value);
auto do_check = [this, name_is_huffman_encoded, name,
value_is_huffman_encoded, value]() -> AssertionResult {
return collector_.ValidateLiteralNameValueHeader(
entry_type_, name_is_huffman_encoded, name, value_is_huffman_encoded,
value);
};
EXPECT_TRUE(
DecodeAndValidateSeveralWays(hbb, ValidateDoneAndEmpty(do_check)));
EXPECT_TRUE(do_check());
}
}
}
}
} |
440 | cpp | google/quiche | hpack_whole_entry_buffer | quiche/http2/hpack/decoder/hpack_whole_entry_buffer.cc | quiche/http2/hpack/decoder/hpack_whole_entry_buffer_test.cc | #ifndef QUICHE_HTTP2_HPACK_DECODER_HPACK_WHOLE_ENTRY_BUFFER_H_
#define QUICHE_HTTP2_HPACK_DECODER_HPACK_WHOLE_ENTRY_BUFFER_H_
#include <stddef.h>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/decoder/hpack_decoder_string_buffer.h"
#include "quiche/http2/hpack/decoder/hpack_decoding_error.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h"
#include "quiche/http2/hpack/decoder/hpack_whole_entry_listener.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT HpackWholeEntryBuffer : public HpackEntryDecoderListener {
public:
HpackWholeEntryBuffer(HpackWholeEntryListener* listener,
size_t max_string_size);
~HpackWholeEntryBuffer() override;
HpackWholeEntryBuffer(const HpackWholeEntryBuffer&) = delete;
HpackWholeEntryBuffer& operator=(const HpackWholeEntryBuffer&) = delete;
void set_listener(HpackWholeEntryListener* listener);
void set_max_string_size_bytes(size_t max_string_size_bytes);
void BufferStringsIfUnbuffered();
bool error_detected() const { return error_detected_; }
void OnIndexedHeader(size_t index) override;
void OnStartLiteralHeader(HpackEntryType entry_type,
size_t maybe_name_index) override;
void OnNameStart(bool huffman_encoded, size_t len) override;
void OnNameData(const char* data, size_t len) override;
void OnNameEnd() override;
void OnValueStart(bool huffman_encoded, size_t len) override;
void OnValueData(const char* data, size_t len) override;
void OnValueEnd() override;
void OnDynamicTableSizeUpdate(size_t size) override;
private:
void ReportError(HpackDecodingError error);
HpackWholeEntryListener* listener_;
HpackDecoderStringBuffer name_, value_;
size_t max_string_size_bytes_;
size_t maybe_name_index_;
HpackEntryType entry_type_;
bool error_detected_ = false;
};
}
#endif
#include "quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h"
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_text_utils.h"
namespace http2 {
HpackWholeEntryBuffer::HpackWholeEntryBuffer(HpackWholeEntryListener* listener,
size_t max_string_size_bytes)
: max_string_size_bytes_(max_string_size_bytes) {
set_listener(listener);
}
HpackWholeEntryBuffer::~HpackWholeEntryBuffer() = default;
void HpackWholeEntryBuffer::set_listener(HpackWholeEntryListener* listener) {
QUICHE_CHECK(listener);
listener_ = listener;
}
void HpackWholeEntryBuffer::set_max_string_size_bytes(
size_t max_string_size_bytes) {
max_string_size_bytes_ = max_string_size_bytes;
}
void HpackWholeEntryBuffer::BufferStringsIfUnbuffered() {
name_.BufferStringIfUnbuffered();
value_.BufferStringIfUnbuffered();
}
void HpackWholeEntryBuffer::OnIndexedHeader(size_t index) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnIndexedHeader: index=" << index;
listener_->OnIndexedHeader(index);
}
void HpackWholeEntryBuffer::OnStartLiteralHeader(HpackEntryType entry_type,
size_t maybe_name_index) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnStartLiteralHeader: entry_type="
<< entry_type << ", maybe_name_index=" << maybe_name_index;
entry_type_ = entry_type;
maybe_name_index_ = maybe_name_index;
}
void HpackWholeEntryBuffer::OnNameStart(bool huffman_encoded, size_t len) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameStart: huffman_encoded="
<< (huffman_encoded ? "true" : "false") << ", len=" << len;
QUICHE_DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_) {
if (len > max_string_size_bytes_) {
QUICHE_DVLOG(1) << "Name length (" << len
<< ") is longer than permitted ("
<< max_string_size_bytes_ << ")";
ReportError(HpackDecodingError::kNameTooLong);
QUICHE_CODE_COUNT_N(decompress_failure_3, 18, 23);
return;
}
name_.OnStart(huffman_encoded, len);
}
}
void HpackWholeEntryBuffer::OnNameData(const char* data, size_t len) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameData: len=" << len
<< " data:\n"
<< quiche::QuicheTextUtils::HexDump(
absl::string_view(data, len));
QUICHE_DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_ && !name_.OnData(data, len)) {
ReportError(HpackDecodingError::kNameHuffmanError);
QUICHE_CODE_COUNT_N(decompress_failure_3, 19, 23);
}
}
void HpackWholeEntryBuffer::OnNameEnd() {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnNameEnd";
QUICHE_DCHECK_EQ(maybe_name_index_, 0u);
if (!error_detected_ && !name_.OnEnd()) {
ReportError(HpackDecodingError::kNameHuffmanError);
QUICHE_CODE_COUNT_N(decompress_failure_3, 20, 23);
}
}
void HpackWholeEntryBuffer::OnValueStart(bool huffman_encoded, size_t len) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueStart: huffman_encoded="
<< (huffman_encoded ? "true" : "false") << ", len=" << len;
if (!error_detected_) {
if (len > max_string_size_bytes_) {
QUICHE_DVLOG(1) << "Value length (" << len << ") of ["
<< name_.GetStringIfComplete()
<< "] is longer than permitted ("
<< max_string_size_bytes_ << ")";
ReportError(HpackDecodingError::kValueTooLong);
QUICHE_CODE_COUNT_N(decompress_failure_3, 21, 23);
return;
}
value_.OnStart(huffman_encoded, len);
}
}
void HpackWholeEntryBuffer::OnValueData(const char* data, size_t len) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueData: len=" << len
<< " data:\n"
<< quiche::QuicheTextUtils::HexDump(
absl::string_view(data, len));
if (!error_detected_ && !value_.OnData(data, len)) {
ReportError(HpackDecodingError::kValueHuffmanError);
QUICHE_CODE_COUNT_N(decompress_failure_3, 22, 23);
}
}
void HpackWholeEntryBuffer::OnValueEnd() {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnValueEnd";
if (error_detected_) {
return;
}
if (!value_.OnEnd()) {
ReportError(HpackDecodingError::kValueHuffmanError);
QUICHE_CODE_COUNT_N(decompress_failure_3, 23, 23);
return;
}
if (maybe_name_index_ == 0) {
listener_->OnLiteralNameAndValue(entry_type_, &name_, &value_);
name_.Reset();
} else {
listener_->OnNameIndexAndLiteralValue(entry_type_, maybe_name_index_,
&value_);
}
value_.Reset();
}
void HpackWholeEntryBuffer::OnDynamicTableSizeUpdate(size_t size) {
QUICHE_DVLOG(2) << "HpackWholeEntryBuffer::OnDynamicTableSizeUpdate: size="
<< size;
listener_->OnDynamicTableSizeUpdate(size);
}
void HpackWholeEntryBuffer::ReportError(HpackDecodingError error) {
if (!error_detected_) {
QUICHE_DVLOG(1) << "HpackWholeEntryBuffer::ReportError: "
<< HpackDecodingErrorToString(error);
error_detected_ = true;
listener_->OnHpackDecodeError(error);
listener_ = HpackWholeEntryNoOpListener::NoOpListener();
}
}
} | #include "quiche/http2/hpack/decoder/hpack_whole_entry_buffer.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::_;
using ::testing::AllOf;
using ::testing::InSequence;
using ::testing::Property;
using ::testing::StrictMock;
namespace http2 {
namespace test {
namespace {
constexpr size_t kMaxStringSize = 20;
class MockHpackWholeEntryListener : public HpackWholeEntryListener {
public:
~MockHpackWholeEntryListener() override = default;
MOCK_METHOD(void, OnIndexedHeader, (size_t index), (override));
MOCK_METHOD(void, OnNameIndexAndLiteralValue,
(HpackEntryType entry_type, size_t name_index,
HpackDecoderStringBuffer* value_buffer),
(override));
MOCK_METHOD(void, OnLiteralNameAndValue,
(HpackEntryType entry_type, HpackDecoderStringBuffer* name_buffer,
HpackDecoderStringBuffer* value_buffer),
(override));
MOCK_METHOD(void, OnDynamicTableSizeUpdate, (size_t size), (override));
MOCK_METHOD(void, OnHpackDecodeError, (HpackDecodingError error), (override));
};
class HpackWholeEntryBufferTest : public quiche::test::QuicheTest {
protected:
HpackWholeEntryBufferTest() : entry_buffer_(&listener_, kMaxStringSize) {}
~HpackWholeEntryBufferTest() override = default;
StrictMock<MockHpackWholeEntryListener> listener_;
HpackWholeEntryBuffer entry_buffer_;
};
TEST_F(HpackWholeEntryBufferTest, OnIndexedHeader) {
{
InSequence seq;
EXPECT_CALL(listener_, OnIndexedHeader(17));
entry_buffer_.OnIndexedHeader(17);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnIndexedHeader(62));
entry_buffer_.OnIndexedHeader(62);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnIndexedHeader(62));
entry_buffer_.OnIndexedHeader(62);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnIndexedHeader(128));
entry_buffer_.OnIndexedHeader(128);
}
StrictMock<MockHpackWholeEntryListener> listener2;
entry_buffer_.set_listener(&listener2);
{
InSequence seq;
EXPECT_CALL(listener2, OnIndexedHeader(100));
entry_buffer_.OnIndexedHeader(100);
}
}
TEST_F(HpackWholeEntryBufferTest, OnDynamicTableSizeUpdate) {
{
InSequence seq;
EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(4096));
entry_buffer_.OnDynamicTableSizeUpdate(4096);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(0));
entry_buffer_.OnDynamicTableSizeUpdate(0);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024));
entry_buffer_.OnDynamicTableSizeUpdate(1024);
}
{
InSequence seq;
EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(1024));
entry_buffer_.OnDynamicTableSizeUpdate(1024);
}
StrictMock<MockHpackWholeEntryListener> listener2;
entry_buffer_.set_listener(&listener2);
{
InSequence seq;
EXPECT_CALL(listener2, OnDynamicTableSizeUpdate(0));
entry_buffer_.OnDynamicTableSizeUpdate(0);
}
}
TEST_F(HpackWholeEntryBufferTest, OnNameIndexAndLiteralValue) {
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader,
123);
entry_buffer_.OnValueStart(false, 10);
entry_buffer_.OnValueData("some data.", 10);
entry_buffer_.BufferStringsIfUnbuffered();
EXPECT_CALL(
listener_,
OnNameIndexAndLiteralValue(
HpackEntryType::kNeverIndexedLiteralHeader, 123,
AllOf(Property(&HpackDecoderStringBuffer::str, "some data."),
Property(&HpackDecoderStringBuffer::BufferedLength, 10))));
entry_buffer_.OnValueEnd();
}
TEST_F(HpackWholeEntryBufferTest, OnLiteralNameAndValue) {
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);
entry_buffer_.OnNameStart(false, 9);
entry_buffer_.OnNameData("some-", 5);
entry_buffer_.OnNameData("name", 4);
entry_buffer_.OnNameEnd();
entry_buffer_.OnValueStart(false, 12);
entry_buffer_.OnValueData("Header Value", 12);
EXPECT_CALL(
listener_,
OnLiteralNameAndValue(
HpackEntryType::kIndexedLiteralHeader,
AllOf(Property(&HpackDecoderStringBuffer::str, "some-name"),
Property(&HpackDecoderStringBuffer::BufferedLength, 9)),
AllOf(Property(&HpackDecoderStringBuffer::str, "Header Value"),
Property(&HpackDecoderStringBuffer::BufferedLength, 0))));
entry_buffer_.OnValueEnd();
}
TEST_F(HpackWholeEntryBufferTest, NameTooLong) {
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);
EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kNameTooLong));
entry_buffer_.OnNameStart(false, kMaxStringSize + 1);
}
TEST_F(HpackWholeEntryBufferTest, ValueTooLong) {
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 0);
EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong));
entry_buffer_.OnNameStart(false, 4);
entry_buffer_.OnNameData("path", 4);
entry_buffer_.OnNameEnd();
entry_buffer_.OnValueStart(false, kMaxStringSize + 1);
}
TEST_F(HpackWholeEntryBufferTest, ValueTooLongWithoutName) {
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);
EXPECT_CALL(listener_, OnHpackDecodeError(HpackDecodingError::kValueTooLong));
entry_buffer_.OnValueStart(false, kMaxStringSize + 1);
}
TEST_F(HpackWholeEntryBufferTest, NameHuffmanError) {
const char data[] = "\xff\xff\xff";
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader,
0);
entry_buffer_.OnNameStart(true, 4);
entry_buffer_.OnNameData(data, 3);
EXPECT_CALL(listener_,
OnHpackDecodeError(HpackDecodingError::kNameHuffmanError));
entry_buffer_.OnNameData(data, 1);
EXPECT_CALL(listener_, OnDynamicTableSizeUpdate(8096)).Times(0);
entry_buffer_.OnDynamicTableSizeUpdate(8096);
}
TEST_F(HpackWholeEntryBufferTest, ValueHuffmanError) {
const char data[] = "\x00\x00\x00";
entry_buffer_.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader,
61);
entry_buffer_.OnValueStart(true, 3);
entry_buffer_.OnValueData(data, 3);
EXPECT_CALL(listener_,
OnHpackDecodeError(HpackDecodingError::kValueHuffmanError));
entry_buffer_.OnValueEnd();
EXPECT_CALL(listener_, OnIndexedHeader(17)).Times(0);
entry_buffer_.OnIndexedHeader(17);
}
}
}
} |
441 | cpp | google/quiche | hpack_huffman_encoder | quiche/http2/hpack/huffman/hpack_huffman_encoder.cc | quiche/http2/hpack/huffman/hpack_huffman_encoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_
#define QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_ENCODER_H_
#include <cstddef>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
QUICHE_EXPORT size_t HuffmanSize(absl::string_view plain);
QUICHE_EXPORT void HuffmanEncode(absl::string_view plain, size_t encoded_size,
std::string* huffman);
QUICHE_EXPORT void HuffmanEncodeFast(absl::string_view input,
size_t encoded_size, std::string* output);
}
#endif
#include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h"
#include <string>
#include "quiche/http2/hpack/huffman/huffman_spec_tables.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
size_t HuffmanSize(absl::string_view plain) {
size_t bits = 0;
for (const uint8_t c : plain) {
bits += HuffmanSpecTables::kCodeLengths[c];
}
return (bits + 7) / 8;
}
void HuffmanEncode(absl::string_view plain, size_t encoded_size,
std::string* huffman) {
QUICHE_DCHECK(huffman != nullptr);
huffman->reserve(huffman->size() + encoded_size);
uint64_t bit_buffer = 0;
size_t bits_unused = 64;
for (uint8_t c : plain) {
size_t code_length = HuffmanSpecTables::kCodeLengths[c];
if (bits_unused < code_length) {
do {
char h = static_cast<char>(bit_buffer >> 56);
bit_buffer <<= 8;
bits_unused += 8;
huffman->push_back(h);
} while (bits_unused <= 56);
}
uint64_t code = HuffmanSpecTables::kRightCodes[c];
size_t shift_by = bits_unused - code_length;
bit_buffer |= (code << shift_by);
bits_unused -= code_length;
}
size_t bits_used = 64 - bits_unused;
while (bits_used >= 8) {
char h = static_cast<char>(bit_buffer >> 56);
bit_buffer <<= 8;
bits_used -= 8;
huffman->push_back(h);
}
if (bits_used > 0) {
constexpr uint64_t leading_eos_bits = 0b11111111;
bit_buffer |= (leading_eos_bits << (56 - bits_used));
char h = static_cast<char>(bit_buffer >> 56);
huffman->push_back(h);
}
}
void HuffmanEncodeFast(absl::string_view input, size_t encoded_size,
std::string* output) {
const size_t original_size = output->size();
const size_t final_size = original_size + encoded_size;
output->resize(final_size + 4, 0);
char* const first = &*output->begin() + original_size;
size_t bit_counter = 0;
for (uint8_t c : input) {
uint64_t code = static_cast<uint64_t>(HuffmanSpecTables::kLeftCodes[c])
<< (8 - (bit_counter % 8));
char* const current = first + (bit_counter / 8);
bit_counter += HuffmanSpecTables::kCodeLengths[c];
*current |= code >> 32;
*(current + 1) |= (code >> 24) & 0xff;
if ((code & 0xff0000) == 0) {
continue;
}
*(current + 2) |= (code >> 16) & 0xff;
if ((code & 0xff00) == 0) {
continue;
}
*(current + 3) |= (code >> 8) & 0xff;
*(current + 4) |= code & 0xff;
}
QUICHE_DCHECK_EQ(encoded_size, (bit_counter + 7) / 8);
if (bit_counter % 8 != 0) {
*(first + encoded_size - 1) |= 0xff >> (bit_counter & 7);
}
output->resize(final_size);
}
} | #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h"
#include <cstddef>
#include <string>
#include "absl/base/macros.h"
#include "absl/strings/escaping.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace {
class HuffmanEncoderTest : public quiche::test::QuicheTestWithParam<bool> {
protected:
HuffmanEncoderTest() : use_fast_encoder_(GetParam()) {}
virtual ~HuffmanEncoderTest() = default;
void Encode(absl::string_view input, size_t encoded_size,
std::string* output) {
use_fast_encoder_ ? HuffmanEncodeFast(input, encoded_size, output)
: HuffmanEncode(input, encoded_size, output);
}
const bool use_fast_encoder_;
};
INSTANTIATE_TEST_SUITE_P(TwoEncoders, HuffmanEncoderTest, ::testing::Bool());
TEST_P(HuffmanEncoderTest, Empty) {
std::string empty("");
size_t encoded_size = HuffmanSize(empty);
EXPECT_EQ(0u, encoded_size);
std::string buffer;
Encode(empty, encoded_size, &buffer);
EXPECT_EQ("", buffer);
}
TEST_P(HuffmanEncoderTest, SpecRequestExamples) {
std::string test_table[] = {
"f1e3c2e5f23a6ba0ab90f4ff",
"www.example.com",
"a8eb10649cbf",
"no-cache",
"25a849e95ba97d7f",
"custom-key",
"25a849e95bb8e8b4bf",
"custom-value",
};
for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {
std::string huffman_encoded;
ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));
const std::string& plain_string(test_table[i + 1]);
size_t encoded_size = HuffmanSize(plain_string);
EXPECT_EQ(huffman_encoded.size(), encoded_size);
std::string buffer;
buffer.reserve(huffman_encoded.size());
Encode(plain_string, encoded_size, &buffer);
EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string;
}
}
TEST_P(HuffmanEncoderTest, SpecResponseExamples) {
std::string test_table[] = {
"6402",
"302",
"aec3771a4b",
"private",
"d07abe941054d444a8200595040b8166e082a62d1bff",
"Mon, 21 Oct 2013 20:13:21 GMT",
"9d29ad171863c78f0b97c8e9ae82ae43d3",
"https:
"94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0"
"03ed4ee5b1063d5007",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
};
for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {
std::string huffman_encoded;
ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));
const std::string& plain_string(test_table[i + 1]);
size_t encoded_size = HuffmanSize(plain_string);
EXPECT_EQ(huffman_encoded.size(), encoded_size);
std::string buffer;
Encode(plain_string, encoded_size, &buffer);
EXPECT_EQ(buffer, huffman_encoded) << "Error encoding " << plain_string;
}
}
TEST_P(HuffmanEncoderTest, EncodedSizeAgreesWithEncodeString) {
std::string test_table[] = {
"",
"Mon, 21 Oct 2013 20:13:21 GMT",
"https:
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
std::string(1, '\0'),
std::string("foo\0bar", 7),
std::string(256, '\0'),
};
for (size_t i = 0; i != 256; ++i) {
test_table[ABSL_ARRAYSIZE(test_table) - 1][i] = static_cast<char>(i);
}
for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); ++i) {
const std::string& plain_string = test_table[i];
size_t encoded_size = HuffmanSize(plain_string);
std::string huffman_encoded;
Encode(plain_string, encoded_size, &huffman_encoded);
EXPECT_EQ(encoded_size, huffman_encoded.size());
}
}
TEST_P(HuffmanEncoderTest, AppendToOutput) {
size_t encoded_size = HuffmanSize("foo");
std::string buffer;
Encode("foo", encoded_size, &buffer);
std::string expected_encoding;
ASSERT_TRUE(absl::HexStringToBytes("94e7", &expected_encoding));
EXPECT_EQ(expected_encoding, buffer);
encoded_size = HuffmanSize("bar");
Encode("bar", encoded_size, &buffer);
ASSERT_TRUE(absl::HexStringToBytes("94e78c767f", &expected_encoding));
EXPECT_EQ(expected_encoding, buffer);
}
}
} |
442 | cpp | google/quiche | hpack_huffman_decoder | quiche/http2/hpack/huffman/hpack_huffman_decoder.cc | quiche/http2/hpack/huffman/hpack_huffman_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_DECODER_H_
#define QUICHE_HTTP2_HPACK_HUFFMAN_HPACK_HUFFMAN_DECODER_H_
#include <stddef.h>
#include <cstdint>
#include <iosfwd>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
typedef uint64_t HuffmanAccumulator;
typedef size_t HuffmanAccumulatorBitCount;
class QUICHE_EXPORT HuffmanBitBuffer {
public:
HuffmanBitBuffer();
void Reset();
size_t AppendBytes(absl::string_view input);
HuffmanAccumulator value() const { return accumulator_; }
HuffmanAccumulatorBitCount count() const { return count_; }
bool IsEmpty() const { return count_ == 0; }
HuffmanAccumulatorBitCount free_count() const;
void ConsumeBits(HuffmanAccumulatorBitCount code_length);
bool InputProperlyTerminated() const;
std::string DebugString() const;
private:
HuffmanAccumulator accumulator_;
HuffmanAccumulatorBitCount count_;
};
inline std::ostream& operator<<(std::ostream& out, const HuffmanBitBuffer& v) {
return out << v.DebugString();
}
class QUICHE_EXPORT HpackHuffmanDecoder {
public:
HpackHuffmanDecoder();
~HpackHuffmanDecoder();
void Reset() { bit_buffer_.Reset(); }
bool Decode(absl::string_view input, std::string* output);
bool InputProperlyTerminated() const {
return bit_buffer_.InputProperlyTerminated();
}
std::string DebugString() const;
private:
HuffmanBitBuffer bit_buffer_;
};
inline std::ostream& operator<<(std::ostream& out,
const HpackHuffmanDecoder& v) {
return out << v.DebugString();
}
}
#endif
#include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h"
#include <bitset>
#include <limits>
#include <ostream>
#include <sstream>
#include <string>
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace {
typedef uint32_t HuffmanCode;
typedef uint16_t HuffmanCodeBitCount;
typedef std::bitset<32> HuffmanCodeBitSet;
typedef std::bitset<64> HuffmanAccumulatorBitSet;
static constexpr HuffmanCodeBitCount kMinCodeBitCount = 5;
static constexpr HuffmanCodeBitCount kMaxCodeBitCount = 30;
static constexpr HuffmanCodeBitCount kHuffmanCodeBitCount =
std::numeric_limits<HuffmanCode>::digits;
static_assert(std::numeric_limits<HuffmanCode>::digits >= kMaxCodeBitCount,
"HuffmanCode isn't big enough.");
static_assert(std::numeric_limits<HuffmanAccumulator>::digits >=
kMaxCodeBitCount,
"HuffmanAccumulator isn't big enough.");
static constexpr HuffmanAccumulatorBitCount kHuffmanAccumulatorBitCount =
std::numeric_limits<HuffmanAccumulator>::digits;
static constexpr HuffmanAccumulatorBitCount kExtraAccumulatorBitCount =
kHuffmanAccumulatorBitCount - kHuffmanCodeBitCount;
struct PrefixInfo {
uint32_t DecodeToCanonical(HuffmanCode bits) const {
HuffmanCode ordinal_in_length =
((bits - first_code) >> (kHuffmanCodeBitCount - code_length));
return first_canonical + ordinal_in_length;
}
const HuffmanCode first_code;
const uint16_t code_length;
const uint16_t first_canonical;
};
inline std::ostream& operator<<(std::ostream& out, const PrefixInfo& v) {
return out << "{first_code: " << HuffmanCodeBitSet(v.first_code)
<< ", code_length: " << v.code_length
<< ", first_canonical: " << v.first_canonical << "}";
}
PrefixInfo PrefixToInfo(HuffmanCode value) {
if (value < 0b10111000000000000000000000000000) {
if (value < 0b01010000000000000000000000000000) {
return {0b00000000000000000000000000000000, 5, 0};
} else {
return {0b01010000000000000000000000000000, 6, 10};
}
} else {
if (value < 0b11111110000000000000000000000000) {
if (value < 0b11111000000000000000000000000000) {
return {0b10111000000000000000000000000000, 7, 36};
} else {
return {0b11111000000000000000000000000000, 8, 68};
}
} else {
if (value < 0b11111111110000000000000000000000) {
if (value < 0b11111111101000000000000000000000) {
if (value < 0b11111111010000000000000000000000) {
return {0b11111110000000000000000000000000, 10, 74};
} else {
return {0b11111111010000000000000000000000, 11, 79};
}
} else {
return {0b11111111101000000000000000000000, 12, 82};
}
} else {
if (value < 0b11111111111111100000000000000000) {
if (value < 0b11111111111110000000000000000000) {
if (value < 0b11111111111100000000000000000000) {
return {0b11111111110000000000000000000000, 13, 84};
} else {
return {0b11111111111100000000000000000000, 14, 90};
}
} else {
return {0b11111111111110000000000000000000, 15, 92};
}
} else {
if (value < 0b11111111111111110100100000000000) {
if (value < 0b11111111111111101110000000000000) {
if (value < 0b11111111111111100110000000000000) {
return {0b11111111111111100000000000000000, 19, 95};
} else {
return {0b11111111111111100110000000000000, 20, 98};
}
} else {
return {0b11111111111111101110000000000000, 21, 106};
}
} else {
if (value < 0b11111111111111111110101000000000) {
if (value < 0b11111111111111111011000000000000) {
return {0b11111111111111110100100000000000, 22, 119};
} else {
return {0b11111111111111111011000000000000, 23, 145};
}
} else {
if (value < 0b11111111111111111111101111000000) {
if (value < 0b11111111111111111111100000000000) {
if (value < 0b11111111111111111111011000000000) {
return {0b11111111111111111110101000000000, 24, 174};
} else {
return {0b11111111111111111111011000000000, 25, 186};
}
} else {
return {0b11111111111111111111100000000000, 26, 190};
}
} else {
if (value < 0b11111111111111111111111111110000) {
if (value < 0b11111111111111111111111000100000) {
return {0b11111111111111111111101111000000, 27, 205};
} else {
return {0b11111111111111111111111000100000, 28, 224};
}
} else {
return {0b11111111111111111111111111110000, 30, 253};
}
}
}
}
}
}
}
}
}
constexpr unsigned char kCanonicalToSymbol[] = {
'0', '1', '2', 'a', 'c', 'e', 'i', 'o',
's', 't', 0x20, '%', '-', '.', '/', '3',
'4', '5', '6', '7', '8', '9', '=', 'A',
'_', 'b', 'd', 'f', 'g', 'h', 'l', 'm',
'n', 'p', 'r', 'u', ':', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'Y', 'j', 'k', 'q', 'v',
'w', 'x', 'y', 'z', '&', '*', ',', ';',
'X', 'Z', '!', '\"', '(', ')', '?', '\'',
'+', '|', '#', '>', 0x00, '$', '@', '[',
']', '~', '^', '}', '<', '`', '{', '\\',
0xc3, 0xd0, 0x80, 0x82, 0x83, 0xa2, 0xb8, 0xc2,
0xe0, 0xe2, 0x99, 0xa1, 0xa7, 0xac, 0xb0, 0xb1,
0xb3, 0xd1, 0xd8, 0xd9, 0xe3, 0xe5, 0xe6, 0x81,
0x84, 0x85, 0x86, 0x88, 0x92, 0x9a, 0x9c, 0xa0,
0xa3, 0xa4, 0xa9, 0xaa, 0xad, 0xb2, 0xb5, 0xb9,
0xba, 0xbb, 0xbd, 0xbe, 0xc4, 0xc6, 0xe4, 0xe8,
0xe9, 0x01, 0x87, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
0x8f, 0x93, 0x95, 0x96, 0x97, 0x98, 0x9b, 0x9d,
0x9e, 0xa5, 0xa6, 0xa8, 0xae, 0xaf, 0xb4, 0xb6,
0xb7, 0xbc, 0xbf, 0xc5, 0xe7, 0xef, 0x09, 0x8e,
0x90, 0x91, 0x94, 0x9f, 0xab, 0xce, 0xd7, 0xe1,
0xec, 0xed, 0xc7, 0xcf, 0xea, 0xeb, 0xc0, 0xc1,
0xc8, 0xc9, 0xca, 0xcd, 0xd2, 0xd5, 0xda, 0xdb,
0xee, 0xf0, 0xf2, 0xf3, 0xff, 0xcb, 0xcc, 0xd3,
0xd4, 0xd6, 0xdd, 0xde, 0xdf, 0xf1, 0xf4, 0xf5,
0xf6, 0xf7, 0xf8, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0b,
0x0c, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
0x15, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, 0x7f, 0xdc, 0xf9, 0x0a, 0x0d, 0x16,
};
constexpr size_t kShortCodeTableSize = 124;
struct ShortCodeInfo {
uint8_t symbol;
uint8_t length;
} kShortCodeTable[kShortCodeTableSize] = {
{0x30, 5},
{0x30, 5},
{0x30, 5},
{0x30, 5},
{0x31, 5},
{0x31, 5},
{0x31, 5},
{0x31, 5},
{0x32, 5},
{0x32, 5},
{0x32, 5},
{0x32, 5},
{0x61, 5},
{0x61, 5},
{0x61, 5},
{0x61, 5},
{0x63, 5},
{0x63, 5},
{0x63, 5},
{0x63, 5},
{0x65, 5},
{0x65, 5},
{0x65, 5},
{0x65, 5},
{0x69, 5},
{0x69, 5},
{0x69, 5},
{0x69, 5},
{0x6f, 5},
{0x6f, 5},
{0x6f, 5},
{0x6f, 5},
{0x73, 5},
{0x73, 5},
{0x73, 5},
{0x73, 5},
{0x74, 5},
{0x74, 5},
{0x74, 5},
{0x74, 5},
{0x20, 6},
{0x20, 6},
{0x25, 6},
{0x25, 6},
{0x2d, 6},
{0x2d, 6},
{0x2e, 6},
{0x2e, 6},
{0x2f, 6},
{0x2f, 6},
{0x33, 6},
{0x33, 6},
{0x34, 6},
{0x34, 6},
{0x35, 6},
{0x35, 6},
{0x36, 6},
{0x36, 6},
{0x37, 6},
{0x37, 6},
{0x38, 6},
{0x38, 6},
{0x39, 6},
{0x39, 6},
{0x3d, 6},
{0x3d, 6},
{0x41, 6},
{0x41, 6},
{0x5f, 6},
{0x5f, 6},
{0x62, 6},
{0x62, 6},
{0x64, 6},
{0x64, 6},
{0x66, 6},
{0x66, 6},
{0x67, 6},
{0x67, 6},
{0x68, 6},
{0x68, 6},
{0x6c, 6},
{0x6c, 6},
{0x6d, 6},
{0x6d, 6},
{0x6e, 6},
{0x6e, 6},
{0x70, 6},
{0x70, 6},
{0x72, 6},
{0x72, 6},
{0x75, 6},
{0x75, 6},
{0x3a, 7},
{0x42, 7},
{0x43, 7},
{0x44, 7},
{0x45, 7},
{0x46, 7},
{0x47, 7},
{0x48, 7},
{0x49, 7},
{0x4a, 7},
{0x4b, 7},
{0x4c, 7},
{0x4d, 7},
{0x4e, 7},
{0x4f, 7},
{0x50, 7},
{0x51, 7},
{0x52, 7},
{0x53, 7},
{0x54, 7},
{0x55, 7},
{0x56, 7},
{0x57, 7},
{0x59, 7},
{0x6a, 7},
{0x6b, 7},
{0x71, 7},
{0x76, 7},
{0x77, 7},
{0x78, 7},
{0x79, 7},
{0x7a, 7},
};
}
HuffmanBitBuffer::HuffmanBitBuffer() { Reset(); }
void HuffmanBitBuffer::Reset() {
accumulator_ = 0;
count_ = 0;
}
size_t HuffmanBitBuffer::AppendBytes(absl::string_view input) {
HuffmanAccumulatorBitCount free_cnt = free_count();
size_t bytes_available = input.size();
if (free_cnt < 8 || bytes_available == 0) {
return 0;
}
size_t bytes_used = 0;
auto* ptr = reinterpret_cast<const uint8_t*>(input.data());
do {
auto b = static_cast<HuffmanAccumulator>(*ptr++);
free_cnt -= 8;
accumulator_ |= (b << free_cnt);
++bytes_used;
} while (free_cnt >= 8 && bytes_used < bytes_available);
count_ += (bytes_used * 8);
return bytes_used;
}
HuffmanAccumulatorBitCount HuffmanBitBuffer::free_count() const {
return kHuffmanAccumulatorBitCount - count_;
}
void HuffmanBitBuffer::ConsumeBits(HuffmanAccumulatorBitCount code_length) {
QUICHE_DCHECK_LE(code_length, count_);
accumulator_ <<= code_length;
count_ -= code_length;
}
bool HuffmanBitBuffer::InputProperlyTerminated() const {
auto cnt = count();
if (cnt < 8) {
if (cnt == 0) {
return true;
}
HuffmanAccumulator expected = ~(~HuffmanAccumulator() >> cnt);
QUICHE_DCHECK_EQ(accumulator_ & ~expected, 0u)
<< "\n expected: " << HuffmanAccumulatorBitSet(expected) << "\n "
<< *this;
return accumulator_ == expected;
}
return false;
}
std::string HuffmanBitBuffer::DebugString() const {
std::stringstream ss;
ss << "{accumulator: " << HuffmanAccumulatorBitSet(accumulator_)
<< "; count: " << count_ << "}";
return ss.str();
}
HpackHuffmanDecoder::HpackHuffmanDecoder() = default;
HpackHuffmanDecoder::~HpackHuffmanDecoder() = default;
bool HpackHuffmanDecoder::Decode(absl::string_view input, std::string* output) {
QUICHE_DVLOG(1) << "HpackHuffmanDecoder::Decode";
input.remove_prefix(bit_buffer_.AppendBytes(input));
while (true) {
QUICHE_DVLOG(3) << "Enter Decode Loop, bit_buffer_: " << bit_buffer_;
if (bit_buffer_.count() >= 7) {
uint8_t short_code =
bit_buffer_.value() >> (kHuffmanAccumulatorBitCount - 7);
QUICHE_DCHECK_LT(short_code, 128);
if (short_code < kShortCodeTableSize) {
ShortCodeInfo info = kShortCodeTable[short_code];
bit_buffer_.ConsumeBits(info.length);
output->push_back(static_cast<char>(info.symbol));
continue;
}
} else {
size_t byte_count = bit_buffer_.AppendBytes(input);
if (byte_count > 0) {
input.remove_prefix(byte_count);
continue;
}
}
HuffmanCode code_prefix = bit_buffer_.value() >> kExtraAccumulatorBitCount;
QUICHE_DVLOG(3) << "code_prefix: " << HuffmanCodeBitSet(code_prefix);
PrefixInfo prefix_info = PrefixToInfo(code_prefix);
QUICHE_DVLOG(3) << "prefix_info: " << prefix_info;
QUICHE_DCHECK_LE(kMinCodeBitCount, prefix_info.code_length);
QUICHE_DCHECK_LE(prefix_info.code_length, kMaxCodeBitCount);
if (prefix_info.code_length <= bit_buffer_.count()) {
uint32_t canonical = prefix_info.DecodeToCanonical(code_prefix);
if (canonical < 256) {
char c = kCanonicalToSymbol[canonical];
output->push_back(c);
bit_buffer_.ConsumeBits(prefix_info.code_length);
continue;
}
QUICHE_DLOG(ERROR) << "EOS explicitly encoded!\n " << bit_buffer_ << "\n "
<< prefix_info;
return false;
}
size_t byte_count = bit_buffer_.AppendBytes(input);
if (byte_count == 0) {
QUICHE_DCHECK_EQ(input.size(), 0u);
return true;
}
input.remove_prefix(byte_count);
}
}
std::string HpackHuffmanDecoder::DebugString() const {
return bit_buffer_.DebugString();
}
} | #include "quiche/http2/hpack/huffman/hpack_huffman_decoder.h"
#include <cstddef>
#include <iostream>
#include <string>
#include "absl/base/macros.h"
#include "absl/strings/escaping.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
TEST(HuffmanBitBufferTest, Reset) {
HuffmanBitBuffer bb;
EXPECT_TRUE(bb.IsEmpty());
EXPECT_TRUE(bb.InputProperlyTerminated());
EXPECT_EQ(bb.count(), 0u);
EXPECT_EQ(bb.free_count(), 64u);
EXPECT_EQ(bb.value(), 0u);
}
TEST(HuffmanBitBufferTest, AppendBytesAligned) {
std::string s;
s.push_back('\x11');
s.push_back('\x22');
s.push_back('\x33');
absl::string_view sp(s);
HuffmanBitBuffer bb;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_TRUE(sp.empty());
EXPECT_FALSE(bb.IsEmpty()) << bb;
EXPECT_FALSE(bb.InputProperlyTerminated());
EXPECT_EQ(bb.count(), 24u) << bb;
EXPECT_EQ(bb.free_count(), 40u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 40) << bb;
s.clear();
s.push_back('\x44');
sp = s;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_TRUE(sp.empty());
EXPECT_EQ(bb.count(), 32u) << bb;
EXPECT_EQ(bb.free_count(), 32u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x11223344) << 32) << bb;
s.clear();
s.push_back('\x55');
s.push_back('\x66');
s.push_back('\x77');
s.push_back('\x88');
s.push_back('\x99');
sp = s;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_EQ(sp.size(), 1u);
EXPECT_EQ('\x99', sp[0]);
EXPECT_EQ(bb.count(), 64u) << bb;
EXPECT_EQ(bb.free_count(), 0u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_EQ(sp.size(), 1u);
EXPECT_EQ('\x99', sp[0]);
EXPECT_EQ(bb.count(), 64u) << bb;
EXPECT_EQ(bb.free_count(), 0u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x1122334455667788LL)) << bb;
}
TEST(HuffmanBitBufferTest, ConsumeBits) {
std::string s;
s.push_back('\x11');
s.push_back('\x22');
s.push_back('\x33');
absl::string_view sp(s);
HuffmanBitBuffer bb;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_TRUE(sp.empty());
bb.ConsumeBits(1);
EXPECT_EQ(bb.count(), 23u) << bb;
EXPECT_EQ(bb.free_count(), 41u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x112233) << 41) << bb;
bb.ConsumeBits(20);
EXPECT_EQ(bb.count(), 3u) << bb;
EXPECT_EQ(bb.free_count(), 61u) << bb;
EXPECT_EQ(bb.value(), HuffmanAccumulator(0x3) << 61) << bb;
}
TEST(HuffmanBitBufferTest, AppendBytesUnaligned) {
std::string s;
s.push_back('\x11');
s.push_back('\x22');
s.push_back('\x33');
s.push_back('\x44');
s.push_back('\x55');
s.push_back('\x66');
s.push_back('\x77');
s.push_back('\x88');
s.push_back('\x99');
s.push_back('\xaa');
s.push_back('\xbb');
s.push_back('\xcc');
s.push_back('\xdd');
absl::string_view sp(s);
HuffmanBitBuffer bb;
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_EQ(sp.size(), 5u);
EXPECT_FALSE(bb.InputProperlyTerminated());
bb.ConsumeBits(15);
EXPECT_EQ(bb.count(), 49u) << bb;
EXPECT_EQ(bb.free_count(), 15u) << bb;
HuffmanAccumulator expected(0x1122334455667788);
expected <<= 15;
EXPECT_EQ(bb.value(), expected);
sp.remove_prefix(bb.AppendBytes(sp));
EXPECT_EQ(sp.size(), 4u);
EXPECT_EQ(bb.count(), 57u) << bb;
EXPECT_EQ(bb.free_count(), 7u) << bb;
expected |= (HuffmanAccumulator(0x99) << 7);
EXPECT_EQ(bb.value(), expected)
<< bb << std::hex << "\n actual: " << bb.value()
<< "\n expected: " << expected;
}
class HpackHuffmanDecoderTest : public RandomDecoderTest {
protected:
HpackHuffmanDecoderTest() {
stop_decode_on_done_ = false;
}
DecodeStatus StartDecoding(DecodeBuffer* b) override {
input_bytes_seen_ = 0;
output_buffer_.clear();
decoder_.Reset();
return ResumeDecoding(b);
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
input_bytes_seen_ += b->Remaining();
absl::string_view sp(b->cursor(), b->Remaining());
if (decoder_.Decode(sp, &output_buffer_)) {
b->AdvanceCursor(b->Remaining());
EXPECT_LE(input_bytes_seen_, input_bytes_expected_);
if (input_bytes_expected_ == input_bytes_seen_) {
if (decoder_.InputProperlyTerminated()) {
return DecodeStatus::kDecodeDone;
} else {
return DecodeStatus::kDecodeError;
}
}
return DecodeStatus::kDecodeInProgress;
}
return DecodeStatus::kDecodeError;
}
HpackHuffmanDecoder decoder_;
std::string output_buffer_;
size_t input_bytes_seen_;
size_t input_bytes_expected_;
};
TEST_F(HpackHuffmanDecoderTest, SpecRequestExamples) {
HpackHuffmanDecoder decoder;
std::string test_table[] = {
"f1e3c2e5f23a6ba0ab90f4ff",
"www.example.com",
"a8eb10649cbf",
"no-cache",
"25a849e95ba97d7f",
"custom-key",
"25a849e95bb8e8b4bf",
"custom-value",
};
for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {
std::string huffman_encoded;
ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));
const std::string& plain_string(test_table[i + 1]);
std::string buffer;
decoder.Reset();
EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder;
EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder;
EXPECT_EQ(buffer, plain_string);
}
}
TEST_F(HpackHuffmanDecoderTest, SpecResponseExamples) {
HpackHuffmanDecoder decoder;
std::string test_table[] = {
"6402",
"302",
"aec3771a4b",
"private",
"d07abe941054d444a8200595040b8166e082a62d1bff",
"Mon, 21 Oct 2013 20:13:21 GMT",
"9d29ad171863c78f0b97c8e9ae82ae43d3",
"https:
"94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c0"
"03ed4ee5b1063d5007",
"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1",
};
for (size_t i = 0; i != ABSL_ARRAYSIZE(test_table); i += 2) {
std::string huffman_encoded;
ASSERT_TRUE(absl::HexStringToBytes(test_table[i], &huffman_encoded));
const std::string& plain_string(test_table[i + 1]);
std::string buffer;
decoder.Reset();
EXPECT_TRUE(decoder.Decode(huffman_encoded, &buffer)) << decoder;
EXPECT_TRUE(decoder.InputProperlyTerminated()) << decoder;
EXPECT_EQ(buffer, plain_string);
}
}
}
}
} |
443 | cpp | google/quiche | hpack_varint_decoder | quiche/http2/hpack/varint/hpack_varint_decoder.cc | quiche/http2/hpack/varint/hpack_varint_decoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_DECODER_H_
#define QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_DECODER_H_
#include <cstdint>
#include <limits>
#include <string>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
#ifndef NDEBUG
const uint8_t kHpackVarintDecoderOffsetDone =
std::numeric_limits<uint8_t>::max();
#endif
class QUICHE_EXPORT HpackVarintDecoder {
public:
DecodeStatus Start(uint8_t prefix_value, uint8_t prefix_length,
DecodeBuffer* db);
DecodeStatus StartExtended(uint8_t prefix_length, DecodeBuffer* db);
DecodeStatus Resume(DecodeBuffer* db);
uint64_t value() const;
void set_value(uint64_t v);
std::string DebugString() const;
DecodeStatus StartForTest(uint8_t prefix_value, uint8_t prefix_length,
DecodeBuffer* db);
DecodeStatus StartExtendedForTest(uint8_t prefix_length, DecodeBuffer* db);
DecodeStatus ResumeForTest(DecodeBuffer* db);
private:
void MarkDone() {
#ifndef NDEBUG
offset_ = kHpackVarintDecoderOffsetDone;
#endif
}
void CheckNotDone() const {
#ifndef NDEBUG
QUICHE_DCHECK_NE(kHpackVarintDecoderOffsetDone, offset_);
#endif
}
void CheckDone() const {
#ifndef NDEBUG
QUICHE_DCHECK_EQ(kHpackVarintDecoderOffsetDone, offset_);
#endif
}
uint64_t value_ = 0;
uint8_t offset_ = 0;
};
}
#endif
#include "quiche/http2/hpack/varint/hpack_varint_decoder.h"
#include <limits>
#include <string>
#include "absl/strings/str_cat.h"
namespace http2 {
DecodeStatus HpackVarintDecoder::Start(uint8_t prefix_value,
uint8_t prefix_length,
DecodeBuffer* db) {
QUICHE_DCHECK_LE(3u, prefix_length);
QUICHE_DCHECK_LE(prefix_length, 8u);
const uint8_t prefix_mask = (1 << prefix_length) - 1;
value_ = prefix_value & prefix_mask;
if (value_ < prefix_mask) {
MarkDone();
return DecodeStatus::kDecodeDone;
}
offset_ = 0;
return Resume(db);
}
DecodeStatus HpackVarintDecoder::StartExtended(uint8_t prefix_length,
DecodeBuffer* db) {
QUICHE_DCHECK_LE(3u, prefix_length);
QUICHE_DCHECK_LE(prefix_length, 8u);
value_ = (1 << prefix_length) - 1;
offset_ = 0;
return Resume(db);
}
DecodeStatus HpackVarintDecoder::Resume(DecodeBuffer* db) {
const uint8_t kMaxOffset = 63;
CheckNotDone();
while (offset_ < kMaxOffset) {
if (db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
uint8_t byte = db->DecodeUInt8();
uint64_t summand = byte & 0x7f;
QUICHE_DCHECK_LE(offset_, 56);
QUICHE_DCHECK_LE(summand, std::numeric_limits<uint64_t>::max() >> offset_);
summand <<= offset_;
QUICHE_DCHECK_LE(value_, std::numeric_limits<uint64_t>::max() - summand);
value_ += summand;
if ((byte & 0x80) == 0) {
MarkDone();
return DecodeStatus::kDecodeDone;
}
offset_ += 7;
}
if (db->Empty()) {
return DecodeStatus::kDecodeInProgress;
}
QUICHE_DCHECK_EQ(kMaxOffset, offset_);
uint8_t byte = db->DecodeUInt8();
if ((byte & 0x80) == 0) {
uint64_t summand = byte & 0x7f;
if (summand <= std::numeric_limits<uint64_t>::max() >> offset_) {
summand <<= offset_;
if (value_ <= std::numeric_limits<uint64_t>::max() - summand) {
value_ += summand;
MarkDone();
return DecodeStatus::kDecodeDone;
}
}
}
QUICHE_DLOG(WARNING)
<< "Variable length int encoding is too large or too long. "
<< DebugString();
MarkDone();
return DecodeStatus::kDecodeError;
}
uint64_t HpackVarintDecoder::value() const {
CheckDone();
return value_;
}
void HpackVarintDecoder::set_value(uint64_t v) {
MarkDone();
value_ = v;
}
std::string HpackVarintDecoder::DebugString() const {
return absl::StrCat("HpackVarintDecoder(value=", value_, ", offset=", offset_,
")");
}
DecodeStatus HpackVarintDecoder::StartForTest(uint8_t prefix_value,
uint8_t prefix_length,
DecodeBuffer* db) {
return Start(prefix_value, prefix_length, db);
}
DecodeStatus HpackVarintDecoder::StartExtendedForTest(uint8_t prefix_length,
DecodeBuffer* db) {
return StartExtended(prefix_length, db);
}
DecodeStatus HpackVarintDecoder::ResumeForTest(DecodeBuffer* db) {
return Resume(db);
}
} | #include "quiche/http2/hpack/varint/hpack_varint_decoder.h"
#include <stddef.h>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include "absl/base/macros.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
namespace {
class HpackVarintDecoderTest
: public RandomDecoderTest,
public ::testing::WithParamInterface<std::tuple<uint8_t, const char*>> {
protected:
HpackVarintDecoderTest()
: high_bits_(std::get<0>(GetParam())), prefix_length_(0) {
QUICHE_CHECK(absl::HexStringToBytes(std::get<1>(GetParam()), &suffix_));
}
void DecodeExpectSuccess(absl::string_view data, uint32_t prefix_length,
uint64_t expected_value) {
Validator validator = [expected_value, this](
const DecodeBuffer& ,
DecodeStatus ) -> AssertionResult {
HTTP2_VERIFY_EQ(expected_value, decoder_.value())
<< "Value doesn't match expected: " << decoder_.value()
<< " != " << expected_value;
return AssertionSuccess();
};
validator =
ValidateDoneAndOffset( data.size(), std::move(validator));
EXPECT_TRUE(Decode(data, prefix_length, std::move(validator)));
EXPECT_EQ(expected_value, decoder_.value());
}
void DecodeExpectError(absl::string_view data, uint32_t prefix_length) {
Validator validator = [](const DecodeBuffer& ,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(DecodeStatus::kDecodeError, status);
return AssertionSuccess();
};
EXPECT_TRUE(Decode(data, prefix_length, std::move(validator)));
}
private:
AssertionResult Decode(absl::string_view data, uint32_t prefix_length,
const Validator validator) {
prefix_length_ = prefix_length;
std::string data_copy(data);
uint8_t high_bits_mask = 0b11111111 << prefix_length_;
data_copy[0] |= (high_bits_mask & high_bits_);
data_copy.append(suffix_);
DecodeBuffer b(data_copy);
bool return_non_zero_on_first = true;
return DecodeAndValidateSeveralWays(&b, return_non_zero_on_first,
validator);
}
DecodeStatus StartDecoding(DecodeBuffer* b) override {
QUICHE_CHECK_LT(0u, b->Remaining());
uint8_t prefix = b->DecodeUInt8();
return decoder_.Start(prefix, prefix_length_, b);
}
DecodeStatus ResumeDecoding(DecodeBuffer* b) override {
return decoder_.Resume(b);
}
const uint8_t high_bits_;
std::string suffix_;
HpackVarintDecoder decoder_;
uint8_t prefix_length_;
};
INSTANTIATE_TEST_SUITE_P(
HpackVarintDecoderTest, HpackVarintDecoderTest,
::testing::Combine(
::testing::Values(0b00000000, 0b11111111, 0b10101010),
::testing::Values("", "00", "666f6f")));
struct {
const char* data;
uint32_t prefix_length;
uint64_t expected_value;
} kSuccessTestData[] = {
{"00", 3, 0},
{"00", 4, 0},
{"00", 5, 0},
{"00", 6, 0},
{"00", 7, 0},
{"00", 8, 0},
{"06", 3, 6},
{"0d", 4, 13},
{"10", 5, 16},
{"29", 6, 41},
{"56", 7, 86},
{"bf", 8, 191},
{"0700", 3, 7},
{"0f00", 4, 15},
{"1f00", 5, 31},
{"3f00", 6, 63},
{"7f00", 7, 127},
{"ff00", 8, 255},
{"078000", 3, 7},
{"0f8000", 4, 15},
{"1f8000", 5, 31},
{"3f8000", 6, 63},
{"7f8000", 7, 127},
{"ff8000", 8, 255},
{"0760", 3, 103},
{"0f2a", 4, 57},
{"1f7f", 5, 158},
{"3f02", 6, 65},
{"7f49", 7, 200},
{"ff6f", 8, 366},
{"07e000", 3, 103},
{"0faa00", 4, 57},
{"1fff00", 5, 158},
{"3f8200", 6, 65},
{"7fc900", 7, 200},
{"ffef00", 8, 366},
{"07e08000", 3, 103},
{"0faa8000", 4, 57},
{"1fff8000", 5, 158},
{"3f828000", 6, 65},
{"7fc98000", 7, 200},
{"ffef8000", 8, 366},
{"07e0808080808080808000", 3, 103},
{"0faa808080808080808000", 4, 57},
{"1fff808080808080808000", 5, 158},
{"3f82808080808080808000", 6, 65},
{"7fc9808080808080808000", 7, 200},
{"ffef808080808080808000", 8, 366},
{"07b260", 3, 12345},
{"0f8a2a", 4, 5401},
{"1fa87f", 5, 16327},
{"3fd002", 6, 399},
{"7fff49", 7, 9598},
{"ffe32f", 8, 6370},
{"07b2e000", 3, 12345},
{"0f8aaa00", 4, 5401},
{"1fa8ff00", 5, 16327},
{"3fd08200", 6, 399},
{"7fffc900", 7, 9598},
{"ffe3af00", 8, 6370},
{"07b2e080808080808000", 3, 12345},
{"0f8aaa80808080808000", 4, 5401},
{"1fa8ff80808080808000", 5, 16327},
{"3fd08280808080808000", 6, 399},
{"7fffc980808080808000", 7, 9598},
{"ffe3af80808080808000", 8, 6370},
{"078ab260", 3, 1579281},
{"0fc18a2a", 4, 689488},
{"1fada87f", 5, 2085964},
{"3fa0d002", 6, 43103},
{"7ffeff49", 7, 1212541},
{"ff93de23", 8, 585746},
{"078ab2e000", 3, 1579281},
{"0fc18aaa00", 4, 689488},
{"1fada8ff00", 5, 2085964},
{"3fa0d08200", 6, 43103},
{"7ffeffc900", 7, 1212541},
{"ff93dea300", 8, 585746},
{"079f8ab260", 3, 202147110},
{"0fa2c18a2a", 4, 88252593},
{"1fd0ada87f", 5, 266999535},
{"3ff9a0d002", 6, 5509304},
{"7f9efeff49", 7, 155189149},
{"ffaa82f404", 8, 10289705},
{"079f8ab2e000", 3, 202147110},
{"0fa2c18aaa00", 4, 88252593},
{"1fd0ada8ff00", 5, 266999535},
{"3ff9a0d08200", 6, 5509304},
{"7f9efeffc900", 7, 155189149},
{"ffaa82f48400", 8, 10289705},
{"0783aa9f8ab260", 3, 3311978140938},
{"0ff0b0a2c18a2a", 4, 1445930244223},
{"1fda84d0ada87f", 5, 4374519874169},
{"3fb5fbf9a0d002", 6, 90263420404},
{"7fcff19efeff49", 7, 2542616951118},
{"ff9fa486bbc327", 8, 1358138807070},
{"07f19883aa9f8ab260", 3, 54263449861016696},
{"0f84fdf0b0a2c18a2a", 4, 23690121121119891},
{"1fa0dfda84d0ada87f", 5, 71672133617889215},
{"3f9ff0b5fbf9a0d002", 6, 1478875878881374},
{"7ffbc1cff19efeff49", 7, 41658236125045114},
{"ff91b6fb85af99c342", 8, 37450237664484368},
{"0794f1f19883aa9f8ab201", 3, 12832019021693745307u},
{"0fa08f84fdf0b0a2c18a01", 4, 9980690937382242223u},
{"1fbfdda0dfda84d0ada801", 5, 12131360551794650846u},
{"3f9dc79ff0b5fbf9a0d001", 6, 15006530362736632796u},
{"7f8790fbc1cff19efeff01", 7, 18445754019193211014u},
{"fffba8c5b8d3fe9f8c8401", 8, 9518498503615141242u},
{"07f8ffffffffffffffff01", 3, 18446744073709551615u},
{"0ff0ffffffffffffffff01", 4, 18446744073709551615u},
{"1fe0ffffffffffffffff01", 5, 18446744073709551615u},
{"3fc0ffffffffffffffff01", 6, 18446744073709551615u},
{"7f80ffffffffffffffff01", 7, 18446744073709551615u},
{"ff80feffffffffffffff01", 8, 18446744073709551615u},
{"0a", 5, 10},
{"1f9a0a", 5, 1337},
};
TEST_P(HpackVarintDecoderTest, Success) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kSuccessTestData); ++i) {
std::string data_bytes;
ASSERT_TRUE(absl::HexStringToBytes(kSuccessTestData[i].data, &data_bytes));
DecodeExpectSuccess(data_bytes, kSuccessTestData[i].prefix_length,
kSuccessTestData[i].expected_value);
}
}
struct {
const char* data;
uint32_t prefix_length;
} kErrorTestData[] = {
{"0780808080808080808080", 3},
{"0f80808080808080808080", 4},
{"1f80808080808080808080", 5},
{"3f80808080808080808080", 6},
{"7f80808080808080808080", 7},
{"ff80808080808080808080", 8},
{"07ffffffffffffffffffff", 3},
{"0fffffffffffffffffffff", 4},
{"1fffffffffffffffffffff", 5},
{"3fffffffffffffffffffff", 6},
{"7fffffffffffffffffffff", 7},
{"ffffffffffffffffffffff", 8},
{"07f9ffffffffffffffff01", 3},
{"0ff1ffffffffffffffff01", 4},
{"1fe1ffffffffffffffff01", 5},
{"3fc1ffffffffffffffff01", 6},
{"7f81ffffffffffffffff01", 7},
{"ff81feffffffffffffff01", 8},
{"07f8ffffffffffffffff8100", 3},
{"0ff0ffffffffffffffff8100", 4},
{"1fe0ffffffffffffffff8100", 5},
{"3fc0ffffffffffffffff8100", 6},
{"7f80ffffffffffffffff8100", 7},
{"ff80feffffffffffffff8100", 8}};
TEST_P(HpackVarintDecoderTest, Error) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kErrorTestData); ++i) {
std::string data_bytes;
ASSERT_TRUE(absl::HexStringToBytes(kErrorTestData[i].data, &data_bytes));
DecodeExpectError(data_bytes, kErrorTestData[i].prefix_length);
}
}
}
}
} |
444 | cpp | google/quiche | hpack_varint_encoder | quiche/http2/hpack/varint/hpack_varint_encoder.cc | quiche/http2/hpack/varint/hpack_varint_encoder_test.cc | #ifndef QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_ENCODER_H_
#define QUICHE_HTTP2_HPACK_VARINT_HPACK_VARINT_ENCODER_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
class QUICHE_EXPORT HpackVarintEncoder {
public:
static void Encode(uint8_t high_bits, uint8_t prefix_length, uint64_t varint,
std::string* output);
};
}
#endif
#include "quiche/http2/hpack/varint/hpack_varint_encoder.h"
#include <limits>
#include <string>
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
void HpackVarintEncoder::Encode(uint8_t high_bits, uint8_t prefix_length,
uint64_t varint, std::string* output) {
QUICHE_DCHECK_LE(1u, prefix_length);
QUICHE_DCHECK_LE(prefix_length, 8u);
const uint8_t prefix_mask = (1 << prefix_length) - 1;
QUICHE_DCHECK_EQ(0, high_bits & prefix_mask);
if (varint < prefix_mask) {
unsigned char first_byte = high_bits | static_cast<unsigned char>(varint);
output->push_back(first_byte);
return;
}
unsigned char first_byte = high_bits | prefix_mask;
output->push_back(first_byte);
varint -= prefix_mask;
while (varint >= 128) {
output->push_back(0b10000000 | (varint % 128));
varint >>= 7;
}
output->push_back(varint);
}
} | #include "quiche/http2/hpack/varint/hpack_varint_encoder.h"
#include <cstddef>
#include <string>
#include "absl/base/macros.h"
#include "absl/strings/escaping.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
struct {
uint8_t high_bits;
uint8_t prefix_length;
uint64_t value;
uint8_t expected_encoding;
} kShortTestData[] = {{0b10110010, 1, 0, 0b10110010},
{0b10101100, 2, 2, 0b10101110},
{0b10100000, 3, 6, 0b10100110},
{0b10110000, 4, 13, 0b10111101},
{0b10100000, 5, 8, 0b10101000},
{0b11000000, 6, 48, 0b11110000},
{0b10000000, 7, 99, 0b11100011},
{0b00000000, 5, 10, 0b00001010}};
TEST(HpackVarintEncoderTest, Short) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kShortTestData); ++i) {
std::string output;
HpackVarintEncoder::Encode(kShortTestData[i].high_bits,
kShortTestData[i].prefix_length,
kShortTestData[i].value, &output);
ASSERT_EQ(1u, output.size());
EXPECT_EQ(kShortTestData[i].expected_encoding,
static_cast<uint8_t>(output[0]));
}
}
struct {
uint8_t high_bits;
uint8_t prefix_length;
uint64_t value;
const char* expected_encoding;
} kLongTestData[] = {
{0b10011000, 3, 103, "9f60"},
{0b10010000, 4, 57, "9f2a"},
{0b11000000, 5, 158, "df7f"},
{0b01000000, 6, 65, "7f02"},
{0b00000000, 7, 200, "7f49"},
{0b10011000, 3, 12345, "9fb260"},
{0b10010000, 4, 5401, "9f8a2a"},
{0b11000000, 5, 16327, "dfa87f"},
{0b01000000, 6, 399, "7fd002"},
{0b00000000, 7, 9598, "7fff49"},
{0b10011000, 3, 1579281, "9f8ab260"},
{0b10010000, 4, 689488, "9fc18a2a"},
{0b11000000, 5, 2085964, "dfada87f"},
{0b01000000, 6, 43103, "7fa0d002"},
{0b00000000, 7, 1212541, "7ffeff49"},
{0b10011000, 3, 202147110, "9f9f8ab260"},
{0b10010000, 4, 88252593, "9fa2c18a2a"},
{0b11000000, 5, 266999535, "dfd0ada87f"},
{0b01000000, 6, 5509304, "7ff9a0d002"},
{0b00000000, 7, 155189149, "7f9efeff49"},
{0b10011000, 3, 3311978140938, "9f83aa9f8ab260"},
{0b10010000, 4, 1445930244223, "9ff0b0a2c18a2a"},
{0b11000000, 5, 4374519874169, "dfda84d0ada87f"},
{0b01000000, 6, 90263420404, "7fb5fbf9a0d002"},
{0b00000000, 7, 2542616951118, "7fcff19efeff49"},
{0b10011000, 3, 54263449861016696, "9ff19883aa9f8ab260"},
{0b10010000, 4, 23690121121119891, "9f84fdf0b0a2c18a2a"},
{0b11000000, 5, 71672133617889215, "dfa0dfda84d0ada87f"},
{0b01000000, 6, 1478875878881374, "7f9ff0b5fbf9a0d002"},
{0b00000000, 7, 41658236125045114, "7ffbc1cff19efeff49"},
{0b10011000, 3, 12832019021693745307u, "9f94f1f19883aa9f8ab201"},
{0b10010000, 4, 9980690937382242223u, "9fa08f84fdf0b0a2c18a01"},
{0b11000000, 5, 12131360551794650846u, "dfbfdda0dfda84d0ada801"},
{0b01000000, 6, 15006530362736632796u, "7f9dc79ff0b5fbf9a0d001"},
{0b00000000, 7, 18445754019193211014u, "7f8790fbc1cff19efeff01"},
{0b10011000, 3, 18446744073709551615u, "9ff8ffffffffffffffff01"},
{0b10010000, 4, 18446744073709551615u, "9ff0ffffffffffffffff01"},
{0b11000000, 5, 18446744073709551615u, "dfe0ffffffffffffffff01"},
{0b01000000, 6, 18446744073709551615u, "7fc0ffffffffffffffff01"},
{0b00000000, 7, 18446744073709551615u, "7f80ffffffffffffffff01"},
{0b00000000, 5, 1337, "1f9a0a"},
};
TEST(HpackVarintEncoderTest, Long) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kLongTestData); ++i) {
std::string expected_encoding;
ASSERT_TRUE(absl::HexStringToBytes(kLongTestData[i].expected_encoding,
&expected_encoding));
std::string output;
HpackVarintEncoder::Encode(kLongTestData[i].high_bits,
kLongTestData[i].prefix_length,
kLongTestData[i].value, &output);
EXPECT_EQ(expected_encoding, output);
}
}
struct {
uint8_t high_bits;
uint8_t prefix_length;
uint64_t value;
uint8_t expected_encoding_first_byte;
} kLastByteIsZeroTestData[] = {
{0b10110010, 1, 1, 0b10110011}, {0b10101100, 2, 3, 0b10101111},
{0b10101000, 3, 7, 0b10101111}, {0b10110000, 4, 15, 0b10111111},
{0b10100000, 5, 31, 0b10111111}, {0b11000000, 6, 63, 0b11111111},
{0b10000000, 7, 127, 0b11111111}, {0b00000000, 8, 255, 0b11111111}};
TEST(HpackVarintEncoderTest, LastByteIsZero) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kLastByteIsZeroTestData); ++i) {
std::string output;
HpackVarintEncoder::Encode(kLastByteIsZeroTestData[i].high_bits,
kLastByteIsZeroTestData[i].prefix_length,
kLastByteIsZeroTestData[i].value, &output);
ASSERT_EQ(2u, output.size());
EXPECT_EQ(kLastByteIsZeroTestData[i].expected_encoding_first_byte,
static_cast<uint8_t>(output[0]));
EXPECT_EQ(0b00000000, output[1]);
}
}
TEST(HpackVarintEncoderTest, Append) {
std::string output("foo");
std::string expected_encoding;
ASSERT_TRUE(absl::HexStringToBytes("666f6f", &expected_encoding));
EXPECT_EQ(expected_encoding, output);
HpackVarintEncoder::Encode(0b10011000, 3, 103, &output);
ASSERT_TRUE(absl::HexStringToBytes("666f6f9f60", &expected_encoding));
EXPECT_EQ(expected_encoding, output);
HpackVarintEncoder::Encode(0b10100000, 5, 8, &output);
ASSERT_TRUE(absl::HexStringToBytes("666f6f9f60a8", &expected_encoding));
EXPECT_EQ(expected_encoding, output);
HpackVarintEncoder::Encode(0b10011000, 3, 202147110, &output);
ASSERT_TRUE(
absl::HexStringToBytes("666f6f9f60a89f9f8ab260", &expected_encoding));
EXPECT_EQ(expected_encoding, output);
}
}
}
} |
445 | cpp | google/quiche | hpack_example | quiche/http2/test_tools/hpack_example.cc | quiche/http2/test_tools/hpack_example_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_EXAMPLE_H_
#define QUICHE_HTTP2_TEST_TOOLS_HPACK_EXAMPLE_H_
#include <string>
#include "absl/strings/string_view.h"
namespace http2 {
namespace test {
std::string HpackExampleToStringOrDie(absl::string_view example);
}
}
#endif
#include "quiche/http2/test_tools/hpack_example.h"
#include <ctype.h>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace http2 {
namespace test {
namespace {
void HpackExampleToStringOrDie(absl::string_view example, std::string* output) {
while (!example.empty()) {
const char c0 = example[0];
if (isxdigit(c0)) {
QUICHE_CHECK_GT(example.size(), 1u) << "Truncated hex byte?";
const char c1 = example[1];
QUICHE_CHECK(isxdigit(c1)) << "Found half a byte?";
std::string byte;
QUICHE_CHECK(absl::HexStringToBytes(example.substr(0, 2), &byte))
<< "Can't parse hex byte";
absl::StrAppend(output, byte);
example.remove_prefix(2);
continue;
}
if (isspace(c0)) {
example.remove_prefix(1);
continue;
}
if (!example.empty() && example[0] == '|') {
auto pos = example.find('\n');
if (pos == absl::string_view::npos) {
break;
}
example.remove_prefix(pos + 1);
continue;
}
QUICHE_BUG(http2_bug_107_1)
<< "Can't parse byte " << static_cast<int>(c0)
<< absl::StrCat(" (0x", absl::Hex(c0), ")") << "\nExample: " << example;
}
QUICHE_CHECK_LT(0u, output->size()) << "Example is empty.";
}
}
std::string HpackExampleToStringOrDie(absl::string_view example) {
std::string output;
HpackExampleToStringOrDie(example, &output);
return output;
}
}
} | #include "quiche/http2/test_tools/hpack_example.h"
#include <string>
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
TEST(HpackExampleToStringOrDie, GoodInput) {
std::string bytes = HpackExampleToStringOrDie(R"(
40 | == Literal never indexed ==
| Blank lines are OK in example:
08 | Literal name (len = 8)
7061 7373 776f 7264 | password
06 | Literal value (len = 6)
7365 6372 6574 | secret
| -> password: secret
)");
const char kExpected[] = {
0x40,
0x08,
0x70, 0x61, 0x73, 0x73,
0x77, 0x6f, 0x72, 0x64,
0x06,
0x73, 0x65, 0x63, 0x72,
0x65, 0x74,
};
EXPECT_EQ(absl::string_view(kExpected, sizeof kExpected), bytes);
}
#ifdef GTEST_HAS_DEATH_TEST
TEST(HpackExampleToStringOrDie, InvalidInput) {
EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie("4"), "Truncated");
EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie("4x"), "half");
EXPECT_QUICHE_DEATH(HpackExampleToStringOrDie(""), "empty");
}
#endif
}
}
} |
446 | cpp | google/quiche | hpack_block_collector | quiche/http2/test_tools/hpack_block_collector.cc | quiche/http2/hpack/decoder/hpack_block_collector_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_COLLECTOR_H_
#define QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_COLLECTOR_H_
#include <stddef.h>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_entry_collector.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class QUICHE_NO_EXPORT HpackBlockCollector : public HpackEntryDecoderListener {
public:
HpackBlockCollector();
HpackBlockCollector(const HpackBlockCollector& other);
~HpackBlockCollector() override;
void OnIndexedHeader(size_t index) override;
void OnDynamicTableSizeUpdate(size_t size) override;
void OnStartLiteralHeader(HpackEntryType header_type,
size_t maybe_name_index) override;
void OnNameStart(bool huffman_encoded, size_t len) override;
void OnNameData(const char* data, size_t len) override;
void OnNameEnd() override;
void OnValueStart(bool huffman_encoded, size_t len) override;
void OnValueData(const char* data, size_t len) override;
void OnValueEnd() override;
void ExpectIndexedHeader(size_t index);
void ExpectDynamicTableSizeUpdate(size_t size);
void ExpectNameIndexAndLiteralValue(HpackEntryType type, size_t index,
bool value_huffman,
const std::string& value);
void ExpectLiteralNameAndValue(HpackEntryType type, bool name_huffman,
const std::string& name, bool value_huffman,
const std::string& value);
void ShuffleEntries(Http2Random* rng);
void AppendToHpackBlockBuilder(HpackBlockBuilder* hbb) const;
::testing::AssertionResult ValidateSoleIndexedHeader(size_t ndx) const;
::testing::AssertionResult ValidateSoleDynamicTableSizeUpdate(
size_t size) const;
::testing::AssertionResult ValidateSoleLiteralValueHeader(
HpackEntryType expected_type, size_t expected_index,
bool expected_value_huffman, absl::string_view expected_value) const;
::testing::AssertionResult ValidateSoleLiteralNameValueHeader(
HpackEntryType expected_type, bool expected_name_huffman,
absl::string_view expected_name, bool expected_value_huffman,
absl::string_view expected_value) const;
bool IsNotPending() const { return pending_entry_.IsClear(); }
bool IsClear() const { return IsNotPending() && entries_.empty(); }
void Clear();
::testing::AssertionResult VerifyEq(const HpackBlockCollector& that) const;
private:
void PushPendingEntry();
HpackEntryCollector pending_entry_;
std::vector<HpackEntryCollector> entries_;
};
}
}
#endif
#include "quiche/http2/test_tools/hpack_block_collector.h"
#include <algorithm>
#include <memory>
#include <string>
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
using ::testing::AssertionResult;
using ::testing::AssertionSuccess;
namespace http2 {
namespace test {
HpackBlockCollector::HpackBlockCollector() = default;
HpackBlockCollector::HpackBlockCollector(const HpackBlockCollector& other)
: pending_entry_(other.pending_entry_), entries_(other.entries_) {}
HpackBlockCollector::~HpackBlockCollector() = default;
void HpackBlockCollector::OnIndexedHeader(size_t index) {
pending_entry_.OnIndexedHeader(index);
PushPendingEntry();
}
void HpackBlockCollector::OnDynamicTableSizeUpdate(size_t size) {
pending_entry_.OnDynamicTableSizeUpdate(size);
PushPendingEntry();
}
void HpackBlockCollector::OnStartLiteralHeader(HpackEntryType header_type,
size_t maybe_name_index) {
pending_entry_.OnStartLiteralHeader(header_type, maybe_name_index);
}
void HpackBlockCollector::OnNameStart(bool huffman_encoded, size_t len) {
pending_entry_.OnNameStart(huffman_encoded, len);
}
void HpackBlockCollector::OnNameData(const char* data, size_t len) {
pending_entry_.OnNameData(data, len);
}
void HpackBlockCollector::OnNameEnd() { pending_entry_.OnNameEnd(); }
void HpackBlockCollector::OnValueStart(bool huffman_encoded, size_t len) {
pending_entry_.OnValueStart(huffman_encoded, len);
}
void HpackBlockCollector::OnValueData(const char* data, size_t len) {
pending_entry_.OnValueData(data, len);
}
void HpackBlockCollector::OnValueEnd() {
pending_entry_.OnValueEnd();
PushPendingEntry();
}
void HpackBlockCollector::PushPendingEntry() {
EXPECT_TRUE(pending_entry_.IsComplete());
QUICHE_DVLOG(2) << "PushPendingEntry: " << pending_entry_;
entries_.push_back(pending_entry_);
EXPECT_TRUE(entries_.back().IsComplete());
pending_entry_.Clear();
}
void HpackBlockCollector::Clear() {
pending_entry_.Clear();
entries_.clear();
}
void HpackBlockCollector::ExpectIndexedHeader(size_t index) {
entries_.push_back(
HpackEntryCollector(HpackEntryType::kIndexedHeader, index));
}
void HpackBlockCollector::ExpectDynamicTableSizeUpdate(size_t size) {
entries_.push_back(
HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, size));
}
void HpackBlockCollector::ExpectNameIndexAndLiteralValue(
HpackEntryType type, size_t index, bool value_huffman,
const std::string& value) {
entries_.push_back(HpackEntryCollector(type, index, value_huffman, value));
}
void HpackBlockCollector::ExpectLiteralNameAndValue(HpackEntryType type,
bool name_huffman,
const std::string& name,
bool value_huffman,
const std::string& value) {
entries_.push_back(
HpackEntryCollector(type, name_huffman, name, value_huffman, value));
}
void HpackBlockCollector::ShuffleEntries(Http2Random* rng) {
std::shuffle(entries_.begin(), entries_.end(), *rng);
}
void HpackBlockCollector::AppendToHpackBlockBuilder(
HpackBlockBuilder* hbb) const {
QUICHE_CHECK(IsNotPending());
for (const auto& entry : entries_) {
entry.AppendToHpackBlockBuilder(hbb);
}
}
AssertionResult HpackBlockCollector::ValidateSoleIndexedHeader(
size_t ndx) const {
HTTP2_VERIFY_TRUE(pending_entry_.IsClear());
HTTP2_VERIFY_EQ(1u, entries_.size());
HTTP2_VERIFY_TRUE(entries_.front().ValidateIndexedHeader(ndx));
return AssertionSuccess();
}
AssertionResult HpackBlockCollector::ValidateSoleLiteralValueHeader(
HpackEntryType expected_type, size_t expected_index,
bool expected_value_huffman, absl::string_view expected_value) const {
HTTP2_VERIFY_TRUE(pending_entry_.IsClear());
HTTP2_VERIFY_EQ(1u, entries_.size());
HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralValueHeader(
expected_type, expected_index, expected_value_huffman, expected_value));
return AssertionSuccess();
}
AssertionResult HpackBlockCollector::ValidateSoleLiteralNameValueHeader(
HpackEntryType expected_type, bool expected_name_huffman,
absl::string_view expected_name, bool expected_value_huffman,
absl::string_view expected_value) const {
HTTP2_VERIFY_TRUE(pending_entry_.IsClear());
HTTP2_VERIFY_EQ(1u, entries_.size());
HTTP2_VERIFY_TRUE(entries_.front().ValidateLiteralNameValueHeader(
expected_type, expected_name_huffman, expected_name,
expected_value_huffman, expected_value));
return AssertionSuccess();
}
AssertionResult HpackBlockCollector::ValidateSoleDynamicTableSizeUpdate(
size_t size) const {
HTTP2_VERIFY_TRUE(pending_entry_.IsClear());
HTTP2_VERIFY_EQ(1u, entries_.size());
HTTP2_VERIFY_TRUE(entries_.front().ValidateDynamicTableSizeUpdate(size));
return AssertionSuccess();
}
AssertionResult HpackBlockCollector::VerifyEq(
const HpackBlockCollector& that) const {
HTTP2_VERIFY_EQ(pending_entry_, that.pending_entry_);
HTTP2_VERIFY_EQ(entries_, that.entries_);
return AssertionSuccess();
}
}
} | #include "quiche/http2/test_tools/hpack_block_collector.h"
#include <string>
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
TEST(HpackBlockCollectorTest, Clear) {
HpackBlockCollector collector;
EXPECT_TRUE(collector.IsClear());
EXPECT_TRUE(collector.IsNotPending());
collector.OnIndexedHeader(234);
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsNotPending());
collector.Clear();
EXPECT_TRUE(collector.IsClear());
EXPECT_TRUE(collector.IsNotPending());
collector.OnDynamicTableSizeUpdate(0);
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsNotPending());
collector.Clear();
collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);
EXPECT_FALSE(collector.IsClear());
EXPECT_FALSE(collector.IsNotPending());
}
TEST(HpackBlockCollectorTest, IndexedHeader) {
HpackBlockCollector a;
a.OnIndexedHeader(123);
EXPECT_TRUE(a.ValidateSoleIndexedHeader(123));
HpackBlockCollector b;
EXPECT_FALSE(a.VerifyEq(b));
b.OnIndexedHeader(1);
EXPECT_TRUE(b.ValidateSoleIndexedHeader(1));
EXPECT_FALSE(a.VerifyEq(b));
b.Clear();
b.OnIndexedHeader(123);
EXPECT_TRUE(a.VerifyEq(b));
b.OnIndexedHeader(234);
EXPECT_FALSE(b.VerifyEq(a));
a.OnIndexedHeader(234);
EXPECT_TRUE(b.VerifyEq(a));
std::string expected;
{
HpackBlockBuilder hbb;
hbb.AppendIndexedHeader(123);
hbb.AppendIndexedHeader(234);
EXPECT_EQ(3u, hbb.size());
expected = hbb.buffer();
}
std::string actual;
{
HpackBlockBuilder hbb;
a.AppendToHpackBlockBuilder(&hbb);
EXPECT_EQ(3u, hbb.size());
actual = hbb.buffer();
}
EXPECT_EQ(expected, actual);
}
TEST(HpackBlockCollectorTest, DynamicTableSizeUpdate) {
HpackBlockCollector a;
a.OnDynamicTableSizeUpdate(0);
EXPECT_TRUE(a.ValidateSoleDynamicTableSizeUpdate(0));
HpackBlockCollector b;
EXPECT_FALSE(a.VerifyEq(b));
b.OnDynamicTableSizeUpdate(1);
EXPECT_TRUE(b.ValidateSoleDynamicTableSizeUpdate(1));
EXPECT_FALSE(a.VerifyEq(b));
b.Clear();
b.OnDynamicTableSizeUpdate(0);
EXPECT_TRUE(a.VerifyEq(b));
b.OnDynamicTableSizeUpdate(4096);
EXPECT_FALSE(b.VerifyEq(a));
a.OnDynamicTableSizeUpdate(4096);
EXPECT_TRUE(b.VerifyEq(a));
std::string expected;
{
HpackBlockBuilder hbb;
hbb.AppendDynamicTableSizeUpdate(0);
hbb.AppendDynamicTableSizeUpdate(4096);
EXPECT_EQ(4u, hbb.size());
expected = hbb.buffer();
}
std::string actual;
{
HpackBlockBuilder hbb;
a.AppendToHpackBlockBuilder(&hbb);
EXPECT_EQ(4u, hbb.size());
actual = hbb.buffer();
}
EXPECT_EQ(expected, actual);
}
}
}
} |
447 | cpp | google/quiche | http2_random | quiche/http2/test_tools/http2_random.cc | quiche/http2/test_tools/http2_random_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HTTP2_RANDOM_H_
#define QUICHE_HTTP2_TEST_TOOLS_HTTP2_RANDOM_H_
#include <cmath>
#include <cstdint>
#include <limits>
#include <random>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class QUICHE_NO_EXPORT Http2Random {
public:
Http2Random();
Http2Random(const Http2Random&) = delete;
Http2Random& operator=(const Http2Random&) = delete;
explicit Http2Random(absl::string_view key);
std::string Key() const;
void FillRandom(void* buffer, size_t buffer_size);
std::string RandString(int length);
uint64_t Rand64();
uint32_t Uniform(uint32_t n) { return Rand64() % n; }
uint64_t UniformInRange(uint64_t lo, uint64_t hi) {
return lo + Rand64() % (hi - lo);
}
uint32_t Skewed(uint32_t max_log) {
const uint32_t base = Rand32() % (max_log + 1);
const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u;
return Rand32() & mask;
}
uint64_t RandomSizeSkewedLow(uint64_t max) {
return std::round(max * std::pow(RandDouble(), 2));
}
double RandDouble();
float RandFloat() { return RandDouble(); }
bool OneIn(int n) { return Uniform(n) == 0; }
uint8_t Rand8() { return Rand64(); }
uint16_t Rand16() { return Rand64(); }
uint32_t Rand32() { return Rand64(); }
std::string RandStringWithAlphabet(int length, absl::string_view alphabet);
using result_type = uint64_t;
static constexpr result_type min() { return 0; }
static constexpr result_type max() {
return std::numeric_limits<result_type>::max();
}
result_type operator()() { return Rand64(); }
private:
uint8_t key_[32];
uint32_t counter_ = 0;
};
}
}
#endif
#include "quiche/http2/test_tools/http2_random.h"
#include <string>
#include "absl/strings/escaping.h"
#include "openssl/chacha.h"
#include "openssl/rand.h"
#include "quiche/common/platform/api/quiche_logging.h"
static const uint8_t kZeroNonce[12] = {0};
namespace http2 {
namespace test {
Http2Random::Http2Random() {
RAND_bytes(key_, sizeof(key_));
QUICHE_LOG(INFO) << "Initialized test RNG with the following key: " << Key();
}
Http2Random::Http2Random(absl::string_view key) {
std::string decoded_key = absl::HexStringToBytes(key);
QUICHE_CHECK_EQ(sizeof(key_), decoded_key.size());
memcpy(key_, decoded_key.data(), sizeof(key_));
}
std::string Http2Random::Key() const {
return absl::BytesToHexString(
absl::string_view(reinterpret_cast<const char*>(key_), sizeof(key_)));
}
void Http2Random::FillRandom(void* buffer, size_t buffer_size) {
memset(buffer, 0, buffer_size);
uint8_t* buffer_u8 = reinterpret_cast<uint8_t*>(buffer);
CRYPTO_chacha_20(buffer_u8, buffer_u8, buffer_size, key_, kZeroNonce,
counter_++);
}
std::string Http2Random::RandString(int length) {
std::string result;
result.resize(length);
FillRandom(&result[0], length);
return result;
}
uint64_t Http2Random::Rand64() {
union {
uint64_t number;
uint8_t bytes[sizeof(uint64_t)];
} result;
FillRandom(result.bytes, sizeof(result.bytes));
return result.number;
}
double Http2Random::RandDouble() {
union {
double f;
uint64_t i;
} value;
value.i = (1023ull << 52ull) | (Rand64() & 0xfffffffffffffu);
return value.f - 1.0;
}
std::string Http2Random::RandStringWithAlphabet(int length,
absl::string_view alphabet) {
std::string result;
result.resize(length);
for (int i = 0; i < length; i++) {
result[i] = alphabet[Uniform(alphabet.size())];
}
return result;
}
}
} | #include "quiche/http2/test_tools/http2_random.h"
#include <algorithm>
#include <set>
#include <string>
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
TEST(Http2RandomTest, ProducesDifferentNumbers) {
Http2Random random;
uint64_t value1 = random.Rand64();
uint64_t value2 = random.Rand64();
uint64_t value3 = random.Rand64();
EXPECT_NE(value1, value2);
EXPECT_NE(value2, value3);
EXPECT_NE(value3, value1);
}
TEST(Http2RandomTest, StartsWithDifferentKeys) {
Http2Random random1;
Http2Random random2;
EXPECT_NE(random1.Key(), random2.Key());
EXPECT_NE(random1.Rand64(), random2.Rand64());
EXPECT_NE(random1.Rand64(), random2.Rand64());
EXPECT_NE(random1.Rand64(), random2.Rand64());
}
TEST(Http2RandomTest, ReproducibleRandom) {
Http2Random random;
uint64_t value1 = random.Rand64();
uint64_t value2 = random.Rand64();
Http2Random clone_random(random.Key());
EXPECT_EQ(clone_random.Key(), random.Key());
EXPECT_EQ(value1, clone_random.Rand64());
EXPECT_EQ(value2, clone_random.Rand64());
}
TEST(Http2RandomTest, STLShuffle) {
Http2Random random;
const std::string original = "abcdefghijklmonpqrsuvwxyz";
std::string shuffled = original;
std::shuffle(shuffled.begin(), shuffled.end(), random);
EXPECT_NE(original, shuffled);
}
TEST(Http2RandomTest, RandFloat) {
Http2Random random;
for (int i = 0; i < 10000; i++) {
float value = random.RandFloat();
ASSERT_GE(value, 0.f);
ASSERT_LE(value, 1.f);
}
}
TEST(Http2RandomTest, RandStringWithAlphabet) {
Http2Random random;
std::string str = random.RandStringWithAlphabet(1000, "xyz");
EXPECT_EQ(1000u, str.size());
std::set<char> characters(str.begin(), str.end());
EXPECT_THAT(characters, testing::ElementsAre('x', 'y', 'z'));
}
TEST(Http2RandomTest, SkewedLow) {
Http2Random random;
constexpr size_t kMax = 1234;
for (int i = 0; i < 10000; i++) {
size_t value = random.RandomSizeSkewedLow(kMax);
ASSERT_GE(value, 0u);
ASSERT_LE(value, kMax);
}
}
TEST(Http2RandomTest, SkewedLowFullRange) {
Http2Random random;
std::set<size_t> values;
for (int i = 0; i < 1000; i++) {
values.insert(random.RandomSizeSkewedLow(3));
}
EXPECT_THAT(values, testing::ElementsAre(0, 1, 2, 3));
}
}
}
} |
448 | cpp | google/quiche | hpack_entry_collector | quiche/http2/test_tools/hpack_entry_collector.cc | quiche/http2/hpack/decoder/hpack_entry_collector_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_ENTRY_COLLECTOR_H_
#define QUICHE_HTTP2_TEST_TOOLS_HPACK_ENTRY_COLLECTOR_H_
#include <stddef.h>
#include <iosfwd>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/decoder/hpack_entry_decoder_listener.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/test_tools/hpack_string_collector.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class QUICHE_NO_EXPORT HpackEntryCollector : public HpackEntryDecoderListener {
public:
HpackEntryCollector();
HpackEntryCollector(const HpackEntryCollector& other);
HpackEntryCollector(HpackEntryType type, size_t index_or_size);
HpackEntryCollector(HpackEntryType type, size_t index, bool value_huffman,
const std::string& value);
HpackEntryCollector(HpackEntryType type, bool name_huffman,
const std::string& name, bool value_huffman,
const std::string& value);
~HpackEntryCollector() override;
void OnIndexedHeader(size_t index) override;
void OnStartLiteralHeader(HpackEntryType header_type,
size_t maybe_name_index) override;
void OnNameStart(bool huffman_encoded, size_t len) override;
void OnNameData(const char* data, size_t len) override;
void OnNameEnd() override;
void OnValueStart(bool huffman_encoded, size_t len) override;
void OnValueData(const char* data, size_t len) override;
void OnValueEnd() override;
void OnDynamicTableSizeUpdate(size_t size) override;
void Clear();
bool IsClear() const;
bool IsComplete() const;
bool LiteralNameExpected() const;
bool LiteralValueExpected() const;
::testing::AssertionResult ValidateIndexedHeader(size_t expected_index) const;
::testing::AssertionResult ValidateLiteralValueHeader(
HpackEntryType expected_type, size_t expected_index,
bool expected_value_huffman, absl::string_view expected_value) const;
::testing::AssertionResult ValidateLiteralNameValueHeader(
HpackEntryType expected_type, bool expected_name_huffman,
absl::string_view expected_name, bool expected_value_huffman,
absl::string_view expected_value) const;
::testing::AssertionResult ValidateDynamicTableSizeUpdate(
size_t expected_size) const;
void set_header_type(HpackEntryType v) { header_type_ = v; }
HpackEntryType header_type() const { return header_type_; }
void set_index(size_t v) { index_ = v; }
size_t index() const { return index_; }
void set_name(const HpackStringCollector& v) { name_ = v; }
const HpackStringCollector& name() const { return name_; }
void set_value(const HpackStringCollector& v) { value_ = v; }
const HpackStringCollector& value() const { return value_; }
void set_started(bool v) { started_ = v; }
bool started() const { return started_; }
void set_ended(bool v) { ended_ = v; }
bool ended() const { return ended_; }
void AppendToHpackBlockBuilder(HpackBlockBuilder* hbb) const;
std::string ToString() const;
private:
void Init(HpackEntryType type, size_t maybe_index);
HpackEntryType header_type_;
size_t index_;
HpackStringCollector name_;
HpackStringCollector value_;
bool started_ = false;
bool ended_ = false;
};
QUICHE_NO_EXPORT bool operator==(const HpackEntryCollector& a,
const HpackEntryCollector& b);
QUICHE_NO_EXPORT bool operator!=(const HpackEntryCollector& a,
const HpackEntryCollector& b);
QUICHE_NO_EXPORT std::ostream& operator<<(std::ostream& out,
const HpackEntryCollector& v);
}
}
#endif
#include "quiche/http2/test_tools/hpack_entry_collector.h"
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/http2/test_tools/hpack_string_collector.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
namespace http2 {
namespace test {
namespace {
const HpackEntryType kInvalidHeaderType = static_cast<HpackEntryType>(99);
const size_t kInvalidIndex = 99999999;
}
HpackEntryCollector::HpackEntryCollector() { Clear(); }
HpackEntryCollector::HpackEntryCollector(const HpackEntryCollector& other) =
default;
HpackEntryCollector::HpackEntryCollector(HpackEntryType type,
size_t index_or_size)
: header_type_(type), index_(index_or_size), started_(true), ended_(true) {}
HpackEntryCollector::HpackEntryCollector(HpackEntryType type, size_t index,
bool value_huffman,
const std::string& value)
: header_type_(type),
index_(index),
value_(value, value_huffman),
started_(true),
ended_(true) {}
HpackEntryCollector::HpackEntryCollector(HpackEntryType type, bool name_huffman,
const std::string& name,
bool value_huffman,
const std::string& value)
: header_type_(type),
index_(0),
name_(name, name_huffman),
value_(value, value_huffman),
started_(true),
ended_(true) {}
HpackEntryCollector::~HpackEntryCollector() = default;
void HpackEntryCollector::OnIndexedHeader(size_t index) {
ASSERT_FALSE(started_);
ASSERT_TRUE(IsClear()) << ToString();
Init(HpackEntryType::kIndexedHeader, index);
ended_ = true;
}
void HpackEntryCollector::OnStartLiteralHeader(HpackEntryType header_type,
size_t maybe_name_index) {
ASSERT_FALSE(started_);
ASSERT_TRUE(IsClear()) << ToString();
Init(header_type, maybe_name_index);
}
void HpackEntryCollector::OnNameStart(bool huffman_encoded, size_t len) {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
ASSERT_FALSE(IsClear());
ASSERT_TRUE(LiteralNameExpected()) << ToString();
name_.OnStringStart(huffman_encoded, len);
}
void HpackEntryCollector::OnNameData(const char* data, size_t len) {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
ASSERT_TRUE(LiteralNameExpected()) << ToString();
ASSERT_TRUE(name_.IsInProgress());
name_.OnStringData(data, len);
}
void HpackEntryCollector::OnNameEnd() {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
ASSERT_TRUE(LiteralNameExpected()) << ToString();
ASSERT_TRUE(name_.IsInProgress());
name_.OnStringEnd();
}
void HpackEntryCollector::OnValueStart(bool huffman_encoded, size_t len) {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
if (LiteralNameExpected()) {
ASSERT_TRUE(name_.HasEnded());
}
ASSERT_TRUE(LiteralValueExpected()) << ToString();
ASSERT_TRUE(value_.IsClear()) << value_.ToString();
value_.OnStringStart(huffman_encoded, len);
}
void HpackEntryCollector::OnValueData(const char* data, size_t len) {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
ASSERT_TRUE(LiteralValueExpected()) << ToString();
ASSERT_TRUE(value_.IsInProgress());
value_.OnStringData(data, len);
}
void HpackEntryCollector::OnValueEnd() {
ASSERT_TRUE(started_);
ASSERT_FALSE(ended_);
ASSERT_TRUE(LiteralValueExpected()) << ToString();
ASSERT_TRUE(value_.IsInProgress());
value_.OnStringEnd();
ended_ = true;
}
void HpackEntryCollector::OnDynamicTableSizeUpdate(size_t size) {
ASSERT_FALSE(started_);
ASSERT_TRUE(IsClear()) << ToString();
Init(HpackEntryType::kDynamicTableSizeUpdate, size);
ended_ = true;
}
void HpackEntryCollector::Clear() {
header_type_ = kInvalidHeaderType;
index_ = kInvalidIndex;
name_.Clear();
value_.Clear();
started_ = ended_ = false;
}
bool HpackEntryCollector::IsClear() const {
return header_type_ == kInvalidHeaderType && index_ == kInvalidIndex &&
name_.IsClear() && value_.IsClear() && !started_ && !ended_;
}
bool HpackEntryCollector::IsComplete() const { return started_ && ended_; }
bool HpackEntryCollector::LiteralNameExpected() const {
switch (header_type_) {
case HpackEntryType::kIndexedLiteralHeader:
case HpackEntryType::kUnindexedLiteralHeader:
case HpackEntryType::kNeverIndexedLiteralHeader:
return index_ == 0;
default:
return false;
}
}
bool HpackEntryCollector::LiteralValueExpected() const {
switch (header_type_) {
case HpackEntryType::kIndexedLiteralHeader:
case HpackEntryType::kUnindexedLiteralHeader:
case HpackEntryType::kNeverIndexedLiteralHeader:
return true;
default:
return false;
}
}
AssertionResult HpackEntryCollector::ValidateIndexedHeader(
size_t expected_index) const {
HTTP2_VERIFY_TRUE(started_);
HTTP2_VERIFY_TRUE(ended_);
HTTP2_VERIFY_EQ(HpackEntryType::kIndexedHeader, header_type_);
HTTP2_VERIFY_EQ(expected_index, index_);
return ::testing::AssertionSuccess();
}
AssertionResult HpackEntryCollector::ValidateLiteralValueHeader(
HpackEntryType expected_type, size_t expected_index,
bool expected_value_huffman, absl::string_view expected_value) const {
HTTP2_VERIFY_TRUE(started_);
HTTP2_VERIFY_TRUE(ended_);
HTTP2_VERIFY_EQ(expected_type, header_type_);
HTTP2_VERIFY_NE(0u, expected_index);
HTTP2_VERIFY_EQ(expected_index, index_);
HTTP2_VERIFY_TRUE(name_.IsClear());
HTTP2_VERIFY_SUCCESS(
value_.Collected(expected_value, expected_value_huffman));
return ::testing::AssertionSuccess();
}
AssertionResult HpackEntryCollector::ValidateLiteralNameValueHeader(
HpackEntryType expected_type, bool expected_name_huffman,
absl::string_view expected_name, bool expected_value_huffman,
absl::string_view expected_value) const {
HTTP2_VERIFY_TRUE(started_);
HTTP2_VERIFY_TRUE(ended_);
HTTP2_VERIFY_EQ(expected_type, header_type_);
HTTP2_VERIFY_EQ(0u, index_);
HTTP2_VERIFY_SUCCESS(name_.Collected(expected_name, expected_name_huffman));
HTTP2_VERIFY_SUCCESS(
value_.Collected(expected_value, expected_value_huffman));
return ::testing::AssertionSuccess();
}
AssertionResult HpackEntryCollector::ValidateDynamicTableSizeUpdate(
size_t size) const {
HTTP2_VERIFY_TRUE(started_);
HTTP2_VERIFY_TRUE(ended_);
HTTP2_VERIFY_EQ(HpackEntryType::kDynamicTableSizeUpdate, header_type_);
HTTP2_VERIFY_EQ(index_, size);
return ::testing::AssertionSuccess();
}
void HpackEntryCollector::AppendToHpackBlockBuilder(
HpackBlockBuilder* hbb) const {
ASSERT_TRUE(started_ && ended_) << *this;
switch (header_type_) {
case HpackEntryType::kIndexedHeader:
hbb->AppendIndexedHeader(index_);
return;
case HpackEntryType::kDynamicTableSizeUpdate:
hbb->AppendDynamicTableSizeUpdate(index_);
return;
case HpackEntryType::kIndexedLiteralHeader:
case HpackEntryType::kUnindexedLiteralHeader:
case HpackEntryType::kNeverIndexedLiteralHeader:
ASSERT_TRUE(value_.HasEnded()) << *this;
if (index_ != 0) {
QUICHE_CHECK(name_.IsClear());
hbb->AppendNameIndexAndLiteralValue(header_type_, index_,
value_.huffman_encoded, value_.s);
} else {
QUICHE_CHECK(name_.HasEnded()) << *this;
hbb->AppendLiteralNameAndValue(header_type_, name_.huffman_encoded,
name_.s, value_.huffman_encoded,
value_.s);
}
return;
default:
ADD_FAILURE() << *this;
}
}
std::string HpackEntryCollector::ToString() const {
std::string result("Type=");
switch (header_type_) {
case HpackEntryType::kIndexedHeader:
result += "IndexedHeader";
break;
case HpackEntryType::kDynamicTableSizeUpdate:
result += "DynamicTableSizeUpdate";
break;
case HpackEntryType::kIndexedLiteralHeader:
result += "IndexedLiteralHeader";
break;
case HpackEntryType::kUnindexedLiteralHeader:
result += "UnindexedLiteralHeader";
break;
case HpackEntryType::kNeverIndexedLiteralHeader:
result += "NeverIndexedLiteralHeader";
break;
default:
if (header_type_ == kInvalidHeaderType) {
result += "<unset>";
} else {
absl::StrAppend(&result, header_type_);
}
}
if (index_ != 0) {
absl::StrAppend(&result, " Index=", index_);
}
if (!name_.IsClear()) {
absl::StrAppend(&result, " Name", name_.ToString());
}
if (!value_.IsClear()) {
absl::StrAppend(&result, " Value", value_.ToString());
}
if (!started_) {
EXPECT_FALSE(ended_);
absl::StrAppend(&result, " !started");
} else if (!ended_) {
absl::StrAppend(&result, " !ended");
} else {
absl::StrAppend(&result, " Complete");
}
return result;
}
void HpackEntryCollector::Init(HpackEntryType type, size_t maybe_index) {
ASSERT_TRUE(IsClear()) << ToString();
header_type_ = type;
index_ = maybe_index;
started_ = true;
}
bool operator==(const HpackEntryCollector& a, const HpackEntryCollector& b) {
return a.name() == b.name() && a.value() == b.value() &&
a.index() == b.index() && a.header_type() == b.header_type() &&
a.started() == b.started() && a.ended() == b.ended();
}
bool operator!=(const HpackEntryCollector& a, const HpackEntryCollector& b) {
return !(a == b);
}
std::ostream& operator<<(std::ostream& out, const HpackEntryCollector& v) {
return out << v.ToString();
}
}
} | #include "quiche/http2/test_tools/hpack_entry_collector.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::HasSubstr;
namespace http2 {
namespace test {
namespace {
TEST(HpackEntryCollectorTest, Clear) {
HpackEntryCollector collector;
QUICHE_VLOG(1) << collector;
EXPECT_THAT(collector.ToString(), HasSubstr("!started"));
EXPECT_TRUE(collector.IsClear());
collector.set_header_type(HpackEntryType::kIndexedLiteralHeader);
EXPECT_FALSE(collector.IsClear());
QUICHE_VLOG(1) << collector;
collector.Clear();
EXPECT_TRUE(collector.IsClear());
collector.set_index(123);
EXPECT_FALSE(collector.IsClear());
QUICHE_VLOG(1) << collector;
collector.Clear();
EXPECT_TRUE(collector.IsClear());
collector.set_name(HpackStringCollector("name", true));
EXPECT_FALSE(collector.IsClear());
QUICHE_VLOG(1) << collector;
collector.Clear();
EXPECT_TRUE(collector.IsClear());
collector.set_value(HpackStringCollector("value", false));
EXPECT_FALSE(collector.IsClear());
QUICHE_VLOG(1) << collector;
}
void IndexedHeaderErrorTest() {
HpackEntryCollector collector;
collector.OnIndexedHeader(1);
collector.OnIndexedHeader(234);
}
TEST(HpackEntryCollectorTest, IndexedHeader) {
HpackEntryCollector collector;
collector.OnIndexedHeader(123);
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsComplete());
EXPECT_TRUE(collector.ValidateIndexedHeader(123));
EXPECT_THAT(collector.ToString(), HasSubstr("IndexedHeader"));
EXPECT_THAT(collector.ToString(), HasSubstr("Complete"));
EXPECT_FATAL_FAILURE(IndexedHeaderErrorTest(), "Value of: started_");
}
void LiteralValueErrorTest() {
HpackEntryCollector collector;
collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 1);
collector.OnNameStart(false, 10);
}
TEST(HpackEntryCollectorTest, LiteralValueHeader) {
HpackEntryCollector collector;
collector.OnStartLiteralHeader(HpackEntryType::kIndexedLiteralHeader, 4);
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_FALSE(collector.IsComplete());
EXPECT_THAT(collector.ToString(), HasSubstr("!ended"));
collector.OnValueStart(true, 5);
QUICHE_VLOG(1) << collector;
collector.OnValueData("value", 5);
collector.OnValueEnd();
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsComplete());
EXPECT_TRUE(collector.ValidateLiteralValueHeader(
HpackEntryType::kIndexedLiteralHeader, 4, true, "value"));
EXPECT_THAT(collector.ToString(), HasSubstr("IndexedLiteralHeader"));
EXPECT_THAT(collector.ToString(), HasSubstr("Complete"));
EXPECT_FATAL_FAILURE(LiteralValueErrorTest(),
"Value of: LiteralNameExpected");
}
void LiteralNameValueHeaderErrorTest() {
HpackEntryCollector collector;
collector.OnStartLiteralHeader(HpackEntryType::kNeverIndexedLiteralHeader, 0);
collector.OnValueStart(false, 10);
}
TEST(HpackEntryCollectorTest, LiteralNameValueHeader) {
HpackEntryCollector collector;
collector.OnStartLiteralHeader(HpackEntryType::kUnindexedLiteralHeader, 0);
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_FALSE(collector.IsComplete());
collector.OnNameStart(false, 4);
collector.OnNameData("na", 2);
QUICHE_VLOG(1) << collector;
collector.OnNameData("me", 2);
collector.OnNameEnd();
collector.OnValueStart(true, 5);
QUICHE_VLOG(1) << collector;
collector.OnValueData("Value", 5);
collector.OnValueEnd();
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsComplete());
EXPECT_TRUE(collector.ValidateLiteralNameValueHeader(
HpackEntryType::kUnindexedLiteralHeader, false, "name", true, "Value"));
EXPECT_FATAL_FAILURE(LiteralNameValueHeaderErrorTest(),
"Value of: name_.HasEnded");
}
void DynamicTableSizeUpdateErrorTest() {
HpackEntryCollector collector;
collector.OnDynamicTableSizeUpdate(123);
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsComplete());
EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(123));
collector.OnDynamicTableSizeUpdate(234);
}
TEST(HpackEntryCollectorTest, DynamicTableSizeUpdate) {
HpackEntryCollector collector;
collector.OnDynamicTableSizeUpdate(8192);
QUICHE_VLOG(1) << collector;
EXPECT_FALSE(collector.IsClear());
EXPECT_TRUE(collector.IsComplete());
EXPECT_TRUE(collector.ValidateDynamicTableSizeUpdate(8192));
EXPECT_EQ(collector,
HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8192));
EXPECT_NE(collector,
HpackEntryCollector(HpackEntryType::kIndexedHeader, 8192));
EXPECT_NE(collector,
HpackEntryCollector(HpackEntryType::kDynamicTableSizeUpdate, 8191));
EXPECT_FATAL_FAILURE(DynamicTableSizeUpdateErrorTest(), "Value of: started_");
}
}
}
} |
449 | cpp | google/quiche | http2_frame_builder | quiche/http2/test_tools/http2_frame_builder.cc | quiche/http2/test_tools/http2_frame_builder_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HTTP2_FRAME_BUILDER_H_
#define QUICHE_HTTP2_TEST_TOOLS_HTTP2_FRAME_BUILDER_H_
#include <stddef.h>
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/http2_structures.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace http2 {
namespace test {
class QUICHE_NO_EXPORT Http2FrameBuilder {
public:
Http2FrameBuilder(Http2FrameType type, uint8_t flags, uint32_t stream_id);
explicit Http2FrameBuilder(const Http2FrameHeader& v);
Http2FrameBuilder() {}
~Http2FrameBuilder() {}
size_t size() const { return buffer_.size(); }
const std::string& buffer() const { return buffer_; }
void Append(absl::string_view s);
void AppendBytes(const void* data, uint32_t num_bytes);
template <typename T, size_t N>
void AppendBytes(T (&buf)[N]) {
AppendBytes(buf, N * sizeof(buf[0]));
}
void AppendZeroes(size_t num_zero_bytes);
void AppendUInt8(uint8_t value);
void AppendUInt16(uint16_t value);
void AppendUInt24(uint32_t value);
void AppendUInt31(uint32_t value);
void AppendUInt32(uint32_t value);
void Append(Http2ErrorCode error_code);
void Append(Http2FrameType type);
void Append(Http2SettingsParameter parameter);
void Append(const Http2FrameHeader& v);
void Append(const Http2PriorityFields& v);
void Append(const Http2RstStreamFields& v);
void Append(const Http2SettingFields& v);
void Append(const Http2PushPromiseFields& v);
void Append(const Http2PingFields& v);
void Append(const Http2GoAwayFields& v);
void Append(const Http2WindowUpdateFields& v);
void Append(const Http2AltSvcFields& v);
void Append(const Http2PriorityUpdateFields& v);
void WriteAt(absl::string_view s, size_t offset);
void WriteBytesAt(const void* data, uint32_t num_bytes, size_t offset);
void WriteUInt24At(uint32_t value, size_t offset);
void SetPayloadLength(uint32_t payload_length);
size_t SetPayloadLength();
private:
std::string buffer_;
};
}
}
#endif
#include "quiche/http2/test_tools/http2_frame_builder.h"
#ifdef WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#endif
#include "absl/strings/str_cat.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
Http2FrameBuilder::Http2FrameBuilder(Http2FrameType type, uint8_t flags,
uint32_t stream_id) {
AppendUInt24(0);
Append(type);
AppendUInt8(flags);
AppendUInt31(stream_id);
}
Http2FrameBuilder::Http2FrameBuilder(const Http2FrameHeader& v) { Append(v); }
void Http2FrameBuilder::Append(absl::string_view s) {
absl::StrAppend(&buffer_, s);
}
void Http2FrameBuilder::AppendBytes(const void* data, uint32_t num_bytes) {
Append(absl::string_view(static_cast<const char*>(data), num_bytes));
}
void Http2FrameBuilder::AppendZeroes(size_t num_zero_bytes) {
char zero = 0;
buffer_.append(num_zero_bytes, zero);
}
void Http2FrameBuilder::AppendUInt8(uint8_t value) { AppendBytes(&value, 1); }
void Http2FrameBuilder::AppendUInt16(uint16_t value) {
value = htons(value);
AppendBytes(&value, 2);
}
void Http2FrameBuilder::AppendUInt24(uint32_t value) {
EXPECT_EQ(value, value & 0xffffff);
value = htonl(value);
AppendBytes(reinterpret_cast<char*>(&value) + 1, 3);
}
void Http2FrameBuilder::AppendUInt31(uint32_t value) {
uint32_t tmp = value & StreamIdMask();
EXPECT_EQ(value, value & StreamIdMask())
<< "High-bit of uint32_t should be clear.";
value = htonl(tmp);
AppendBytes(&value, 4);
}
void Http2FrameBuilder::AppendUInt32(uint32_t value) {
value = htonl(value);
AppendBytes(&value, sizeof(value));
}
void Http2FrameBuilder::Append(Http2ErrorCode error_code) {
AppendUInt32(static_cast<uint32_t>(error_code));
}
void Http2FrameBuilder::Append(Http2FrameType type) {
AppendUInt8(static_cast<uint8_t>(type));
}
void Http2FrameBuilder::Append(Http2SettingsParameter parameter) {
AppendUInt16(static_cast<uint16_t>(parameter));
}
void Http2FrameBuilder::Append(const Http2FrameHeader& v) {
AppendUInt24(v.payload_length);
Append(v.type);
AppendUInt8(v.flags);
AppendUInt31(v.stream_id);
}
void Http2FrameBuilder::Append(const Http2PriorityFields& v) {
uint32_t tmp = v.stream_dependency & StreamIdMask();
EXPECT_EQ(tmp, v.stream_dependency);
if (v.is_exclusive) {
tmp |= 0x80000000;
}
AppendUInt32(tmp);
ASSERT_LE(1u, v.weight);
ASSERT_LE(v.weight, 256u);
AppendUInt8(v.weight - 1);
}
void Http2FrameBuilder::Append(const Http2RstStreamFields& v) {
Append(v.error_code);
}
void Http2FrameBuilder::Append(const Http2SettingFields& v) {
Append(v.parameter);
AppendUInt32(v.value);
}
void Http2FrameBuilder::Append(const Http2PushPromiseFields& v) {
AppendUInt31(v.promised_stream_id);
}
void Http2FrameBuilder::Append(const Http2PingFields& v) {
AppendBytes(v.opaque_bytes, sizeof Http2PingFields::opaque_bytes);
}
void Http2FrameBuilder::Append(const Http2GoAwayFields& v) {
AppendUInt31(v.last_stream_id);
Append(v.error_code);
}
void Http2FrameBuilder::Append(const Http2WindowUpdateFields& v) {
EXPECT_NE(0u, v.window_size_increment) << "Increment must be non-zero.";
AppendUInt31(v.window_size_increment);
}
void Http2FrameBuilder::Append(const Http2AltSvcFields& v) {
AppendUInt16(v.origin_length);
}
void Http2FrameBuilder::Append(const Http2PriorityUpdateFields& v) {
AppendUInt31(v.prioritized_stream_id);
}
void Http2FrameBuilder::WriteAt(absl::string_view s, size_t offset) {
ASSERT_LE(offset, buffer_.size());
size_t len = offset + s.size();
if (len > buffer_.size()) {
buffer_.resize(len);
}
for (size_t ndx = 0; ndx < s.size(); ++ndx) {
buffer_[offset + ndx] = s[ndx];
}
}
void Http2FrameBuilder::WriteBytesAt(const void* data, uint32_t num_bytes,
size_t offset) {
WriteAt(absl::string_view(static_cast<const char*>(data), num_bytes), offset);
}
void Http2FrameBuilder::WriteUInt24At(uint32_t value, size_t offset) {
ASSERT_LT(value, static_cast<uint32_t>(1 << 24));
value = htonl(value);
WriteBytesAt(reinterpret_cast<char*>(&value) + 1, sizeof(value) - 1, offset);
}
void Http2FrameBuilder::SetPayloadLength(uint32_t payload_length) {
WriteUInt24At(payload_length, 0);
}
size_t Http2FrameBuilder::SetPayloadLength() {
EXPECT_GE(size(), Http2FrameHeader::EncodedSize());
uint32_t payload_length = size() - Http2FrameHeader::EncodedSize();
SetPayloadLength(payload_length);
return payload_length;
}
}
} | #include "quiche/http2/test_tools/http2_frame_builder.h"
#include <string>
#include "absl/strings/escaping.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
const char kHighBitSetMsg[] = "High-bit of uint32_t should be clear";
TEST(Http2FrameBuilderTest, Constructors) {
{
Http2FrameBuilder fb;
EXPECT_EQ(0u, fb.size());
}
{
Http2FrameBuilder fb(Http2FrameType::DATA, 0, 123);
EXPECT_EQ(9u, fb.size());
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("000000"
"00"
"00"
"0000007b",
&expected_data));
EXPECT_EQ(expected_data, fb.buffer());
}
{
Http2FrameHeader header;
header.payload_length = (1 << 24) - 1;
header.type = Http2FrameType::HEADERS;
header.flags = Http2FrameFlag::END_HEADERS;
header.stream_id = StreamIdMask();
Http2FrameBuilder fb(header);
EXPECT_EQ(9u, fb.size());
std::string expected_data;
ASSERT_TRUE(absl::HexStringToBytes(
"ffffff"
"01"
"04"
"7fffffff",
&expected_data));
EXPECT_EQ(expected_data, fb.buffer());
}
}
TEST(Http2FrameBuilderTest, SetPayloadLength) {
Http2FrameBuilder fb(Http2FrameType::DATA, PADDED, 20000);
EXPECT_EQ(9u, fb.size());
fb.AppendUInt8(50);
EXPECT_EQ(10u, fb.size());
fb.Append("ten bytes.");
EXPECT_EQ(20u, fb.size());
fb.AppendZeroes(50);
EXPECT_EQ(70u, fb.size());
fb.SetPayloadLength();
EXPECT_EQ(70u, fb.size());
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("00003d"
"00"
"08"
"00004e20"
"32"
"74656e2062797465732e"
"00000000000000000000"
"00000000000000000000"
"00000000000000000000"
"00000000000000000000"
"00000000000000000000",
&expected_data));
EXPECT_EQ(expected_data, fb.buffer());
}
TEST(Http2FrameBuilderTest, Settings) {
Http2FrameBuilder fb(Http2FrameType::SETTINGS, 0, 0);
Http2SettingFields sf;
sf.parameter = Http2SettingsParameter::HEADER_TABLE_SIZE;
sf.value = 1 << 12;
fb.Append(sf);
sf.parameter = Http2SettingsParameter::ENABLE_PUSH;
sf.value = 0;
fb.Append(sf);
sf.parameter = Http2SettingsParameter::MAX_CONCURRENT_STREAMS;
sf.value = ~0;
fb.Append(sf);
sf.parameter = Http2SettingsParameter::INITIAL_WINDOW_SIZE;
sf.value = 1 << 16;
fb.Append(sf);
sf.parameter = Http2SettingsParameter::MAX_FRAME_SIZE;
sf.value = 1 << 14;
fb.Append(sf);
sf.parameter = Http2SettingsParameter::MAX_HEADER_LIST_SIZE;
sf.value = 1 << 10;
fb.Append(sf);
size_t payload_size = 6 * Http2SettingFields::EncodedSize();
EXPECT_EQ(Http2FrameHeader::EncodedSize() + payload_size, fb.size());
fb.SetPayloadLength(payload_size);
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("000024"
"04"
"00"
"00000000"
"0001"
"00001000"
"0002"
"00000000"
"0003"
"ffffffff"
"0004"
"00010000"
"0005"
"00004000"
"0006"
"00000400",
&expected_data));
EXPECT_EQ(expected_data, fb.buffer());
}
TEST(Http2FrameBuilderTest, EnhanceYourCalm) {
std::string expected_data;
ASSERT_TRUE(absl::HexStringToBytes("0000000b", &expected_data));
{
Http2FrameBuilder fb;
fb.Append(Http2ErrorCode::ENHANCE_YOUR_CALM);
EXPECT_EQ(expected_data, fb.buffer());
}
{
Http2FrameBuilder fb;
Http2RstStreamFields rsp;
rsp.error_code = Http2ErrorCode::ENHANCE_YOUR_CALM;
fb.Append(rsp);
EXPECT_EQ(expected_data, fb.buffer());
}
}
TEST(Http2FrameBuilderTest, PushPromise) {
std::string expected_data;
ASSERT_TRUE(absl::HexStringToBytes("7fffffff", &expected_data));
{
Http2FrameBuilder fb;
fb.Append(Http2PushPromiseFields{0x7fffffff});
EXPECT_EQ(expected_data, fb.buffer());
}
{
Http2FrameBuilder fb;
EXPECT_NONFATAL_FAILURE(fb.Append(Http2PushPromiseFields{0xffffffff}),
kHighBitSetMsg);
EXPECT_EQ(expected_data, fb.buffer());
}
}
TEST(Http2FrameBuilderTest, Ping) {
Http2FrameBuilder fb;
Http2PingFields ping{"8 bytes"};
fb.Append(ping);
const absl::string_view kData{"8 bytes\0", 8};
EXPECT_EQ(kData.size(), Http2PingFields::EncodedSize());
EXPECT_EQ(kData, fb.buffer());
}
TEST(Http2FrameBuilderTest, GoAway) {
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("12345678"
"00000001",
&expected_data));
EXPECT_EQ(expected_data.size(), Http2GoAwayFields::EncodedSize());
{
Http2FrameBuilder fb;
Http2GoAwayFields ga(0x12345678, Http2ErrorCode::PROTOCOL_ERROR);
fb.Append(ga);
EXPECT_EQ(expected_data, fb.buffer());
}
{
Http2FrameBuilder fb;
Http2GoAwayFields ga(0x92345678, Http2ErrorCode::PROTOCOL_ERROR);
EXPECT_NONFATAL_FAILURE(fb.Append(ga), kHighBitSetMsg);
EXPECT_EQ(expected_data, fb.buffer());
}
}
TEST(Http2FrameBuilderTest, WindowUpdate) {
Http2FrameBuilder fb;
fb.Append(Http2WindowUpdateFields{123456});
EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0x80000001}),
kHighBitSetMsg);
EXPECT_NONFATAL_FAILURE(fb.Append(Http2WindowUpdateFields{0}), "non-zero");
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("0001e240"
"00000001"
"00000000",
&expected_data));
EXPECT_EQ(expected_data.size(), 3 * Http2WindowUpdateFields::EncodedSize());
EXPECT_EQ(expected_data, fb.buffer());
}
TEST(Http2FrameBuilderTest, AltSvc) {
Http2FrameBuilder fb;
fb.Append(Http2AltSvcFields{99});
fb.Append(Http2AltSvcFields{0});
std::string expected_data;
ASSERT_TRUE(
absl::HexStringToBytes("0063"
"0000",
&expected_data));
EXPECT_EQ(expected_data.size(), 2 * Http2AltSvcFields::EncodedSize());
EXPECT_EQ(expected_data, fb.buffer());
}
}
}
} |
450 | cpp | google/quiche | hpack_block_builder | quiche/http2/test_tools/hpack_block_builder.cc | quiche/http2/test_tools/hpack_block_builder_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_BUILDER_H_
#define QUICHE_HTTP2_TEST_TOOLS_HPACK_BLOCK_BUILDER_H_
#include <stddef.h>
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/http2_hpack_constants.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
class QUICHE_NO_EXPORT HpackBlockBuilder {
public:
explicit HpackBlockBuilder(absl::string_view initial_contents)
: buffer_(initial_contents.data(), initial_contents.size()) {}
HpackBlockBuilder() {}
~HpackBlockBuilder() {}
size_t size() const { return buffer_.size(); }
const std::string& buffer() const { return buffer_; }
void AppendIndexedHeader(uint64_t index) {
AppendEntryTypeAndVarint(HpackEntryType::kIndexedHeader, index);
}
void AppendDynamicTableSizeUpdate(uint64_t size) {
AppendEntryTypeAndVarint(HpackEntryType::kDynamicTableSizeUpdate, size);
}
void AppendNameIndexAndLiteralValue(HpackEntryType entry_type,
uint64_t name_index,
bool value_is_huffman_encoded,
absl::string_view value) {
EXPECT_NE(0u, name_index);
AppendEntryTypeAndVarint(entry_type, name_index);
AppendString(value_is_huffman_encoded, value);
}
void AppendLiteralNameAndValue(HpackEntryType entry_type,
bool name_is_huffman_encoded,
absl::string_view name,
bool value_is_huffman_encoded,
absl::string_view value) {
AppendEntryTypeAndVarint(entry_type, 0);
AppendString(name_is_huffman_encoded, name);
AppendString(value_is_huffman_encoded, value);
}
void AppendHighBitsAndVarint(uint8_t high_bits, uint8_t prefix_length,
uint64_t varint);
void AppendEntryTypeAndVarint(HpackEntryType entry_type, uint64_t varint);
void AppendString(bool is_huffman_encoded, absl::string_view str);
private:
std::string buffer_;
};
}
}
#endif
#include "quiche/http2/test_tools/hpack_block_builder.h"
#include "quiche/http2/hpack/varint/hpack_varint_encoder.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
void HpackBlockBuilder::AppendHighBitsAndVarint(uint8_t high_bits,
uint8_t prefix_length,
uint64_t varint) {
EXPECT_LE(3, prefix_length);
EXPECT_LE(prefix_length, 8);
HpackVarintEncoder::Encode(high_bits, prefix_length, varint, &buffer_);
}
void HpackBlockBuilder::AppendEntryTypeAndVarint(HpackEntryType entry_type,
uint64_t varint) {
uint8_t high_bits;
uint8_t prefix_length;
switch (entry_type) {
case HpackEntryType::kIndexedHeader:
high_bits = 0x80;
prefix_length = 7;
break;
case HpackEntryType::kDynamicTableSizeUpdate:
high_bits = 0x20;
prefix_length = 5;
break;
case HpackEntryType::kIndexedLiteralHeader:
high_bits = 0x40;
prefix_length = 6;
break;
case HpackEntryType::kUnindexedLiteralHeader:
high_bits = 0x00;
prefix_length = 4;
break;
case HpackEntryType::kNeverIndexedLiteralHeader:
high_bits = 0x10;
prefix_length = 4;
break;
default:
QUICHE_BUG(http2_bug_110_1) << "Unreached, entry_type=" << entry_type;
high_bits = 0;
prefix_length = 0;
break;
}
AppendHighBitsAndVarint(high_bits, prefix_length, varint);
}
void HpackBlockBuilder::AppendString(bool is_huffman_encoded,
absl::string_view str) {
uint8_t high_bits = is_huffman_encoded ? 0x80 : 0;
uint8_t prefix_length = 7;
AppendHighBitsAndVarint(high_bits, prefix_length, str.size());
buffer_.append(str.data(), str.size());
}
}
} | #include "quiche/http2/test_tools/hpack_block_builder.h"
#include <string>
#include "absl/strings/escaping.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace http2 {
namespace test {
namespace {
const bool kUncompressed = false;
const bool kCompressed = true;
const uint32_t kStaticTableMethodGET = 2;
const uint32_t kStaticTablePathSlash = 4;
const uint32_t kStaticTableSchemeHttp = 6;
TEST(HpackBlockBuilderTest, ExamplesFromSpecC2) {
{
HpackBlockBuilder b;
b.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader,
kUncompressed, "custom-key", kUncompressed,
"custom-header");
EXPECT_EQ(26u, b.size());
const char kExpected[] =
"\x40"
"\x0a"
"custom-key"
"\x0d"
"custom-header";
EXPECT_EQ(kExpected, b.buffer());
}
{
HpackBlockBuilder b;
b.AppendNameIndexAndLiteralValue(HpackEntryType::kUnindexedLiteralHeader, 4,
kUncompressed, "/sample/path");
EXPECT_EQ(14u, b.size());
const char kExpected[] =
"\x04"
"\x0c"
"/sample/path";
EXPECT_EQ(kExpected, b.buffer());
}
{
HpackBlockBuilder b;
b.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader,
kUncompressed, "password", kUncompressed,
"secret");
EXPECT_EQ(17u, b.size());
const char kExpected[] =
"\x10"
"\x08"
"password"
"\x06"
"secret";
EXPECT_EQ(kExpected, b.buffer());
}
{
HpackBlockBuilder b;
b.AppendIndexedHeader(2);
EXPECT_EQ(1u, b.size());
const char kExpected[] = "\x82";
EXPECT_EQ(kExpected, b.buffer());
}
}
TEST(HpackBlockBuilderTest, ExamplesFromSpecC3) {
{
HpackBlockBuilder b;
b.AppendIndexedHeader(2);
b.AppendIndexedHeader(6);
b.AppendIndexedHeader(4);
b.AppendNameIndexAndLiteralValue(HpackEntryType::kIndexedLiteralHeader, 1,
kUncompressed, "www.example.com");
EXPECT_EQ(20u, b.size());
std::string expected;
ASSERT_TRUE(absl::HexStringToBytes(
"828684410f7777772e6578616d706c652e636f6d", &expected));
EXPECT_EQ(expected, b.buffer());
}
}
TEST(HpackBlockBuilderTest, ExamplesFromSpecC4) {
{
HpackBlockBuilder b;
b.AppendIndexedHeader(kStaticTableMethodGET);
b.AppendIndexedHeader(kStaticTableSchemeHttp);
b.AppendIndexedHeader(kStaticTablePathSlash);
const char kHuffmanWwwExampleCom[] = {'\xf1', '\xe3', '\xc2', '\xe5',
'\xf2', '\x3a', '\x6b', '\xa0',
'\xab', '\x90', '\xf4', '\xff'};
b.AppendNameIndexAndLiteralValue(
HpackEntryType::kIndexedLiteralHeader, 1, kCompressed,
absl::string_view(kHuffmanWwwExampleCom, sizeof kHuffmanWwwExampleCom));
EXPECT_EQ(17u, b.size());
std::string expected;
ASSERT_TRUE(absl::HexStringToBytes("828684418cf1e3c2e5f23a6ba0ab90f4ff",
&expected));
EXPECT_EQ(expected, b.buffer());
}
}
TEST(HpackBlockBuilderTest, DynamicTableSizeUpdate) {
{
HpackBlockBuilder b;
b.AppendDynamicTableSizeUpdate(0);
EXPECT_EQ(1u, b.size());
const char kData[] = {'\x20'};
absl::string_view expected(kData, sizeof kData);
EXPECT_EQ(expected, b.buffer());
}
{
HpackBlockBuilder b;
b.AppendDynamicTableSizeUpdate(4096);
EXPECT_EQ(3u, b.size());
const char kData[] = {'\x3f', '\xe1', '\x1f'};
absl::string_view expected(kData, sizeof kData);
EXPECT_EQ(expected, b.buffer());
}
{
HpackBlockBuilder b;
b.AppendDynamicTableSizeUpdate(1000000000000);
EXPECT_EQ(7u, b.size());
const char kData[] = {'\x3f', '\xe1', '\x9f', '\x94',
'\xa5', '\x8d', '\x1d'};
absl::string_view expected(kData, sizeof kData);
EXPECT_EQ(expected, b.buffer());
}
}
}
}
} |
451 | cpp | google/quiche | random_decoder_test_base | quiche/http2/test_tools/random_decoder_test_base.cc | quiche/http2/test_tools/random_decoder_test_base_test.cc | #ifndef QUICHE_HTTP2_TEST_TOOLS_RANDOM_DECODER_TEST_BASE_H_
#define QUICHE_HTTP2_TEST_TOOLS_RANDOM_DECODER_TEST_BASE_H_
#include <stddef.h>
#include <cstdint>
#include <type_traits>
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/quiche_callbacks.h"
namespace http2 {
namespace test {
template <typename T, size_t N>
absl::string_view ToStringPiece(T (&data)[N]) {
return absl::string_view(reinterpret_cast<const char*>(data), N * sizeof(T));
}
template <typename T,
typename E = typename std::enable_if<std::is_enum<T>::value>::type>
void CorruptEnum(T* out, Http2Random* rng) {
using underlying_type_T = typename std::underlying_type<T>::type;
using unsigned_underlying_type_T =
typename std::make_unsigned<underlying_type_T>::type;
auto r = static_cast<unsigned_underlying_type_T>(rng->Rand32());
*out = static_cast<T>(r);
}
class QUICHE_NO_EXPORT RandomDecoderTest : public quiche::test::QuicheTest {
public:
using SelectSize = quiche::MultiUseCallback<size_t(bool first, size_t offset,
size_t remaining)>;
using AssertionResult = ::testing::AssertionResult;
using Validator = quiche::MultiUseCallback<AssertionResult(
const DecodeBuffer& input, DecodeStatus status)>;
using NoArgValidator = quiche::MultiUseCallback<AssertionResult()>;
RandomDecoderTest();
protected:
virtual DecodeStatus StartDecoding(DecodeBuffer* db) = 0;
virtual DecodeStatus ResumeDecoding(DecodeBuffer* db) = 0;
virtual bool StopDecodeOnDone();
DecodeStatus DecodeSegments(DecodeBuffer* original,
const SelectSize& select_size);
::testing::AssertionResult DecodeSegmentsAndValidate(
DecodeBuffer* original, const SelectSize& select_size,
const Validator& validator) {
DecodeStatus status = DecodeSegments(original, select_size);
return validator(*original, status);
}
static SelectSize SelectRemaining() {
return [](bool , size_t , size_t remaining) -> size_t {
return remaining;
};
}
static SelectSize SelectOne() {
return [](bool , size_t ,
size_t ) -> size_t { return 1; };
}
static SelectSize SelectZeroAndOne(bool return_non_zero_on_first);
SelectSize SelectRandom(bool return_non_zero_on_first);
AssertionResult DecodeAndValidateSeveralWays(DecodeBuffer* original,
bool return_non_zero_on_first,
const Validator& validator);
static Validator ToValidator(std::nullptr_t) {
return [](const DecodeBuffer& , DecodeStatus ) {
return ::testing::AssertionSuccess();
};
}
static Validator ToValidator(Validator validator) {
if (validator == nullptr) {
return ToValidator(nullptr);
}
return validator;
}
static Validator ToValidator(NoArgValidator validator) {
if (validator == nullptr) {
return ToValidator(nullptr);
}
return [validator = std::move(validator)](const DecodeBuffer& ,
DecodeStatus ) {
return validator();
};
}
static Validator ValidateDoneAndEmpty(Validator wrapped) {
return [wrapped = std::move(wrapped)](
const DecodeBuffer& input,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);
HTTP2_VERIFY_EQ(0u, input.Remaining()) << "\nOffset=" << input.Offset();
if (wrapped) {
return wrapped(input, status);
}
return ::testing::AssertionSuccess();
};
}
static Validator ValidateDoneAndEmpty(NoArgValidator wrapped) {
return [wrapped = std::move(wrapped)](
const DecodeBuffer& input,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);
HTTP2_VERIFY_EQ(0u, input.Remaining()) << "\nOffset=" << input.Offset();
if (wrapped) {
return wrapped();
}
return ::testing::AssertionSuccess();
};
}
static Validator ValidateDoneAndEmpty() {
return ValidateDoneAndEmpty(NoArgValidator());
}
static Validator ValidateDoneAndOffset(uint32_t offset, Validator wrapped) {
return [wrapped = std::move(wrapped), offset](
const DecodeBuffer& input,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);
HTTP2_VERIFY_EQ(offset, input.Offset())
<< "\nRemaining=" << input.Remaining();
if (wrapped) {
return wrapped(input, status);
}
return ::testing::AssertionSuccess();
};
}
static Validator ValidateDoneAndOffset(uint32_t offset,
NoArgValidator wrapped) {
return [wrapped = std::move(wrapped), offset](
const DecodeBuffer& input,
DecodeStatus status) -> AssertionResult {
HTTP2_VERIFY_EQ(status, DecodeStatus::kDecodeDone);
HTTP2_VERIFY_EQ(offset, input.Offset())
<< "\nRemaining=" << input.Remaining();
if (wrapped) {
return wrapped();
}
return ::testing::AssertionSuccess();
};
}
static Validator ValidateDoneAndOffset(uint32_t offset) {
return ValidateDoneAndOffset(offset, NoArgValidator());
}
Http2Random& Random() { return random_; }
Http2Random* RandomPtr() { return &random_; }
uint32_t RandStreamId();
bool stop_decode_on_done_ = true;
private:
Http2Random random_;
};
}
}
#endif
#include "quiche/http2/test_tools/random_decoder_test_base.h"
#include <stddef.h>
#include <algorithm>
#include <memory>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/http2_constants.h"
#include "quiche/http2/test_tools/verify_macros.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::AssertionResult;
namespace http2 {
namespace test {
RandomDecoderTest::RandomDecoderTest() = default;
bool RandomDecoderTest::StopDecodeOnDone() { return stop_decode_on_done_; }
DecodeStatus RandomDecoderTest::DecodeSegments(DecodeBuffer* original,
const SelectSize& select_size) {
DecodeStatus status = DecodeStatus::kDecodeInProgress;
bool first = true;
QUICHE_VLOG(2) << "DecodeSegments: input size=" << original->Remaining();
while (first || original->HasData()) {
size_t remaining = original->Remaining();
size_t size =
std::min(remaining, select_size(first, original->Offset(), remaining));
DecodeBuffer db(original->cursor(), size);
QUICHE_VLOG(2) << "Decoding " << size << " bytes of " << remaining
<< " remaining";
if (first) {
first = false;
status = StartDecoding(&db);
} else {
status = ResumeDecoding(&db);
}
if (db.Offset() == 0 && db.HasData() &&
status != DecodeStatus::kDecodeError) {
ADD_FAILURE() << "Decoder didn't make any progress; db.FullSize="
<< db.FullSize()
<< " original.Offset=" << original->Offset();
return DecodeStatus::kDecodeError;
}
original->AdvanceCursor(db.Offset());
switch (status) {
case DecodeStatus::kDecodeDone:
if (original->Empty() || StopDecodeOnDone()) {
return DecodeStatus::kDecodeDone;
}
continue;
case DecodeStatus::kDecodeInProgress:
continue;
case DecodeStatus::kDecodeError:
return DecodeStatus::kDecodeError;
}
}
return status;
}
AssertionResult RandomDecoderTest::DecodeAndValidateSeveralWays(
DecodeBuffer* original, bool return_non_zero_on_first,
const Validator& validator) {
const uint32_t original_remaining = original->Remaining();
QUICHE_VLOG(1) << "DecodeAndValidateSeveralWays - Start, remaining = "
<< original_remaining;
uint32_t first_consumed;
{
DecodeBuffer input(original->cursor(), original_remaining);
QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectRemaining";
HTTP2_VERIFY_SUCCESS(
DecodeSegmentsAndValidate(&input, SelectRemaining(), validator))
<< "\nFailed with SelectRemaining; input.Offset=" << input.Offset()
<< "; input.Remaining=" << input.Remaining();
first_consumed = input.Offset();
}
if (original_remaining <= 30) {
DecodeBuffer input(original->cursor(), original_remaining);
QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectOne";
HTTP2_VERIFY_SUCCESS(
DecodeSegmentsAndValidate(&input, SelectOne(), validator))
<< "\nFailed with SelectOne; input.Offset=" << input.Offset()
<< "; input.Remaining=" << input.Remaining();
HTTP2_VERIFY_EQ(first_consumed, input.Offset())
<< "\nFailed with SelectOne";
}
if (original_remaining <= 20) {
DecodeBuffer input(original->cursor(), original_remaining);
QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectZeroAndOne";
HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate(
&input, SelectZeroAndOne(return_non_zero_on_first), validator))
<< "\nFailed with SelectZeroAndOne";
HTTP2_VERIFY_EQ(first_consumed, input.Offset())
<< "\nFailed with SelectZeroAndOne; input.Offset=" << input.Offset()
<< "; input.Remaining=" << input.Remaining();
}
{
DecodeBuffer input(original->cursor(), original_remaining);
QUICHE_VLOG(2) << "DecodeSegmentsAndValidate with SelectRandom";
HTTP2_VERIFY_SUCCESS(DecodeSegmentsAndValidate(
&input, SelectRandom(return_non_zero_on_first), validator))
<< "\nFailed with SelectRandom; input.Offset=" << input.Offset()
<< "; input.Remaining=" << input.Remaining();
HTTP2_VERIFY_EQ(first_consumed, input.Offset())
<< "\nFailed with SelectRandom";
}
HTTP2_VERIFY_EQ(original_remaining, original->Remaining());
original->AdvanceCursor(first_consumed);
QUICHE_VLOG(1) << "DecodeAndValidateSeveralWays - SUCCESS";
return ::testing::AssertionSuccess();
}
RandomDecoderTest::SelectSize RandomDecoderTest::SelectZeroAndOne(
bool return_non_zero_on_first) {
std::shared_ptr<bool> zero_next(new bool);
*zero_next = !return_non_zero_on_first;
return [zero_next](bool , size_t ,
size_t ) -> size_t {
if (*zero_next) {
*zero_next = false;
return 0;
} else {
*zero_next = true;
return 1;
}
};
}
RandomDecoderTest::SelectSize RandomDecoderTest::SelectRandom(
bool return_non_zero_on_first) {
return [this, return_non_zero_on_first](bool first, size_t ,
size_t remaining) -> size_t {
uint32_t r = random_.Rand32();
if (first && return_non_zero_on_first) {
QUICHE_CHECK_LT(0u, remaining);
if (remaining == 1) {
return 1;
}
return 1 + (r % remaining);
}
return r % (remaining + 1);
};
}
uint32_t RandomDecoderTest::RandStreamId() {
return random_.Rand32() & StreamIdMask();
}
}
} | #include "quiche/http2/test_tools/random_decoder_test_base.h"
#include <stddef.h>
#include <functional>
#include <ios>
#include <set>
#include <type_traits>
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/http2/test_tools/http2_random.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/quiche_callbacks.h"
namespace http2 {
namespace test {
namespace {
const char kData[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
const bool kReturnNonZeroOnFirst = true;
const bool kMayReturnZeroOnFirst = false;
class RandomDecoderTestTest : public RandomDecoderTest {
public:
RandomDecoderTestTest() : data_db_(kData) {
QUICHE_CHECK_EQ(sizeof kData, 8u);
}
protected:
typedef quiche::MultiUseCallback<DecodeStatus(DecodeBuffer* db)> DecodingFn;
DecodeStatus StartDecoding(DecodeBuffer* db) override {
++start_decoding_calls_;
if (start_decoding_fn_) {
return start_decoding_fn_(db);
}
return DecodeStatus::kDecodeError;
}
DecodeStatus ResumeDecoding(DecodeBuffer* db) override {
++resume_decoding_calls_;
if (resume_decoding_fn_) {
return resume_decoding_fn_(db);
}
return DecodeStatus::kDecodeError;
}
bool StopDecodeOnDone() override {
++stop_decode_on_done_calls_;
if (override_stop_decode_on_done_) {
return sub_stop_decode_on_done_;
}
return RandomDecoderTest::StopDecodeOnDone();
}
size_t start_decoding_calls_ = 0;
size_t resume_decoding_calls_ = 0;
size_t stop_decode_on_done_calls_ = 0;
DecodingFn start_decoding_fn_;
DecodingFn resume_decoding_fn_;
DecodeBuffer data_db_;
bool sub_stop_decode_on_done_ = true;
bool override_stop_decode_on_done_ = true;
};
TEST_F(RandomDecoderTestTest, StopOnStartPartiallyDone) {
start_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_EQ(kData, db->cursor());
EXPECT_EQ(sizeof kData, db->Remaining());
db->DecodeUInt8();
return DecodeStatus::kDecodeDone;
};
EXPECT_EQ(DecodeStatus::kDecodeDone,
DecodeSegments(&data_db_, SelectRemaining()));
EXPECT_EQ(1u, data_db_.Offset());
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_EQ(0u, resume_decoding_calls_);
EXPECT_EQ(1u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, StopOnResumePartiallyDone) {
start_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, start_decoding_calls_);
db->DecodeUInt8();
return DecodeStatus::kDecodeInProgress;
};
resume_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, resume_decoding_calls_);
EXPECT_EQ(data_db_.cursor(), db->cursor());
db->DecodeUInt16();
return DecodeStatus::kDecodeDone;
};
override_stop_decode_on_done_ = false;
stop_decode_on_done_ = true;
EXPECT_EQ(DecodeStatus::kDecodeDone,
DecodeSegments(&data_db_, SelectRemaining()));
EXPECT_EQ(3u, data_db_.Offset());
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_EQ(1u, resume_decoding_calls_);
EXPECT_EQ(1u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, InProgressWhenEmpty) {
start_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, start_decoding_calls_);
if (db->HasData()) {
db->DecodeUInt8();
if (db->HasData()) {
db->DecodeUInt8();
}
}
return DecodeStatus::kDecodeInProgress;
};
resume_decoding_fn_ = [](DecodeBuffer* db) {
if (db->HasData()) {
db->AdvanceCursor(db->Remaining());
}
return DecodeStatus::kDecodeInProgress;
};
EXPECT_EQ(DecodeStatus::kDecodeInProgress,
DecodeSegments(&data_db_, SelectRandom(kMayReturnZeroOnFirst)));
EXPECT_TRUE(data_db_.Empty());
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_LE(1u, resume_decoding_calls_);
EXPECT_EQ(0u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, DoneExactlyAtEnd) {
start_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_EQ(1u, db->Remaining());
EXPECT_EQ(1u, db->FullSize());
db->DecodeUInt8();
return DecodeStatus::kDecodeInProgress;
};
resume_decoding_fn_ = [this](DecodeBuffer* db) {
EXPECT_EQ(1u, db->Remaining());
EXPECT_EQ(1u, db->FullSize());
db->DecodeUInt8();
if (data_db_.Remaining() == 1) {
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
};
override_stop_decode_on_done_ = true;
sub_stop_decode_on_done_ = true;
EXPECT_EQ(DecodeStatus::kDecodeDone, DecodeSegments(&data_db_, SelectOne()));
EXPECT_EQ(0u, data_db_.Remaining());
EXPECT_EQ(1u, start_decoding_calls_);
EXPECT_EQ((sizeof kData) - 1, resume_decoding_calls_);
EXPECT_EQ(0u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, DecodeSeveralWaysToEnd) {
size_t decoded_since_start = 0;
auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {
decoded_since_start += db->Remaining();
db->AdvanceCursor(db->Remaining());
EXPECT_EQ(0u, db->Remaining());
if (decoded_since_start == data_db_.FullSize()) {
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
};
start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {
decoded_since_start = 0;
return shared_fn(db);
};
resume_decoding_fn_ = shared_fn;
Validator validator = ValidateDoneAndEmpty();
EXPECT_TRUE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst,
validator));
EXPECT_EQ(0u, data_db_.Remaining());
EXPECT_EQ(4u, start_decoding_calls_);
EXPECT_EQ(0u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, DecodeTwoWaysAndStopEarly) {
size_t decoded_since_start = 0;
auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {
uint32_t amount = db->Remaining();
if (start_decoding_calls_ == 2 && amount > 1) {
amount = 1;
}
decoded_since_start += amount;
db->AdvanceCursor(amount);
if (decoded_since_start == data_db_.FullSize()) {
return DecodeStatus::kDecodeDone;
}
if (decoded_since_start > 1 && start_decoding_calls_ == 2) {
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
};
start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {
decoded_since_start = 0;
return shared_fn(db);
};
resume_decoding_fn_ = shared_fn;
Validator validator = [this](const DecodeBuffer& ,
DecodeStatus status) -> AssertionResult {
if (start_decoding_calls_ <= 2 && status != DecodeStatus::kDecodeDone) {
return ::testing::AssertionFailure()
<< "Expected DecodeStatus::kDecodeDone, not " << status;
}
if (start_decoding_calls_ > 2) {
return ::testing::AssertionFailure()
<< "How did we get to pass " << start_decoding_calls_;
}
return ::testing::AssertionSuccess();
};
EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kMayReturnZeroOnFirst,
validator));
EXPECT_EQ(2u, start_decoding_calls_);
EXPECT_EQ(1u, stop_decode_on_done_calls_);
}
TEST_F(RandomDecoderTestTest, DecodeThreeWaysAndError) {
size_t decoded_since_start = 0;
auto shared_fn = [&decoded_since_start, this](DecodeBuffer* db) {
if (start_decoding_calls_ == 3 && decoded_since_start > 0) {
return DecodeStatus::kDecodeError;
}
uint32_t amount = db->Remaining();
if (start_decoding_calls_ == 3 && amount > 1) {
amount = 1;
}
decoded_since_start += amount;
db->AdvanceCursor(amount);
if (decoded_since_start == data_db_.FullSize()) {
return DecodeStatus::kDecodeDone;
}
return DecodeStatus::kDecodeInProgress;
};
start_decoding_fn_ = [&decoded_since_start, shared_fn](DecodeBuffer* db) {
decoded_since_start = 0;
return shared_fn(db);
};
resume_decoding_fn_ = shared_fn;
Validator validator = ValidateDoneAndEmpty();
EXPECT_FALSE(DecodeAndValidateSeveralWays(&data_db_, kReturnNonZeroOnFirst,
validator));
EXPECT_EQ(3u, start_decoding_calls_);
EXPECT_EQ(0u, stop_decode_on_done_calls_);
}
TEST(CorruptEnumTest, ManyValues) {
std::set<uint64_t> values;
DecodeStatus status;
QUICHE_LOG(INFO) << "sizeof status = " << sizeof status;
Http2Random rng;
for (int ndx = 0; ndx < 256; ++ndx) {
CorruptEnum(&status, &rng);
values.insert(static_cast<uint64_t>(status));
}
}
typedef typename std::underlying_type<DecodeStatus>::type DecodeStatusUT;
struct CorruptEnumTestStruct {
DecodeStatusUT filler1;
DecodeStatus status;
DecodeStatusUT filler2;
};
TEST(CorruptEnumTest, CorruptsOnlyEnum) {
Http2Random rng;
for (const DecodeStatusUT filler : {DecodeStatusUT(), ~DecodeStatusUT()}) {
QUICHE_LOG(INFO) << "filler=0x" << std::hex << filler;
CorruptEnumTestStruct s;
s.filler1 = filler;
s.filler2 = filler;
for (int ndx = 0; ndx < 256; ++ndx) {
CorruptEnum(&s.status, &rng);
EXPECT_EQ(s.filler1, filler);
EXPECT_EQ(s.filler2, filler);
}
}
}
}
}
} |
452 | cpp | google/quiche | cached_blind_sign_auth | quiche/blind_sign_auth/cached_blind_sign_auth.cc | quiche/blind_sign_auth/cached_blind_sign_auth_test.cc | #ifndef QUICHE_BLIND_SIGN_AUTH_CACHED_BLIND_SIGN_AUTH_H_
#define QUICHE_BLIND_SIGN_AUTH_CACHED_BLIND_SIGN_AUTH_H_
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_mutex.h"
#include "quiche/common/quiche_circular_deque.h"
namespace quiche {
inline constexpr int kBlindSignAuthRequestMaxTokens = 1024;
class QUICHE_EXPORT CachedBlindSignAuth : public BlindSignAuthInterface {
public:
CachedBlindSignAuth(
BlindSignAuthInterface* blind_sign_auth,
int max_tokens_per_request = kBlindSignAuthRequestMaxTokens)
: blind_sign_auth_(blind_sign_auth),
max_tokens_per_request_(max_tokens_per_request) {}
void GetTokens(std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback) override;
void ClearCache() {
QuicheWriterMutexLock lock(&mutex_);
cached_tokens_.clear();
}
private:
void HandleGetTokensResponse(
SignedTokenCallback callback, int num_tokens,
absl::StatusOr<absl::Span<BlindSignToken>> tokens);
std::vector<BlindSignToken> CreateOutputTokens(int num_tokens)
QUICHE_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
void RemoveExpiredTokens() QUICHE_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
BlindSignAuthInterface* blind_sign_auth_;
int max_tokens_per_request_;
QuicheMutex mutex_;
QuicheCircularDeque<BlindSignToken> cached_tokens_ QUICHE_GUARDED_BY(mutex_);
};
}
#endif
#include "quiche/blind_sign_auth/cached_blind_sign_auth.h"
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/functional/bind_front.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_mutex.h"
namespace quiche {
constexpr absl::Duration kFreshnessConstant = absl::Minutes(5);
void CachedBlindSignAuth::GetTokens(std::optional<std::string> oauth_token,
int num_tokens, ProxyLayer proxy_layer,
BlindSignAuthServiceType service_type,
SignedTokenCallback callback) {
if (num_tokens > max_tokens_per_request_) {
std::move(callback)(absl::InvalidArgumentError(
absl::StrFormat("Number of tokens requested exceeds maximum: %d",
kBlindSignAuthRequestMaxTokens)));
return;
}
if (num_tokens < 0) {
std::move(callback)(absl::InvalidArgumentError(absl::StrFormat(
"Negative number of tokens requested: %d", num_tokens)));
return;
}
std::vector<BlindSignToken> output_tokens;
{
QuicheWriterMutexLock lock(&mutex_);
RemoveExpiredTokens();
if (static_cast<size_t>(num_tokens) <= cached_tokens_.size()) {
output_tokens = CreateOutputTokens(num_tokens);
}
}
if (!output_tokens.empty() || num_tokens == 0) {
std::move(callback)(absl::MakeSpan(output_tokens));
return;
}
SignedTokenCallback caching_callback =
absl::bind_front(&CachedBlindSignAuth::HandleGetTokensResponse, this,
std::move(callback), num_tokens);
blind_sign_auth_->GetTokens(oauth_token, kBlindSignAuthRequestMaxTokens,
proxy_layer, service_type,
std::move(caching_callback));
}
void CachedBlindSignAuth::HandleGetTokensResponse(
SignedTokenCallback callback, int num_tokens,
absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
if (!tokens.ok()) {
QUICHE_LOG(WARNING) << "BlindSignAuth::GetTokens failed: "
<< tokens.status();
std::move(callback)(tokens);
return;
}
if (tokens->size() < static_cast<size_t>(num_tokens) ||
tokens->size() > kBlindSignAuthRequestMaxTokens) {
QUICHE_LOG(WARNING) << "Expected " << num_tokens << " tokens, got "
<< tokens->size();
}
std::vector<BlindSignToken> output_tokens;
size_t cache_size;
{
QuicheWriterMutexLock lock(&mutex_);
for (const BlindSignToken& token : *tokens) {
cached_tokens_.push_back(token);
}
RemoveExpiredTokens();
cache_size = cached_tokens_.size();
if (cache_size >= static_cast<size_t>(num_tokens)) {
output_tokens = CreateOutputTokens(num_tokens);
}
}
if (!output_tokens.empty()) {
std::move(callback)(absl::MakeSpan(output_tokens));
return;
}
std::move(callback)(absl::ResourceExhaustedError(absl::StrFormat(
"Requested %d tokens, cache only has %d after GetTokensRequest",
num_tokens, cache_size)));
}
std::vector<BlindSignToken> CachedBlindSignAuth::CreateOutputTokens(
int num_tokens) {
std::vector<BlindSignToken> output_tokens;
if (cached_tokens_.size() < static_cast<size_t>(num_tokens)) {
QUICHE_LOG(FATAL) << "Check failed, not enough tokens in cache: "
<< cached_tokens_.size() << " < " << num_tokens;
}
for (int i = 0; i < num_tokens; i++) {
output_tokens.push_back(std::move(cached_tokens_.front()));
cached_tokens_.pop_front();
}
return output_tokens;
}
void CachedBlindSignAuth::RemoveExpiredTokens() {
size_t original_size = cached_tokens_.size();
absl::Time now_plus_five_mins = absl::Now() + kFreshnessConstant;
for (size_t i = 0; i < original_size; i++) {
BlindSignToken token = std::move(cached_tokens_.front());
cached_tokens_.pop_front();
if (token.expiration > now_plus_five_mins) {
cached_tokens_.push_back(std::move(token));
}
}
}
} | #include "quiche/blind_sign_auth/cached_blind_sign_auth.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/test_tools/mock_blind_sign_auth_interface.h"
#include "quiche/common/platform/api/quiche_mutex.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
namespace quiche {
namespace test {
namespace {
using ::testing::_;
using ::testing::InvokeArgument;
using ::testing::Unused;
class CachedBlindSignAuthTest : public QuicheTest {
protected:
void SetUp() override {
cached_blind_sign_auth_ =
std::make_unique<CachedBlindSignAuth>(&mock_blind_sign_auth_interface_);
}
void TearDown() override {
fake_tokens_.clear();
cached_blind_sign_auth_.reset();
}
public:
std::vector<BlindSignToken> MakeFakeTokens(int num_tokens) {
std::vector<BlindSignToken> fake_tokens;
for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) {
fake_tokens.push_back(BlindSignToken{absl::StrCat("token:", i),
absl::Now() + absl::Hours(1)});
}
return fake_tokens;
}
std::vector<BlindSignToken> MakeExpiredTokens(int num_tokens) {
std::vector<BlindSignToken> fake_tokens;
for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) {
fake_tokens.push_back(BlindSignToken{absl::StrCat("token:", i),
absl::Now() - absl::Hours(1)});
}
return fake_tokens;
}
MockBlindSignAuthInterface mock_blind_sign_auth_interface_;
std::unique_ptr<CachedBlindSignAuth> cached_blind_sign_auth_;
std::optional<std::string> oauth_token_ = "oauth_token";
std::vector<BlindSignToken> fake_tokens_;
};
TEST_F(CachedBlindSignAuthTest, TestGetTokensOneCallSuccessful) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(1)
.WillOnce([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeFakeTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = 5;
QuicheNotification done;
SignedTokenCallback callback =
[num_tokens, &done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i));
}
done.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));
done.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensMultipleRemoteCallsSuccessful) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(2)
.WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeFakeTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens - 1;
QuicheNotification first;
SignedTokenCallback first_callback =
[num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i));
}
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
QuicheNotification second;
SignedTokenCallback second_callback =
[num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
EXPECT_EQ(tokens->at(0).token,
absl::StrCat("token:", kBlindSignAuthRequestMaxTokens - 1));
for (int i = 1; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i - 1));
}
second.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));
second.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensSecondRequestFilledFromCache) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(1)
.WillOnce([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeFakeTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens / 2;
QuicheNotification first;
SignedTokenCallback first_callback =
[num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i));
}
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
QuicheNotification second;
SignedTokenCallback second_callback =
[num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token,
absl::StrCat("token:", i + num_tokens));
}
second.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));
second.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensThirdRequestRefillsCache) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(2)
.WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeFakeTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens / 2;
QuicheNotification first;
SignedTokenCallback first_callback =
[num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i));
}
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
QuicheNotification second;
SignedTokenCallback second_callback =
[num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(num_tokens, tokens->size());
for (int i = 0; i < num_tokens; i++) {
EXPECT_EQ(tokens->at(i).token,
absl::StrCat("token:", i + num_tokens));
}
second.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));
second.WaitForNotification();
QuicheNotification third;
int third_request_tokens = 10;
SignedTokenCallback third_callback =
[third_request_tokens,
&third](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(third_request_tokens, tokens->size());
for (int i = 0; i < third_request_tokens; i++) {
EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i));
}
third.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, third_request_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(third_callback));
third.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensRequestTooLarge) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(0);
int num_tokens = kBlindSignAuthRequestMaxTokens + 1;
SignedTokenCallback callback =
[](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
EXPECT_THAT(
tokens.status().message(),
absl::StrFormat("Number of tokens requested exceeds maximum: %d",
kBlindSignAuthRequestMaxTokens));
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensRequestNegative) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(0);
int num_tokens = -1;
SignedTokenCallback callback =
[num_tokens](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
EXPECT_THAT(tokens.status().message(),
absl::StrFormat("Negative number of tokens requested: %d",
num_tokens));
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));
}
TEST_F(CachedBlindSignAuthTest, TestHandleGetTokensResponseErrorHandling) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(2)
.WillOnce([](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
std::move(callback)(absl::InternalError("AuthAndSign failed"));
})
.WillOnce([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeFakeTokens(num_tokens);
fake_tokens_.pop_back();
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens;
QuicheNotification first;
SignedTokenCallback first_callback =
[&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);
EXPECT_THAT(tokens.status().message(), "AuthAndSign failed");
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
QuicheNotification second;
SignedTokenCallback second_callback =
[&second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(),
absl::StatusCode::kResourceExhausted);
second.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));
second.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestGetTokensZeroTokensRequested) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(0);
int num_tokens = 0;
SignedTokenCallback callback =
[](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
EXPECT_EQ(tokens->size(), 0);
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback));
}
TEST_F(CachedBlindSignAuthTest, TestExpiredTokensArePruned) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(1)
.WillOnce([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeExpiredTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens;
QuicheNotification first;
SignedTokenCallback first_callback =
[&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(),
absl::StatusCode::kResourceExhausted);
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
}
TEST_F(CachedBlindSignAuthTest, TestClearCacheRemovesTokens) {
EXPECT_CALL(mock_blind_sign_auth_interface_,
GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _))
.Times(2)
.WillRepeatedly([this](Unused, int num_tokens, Unused, Unused,
SignedTokenCallback callback) {
fake_tokens_ = MakeExpiredTokens(num_tokens);
std::move(callback)(absl::MakeSpan(fake_tokens_));
});
int num_tokens = kBlindSignAuthRequestMaxTokens / 2;
QuicheNotification first;
SignedTokenCallback first_callback =
[&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(),
absl::StatusCode::kResourceExhausted);
first.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback));
first.WaitForNotification();
cached_blind_sign_auth_->ClearCache();
QuicheNotification second;
SignedTokenCallback second_callback =
[&second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(),
absl::StatusCode::kResourceExhausted);
second.Notify();
};
cached_blind_sign_auth_->GetTokens(
oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback));
second.WaitForNotification();
}
}
}
} |
453 | cpp | google/quiche | blind_sign_auth | quiche/blind_sign_auth/blind_sign_auth.cc | quiche/blind_sign_auth/blind_sign_auth_test.cc | #ifndef QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_
#define QUICHE_BLIND_SIGN_AUTH_BLIND_SIGN_AUTH_H_
#include <memory>
#include <optional>
#include <string>
#include "absl/status/statusor.h"
#include "absl/time/time.h"
#include "anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche {
class QUICHE_EXPORT BlindSignAuth : public BlindSignAuthInterface {
public:
explicit BlindSignAuth(BlindSignMessageInterface* fetcher,
privacy::ppn::BlindSignAuthOptions auth_options)
: fetcher_(fetcher), auth_options_(std::move(auth_options)) {}
void GetTokens(std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback) override;
private:
void GetInitialDataCallback(
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response);
void GeneratePrivacyPassTokens(
privacy::ppn::GetInitialDataResponse initial_data_response,
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback);
void PrivacyPassAuthAndSignCallback(
std::string encoded_extensions, absl::Time public_key_expiry_time,
anonymous_tokens::GeoHint geo_hint,
anonymous_tokens::AnonymousTokensUseCase use_case,
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response);
privacy::ppn::ProxyLayer QuicheProxyLayerToPpnProxyLayer(
quiche::ProxyLayer proxy_layer);
BlindSignMessageInterface* fetcher_ = nullptr;
privacy::ppn::BlindSignAuthOptions auth_options_;
};
std::string BlindSignAuthServiceTypeToString(
quiche::BlindSignAuthServiceType service_type);
}
#endif
#include "quiche/blind_sign_auth/blind_sign_auth.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/functional/bind_front.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "anonymous_tokens/cpp/crypto/crypto_utils.h"
#include "anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "anonymous_tokens/cpp/shared/proto_utils.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_random.h"
namespace quiche {
namespace {
template <typename T>
std::string OmitDefault(T value) {
return value == 0 ? "" : absl::StrCat(value);
}
constexpr absl::string_view kIssuerHostname =
"https:
}
void BlindSignAuth::GetTokens(std::optional<std::string> oauth_token,
int num_tokens, ProxyLayer proxy_layer,
BlindSignAuthServiceType service_type,
SignedTokenCallback callback) {
privacy::ppn::GetInitialDataRequest request;
request.set_use_attestation(false);
request.set_service_type(BlindSignAuthServiceTypeToString(service_type));
request.set_location_granularity(
privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);
request.set_validation_version(2);
request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));
std::string body = request.SerializeAsString();
BlindSignMessageCallback initial_data_callback = absl::bind_front(
&BlindSignAuth::GetInitialDataCallback, this, oauth_token, num_tokens,
proxy_layer, service_type, std::move(callback));
fetcher_->DoRequest(BlindSignMessageRequestType::kGetInitialData, oauth_token,
body, std::move(initial_data_callback));
}
void BlindSignAuth::GetInitialDataCallback(
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response) {
if (!response.ok()) {
QUICHE_LOG(WARNING) << "GetInitialDataRequest failed: "
<< response.status();
std::move(callback)(response.status());
return;
}
absl::StatusCode code = response->status_code();
if (code != absl::StatusCode::kOk) {
std::string message =
absl::StrCat("GetInitialDataRequest failed with code: ", code);
QUICHE_LOG(WARNING) << message;
std::move(callback)(absl::Status(code, message));
return;
}
privacy::ppn::GetInitialDataResponse initial_data_response;
if (!initial_data_response.ParseFromString(response->body())) {
QUICHE_LOG(WARNING) << "Failed to parse GetInitialDataResponse";
std::move(callback)(
absl::InternalError("Failed to parse GetInitialDataResponse"));
return;
}
bool use_privacy_pass_client =
initial_data_response.has_privacy_pass_data() &&
auth_options_.enable_privacy_pass();
if (use_privacy_pass_client) {
QUICHE_DVLOG(1) << "Using Privacy Pass client";
GeneratePrivacyPassTokens(initial_data_response, std::move(oauth_token),
num_tokens, proxy_layer, service_type,
std::move(callback));
} else {
QUICHE_LOG(ERROR) << "Non-Privacy Pass tokens are no longer supported";
std::move(callback)(absl::UnimplementedError(
"Non-Privacy Pass tokens are no longer supported"));
}
}
void BlindSignAuth::GeneratePrivacyPassTokens(
privacy::ppn::GetInitialDataResponse initial_data_response,
std::optional<std::string> oauth_token, int num_tokens,
ProxyLayer proxy_layer, BlindSignAuthServiceType service_type,
SignedTokenCallback callback) {
anonymous_tokens::RSAPublicKey public_key_proto;
if (!public_key_proto.ParseFromString(
initial_data_response.at_public_metadata_public_key()
.serialized_public_key())) {
std::move(callback)(
absl::InvalidArgumentError("Failed to parse Privacy Pass public key"));
return;
}
absl::StatusOr<bssl::UniquePtr<RSA>> bssl_rsa_key =
anonymous_tokens::CreatePublicKeyRSA(
public_key_proto.n(), public_key_proto.e());
if (!bssl_rsa_key.ok()) {
std::move(callback)(bssl_rsa_key.status());
return;
}
absl::StatusOr<anonymous_tokens::Extensions> extensions =
anonymous_tokens::DecodeExtensions(
initial_data_response.privacy_pass_data()
.public_metadata_extensions());
if (!extensions.ok()) {
QUICHE_LOG(WARNING) << "Failed to decode extensions: "
<< extensions.status();
std::move(callback)(extensions.status());
return;
}
std::vector<uint16_t> kExpectedExtensionTypes = {
0x0001, 0x0002,
0xF001, 0xF002, 0xF003};
absl::Status result =
anonymous_tokens::ValidateExtensionsOrderAndValues(
*extensions, absl::MakeSpan(kExpectedExtensionTypes), absl::Now());
if (!result.ok()) {
QUICHE_LOG(WARNING) << "Failed to validate extensions: " << result;
std::move(callback)(result);
return;
}
absl::StatusOr<anonymous_tokens::ExpirationTimestamp>
expiration_timestamp = anonymous_tokens::
ExpirationTimestamp::FromExtension(extensions->extensions.at(0));
if (!expiration_timestamp.ok()) {
QUICHE_LOG(WARNING) << "Failed to parse expiration timestamp: "
<< expiration_timestamp.status();
std::move(callback)(expiration_timestamp.status());
return;
}
absl::Time public_metadata_expiry_time =
absl::FromUnixSeconds(expiration_timestamp->timestamp);
absl::StatusOr<anonymous_tokens::GeoHint> geo_hint =
anonymous_tokens::GeoHint::FromExtension(
extensions->extensions.at(1));
QUICHE_CHECK(geo_hint.ok());
anonymous_tokens::TokenChallenge challenge;
challenge.issuer_name = kIssuerHostname;
absl::StatusOr<std::string> token_challenge =
anonymous_tokens::MarshalTokenChallenge(challenge);
if (!token_challenge.ok()) {
QUICHE_LOG(WARNING) << "Failed to marshal token challenge: "
<< token_challenge.status();
std::move(callback)(token_challenge.status());
return;
}
QuicheRandom* random = QuicheRandom::GetInstance();
std::vector<anonymous_tokens::ExtendedTokenRequest>
extended_token_requests;
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients;
std::vector<std::string> privacy_pass_blinded_tokens;
for (int i = 0; i < num_tokens; i++) {
auto client = anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient::Create(*bssl_rsa_key.value());
if (!client.ok()) {
QUICHE_LOG(WARNING) << "Failed to create Privacy Pass client: "
<< client.status();
std::move(callback)(client.status());
return;
}
std::string nonce_rand(32, '\0');
random->RandBytes(nonce_rand.data(), nonce_rand.size());
absl::StatusOr<anonymous_tokens::ExtendedTokenRequest>
extended_token_request = client.value()->CreateTokenRequest(
*token_challenge, nonce_rand,
initial_data_response.privacy_pass_data().token_key_id(),
*extensions);
if (!extended_token_request.ok()) {
QUICHE_LOG(WARNING) << "Failed to create ExtendedTokenRequest: "
<< extended_token_request.status();
std::move(callback)(extended_token_request.status());
return;
}
privacy_pass_clients.push_back(*std::move(client));
extended_token_requests.push_back(*extended_token_request);
privacy_pass_blinded_tokens.push_back(absl::Base64Escape(
extended_token_request->request.blinded_token_request));
}
privacy::ppn::AuthAndSignRequest sign_request;
sign_request.set_service_type(BlindSignAuthServiceTypeToString(service_type));
sign_request.set_key_type(privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);
sign_request.set_key_version(
initial_data_response.at_public_metadata_public_key().key_version());
sign_request.mutable_blinded_token()->Assign(
privacy_pass_blinded_tokens.begin(), privacy_pass_blinded_tokens.end());
sign_request.mutable_public_metadata_extensions()->assign(
initial_data_response.privacy_pass_data().public_metadata_extensions());
sign_request.set_do_not_use_rsa_public_exponent(true);
sign_request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer));
absl::StatusOr<anonymous_tokens::AnonymousTokensUseCase>
use_case = anonymous_tokens::ParseUseCase(
initial_data_response.at_public_metadata_public_key().use_case());
if (!use_case.ok()) {
QUICHE_LOG(WARNING) << "Failed to parse use case: " << use_case.status();
std::move(callback)(use_case.status());
return;
}
BlindSignMessageCallback auth_and_sign_callback =
absl::bind_front(&BlindSignAuth::PrivacyPassAuthAndSignCallback, this,
std::move(initial_data_response.privacy_pass_data()
.public_metadata_extensions()),
public_metadata_expiry_time, *geo_hint, *use_case,
std::move(privacy_pass_clients), std::move(callback));
fetcher_->DoRequest(BlindSignMessageRequestType::kAuthAndSign, oauth_token,
sign_request.SerializeAsString(),
std::move(auth_and_sign_callback));
}
void BlindSignAuth::PrivacyPassAuthAndSignCallback(
std::string encoded_extensions, absl::Time public_key_expiry_time,
anonymous_tokens::GeoHint geo_hint,
anonymous_tokens::AnonymousTokensUseCase use_case,
std::vector<std::unique_ptr<anonymous_tokens::
PrivacyPassRsaBssaPublicMetadataClient>>
privacy_pass_clients,
SignedTokenCallback callback,
absl::StatusOr<BlindSignMessageResponse> response) {
if (!response.ok()) {
QUICHE_LOG(WARNING) << "AuthAndSign failed: " << response.status();
std::move(callback)(response.status());
return;
}
absl::StatusCode code = response->status_code();
if (code != absl::StatusCode::kOk) {
std::string message = absl::StrCat("AuthAndSign failed with code: ", code);
QUICHE_LOG(WARNING) << message;
std::move(callback)(absl::Status(code, message));
return;
}
privacy::ppn::AuthAndSignResponse sign_response;
if (!sign_response.ParseFromString(response->body())) {
QUICHE_LOG(WARNING) << "Failed to parse AuthAndSignResponse";
std::move(callback)(
absl::InternalError("Failed to parse AuthAndSignResponse"));
return;
}
if (static_cast<size_t>(sign_response.blinded_token_signature_size()) !=
privacy_pass_clients.size()) {
QUICHE_LOG(WARNING) << "Number of signatures does not equal number of "
"Privacy Pass tokens sent";
std::move(callback)(
absl::InternalError("Number of signatures does not equal number of "
"Privacy Pass tokens sent"));
return;
}
std::vector<BlindSignToken> tokens_vec;
for (int i = 0; i < sign_response.blinded_token_signature_size(); i++) {
std::string unescaped_blinded_sig;
if (!absl::Base64Unescape(sign_response.blinded_token_signature()[i],
&unescaped_blinded_sig)) {
QUICHE_LOG(WARNING) << "Failed to unescape blinded signature";
std::move(callback)(
absl::InternalError("Failed to unescape blinded signature"));
return;
}
absl::StatusOr<anonymous_tokens::Token> token =
privacy_pass_clients[i]->FinalizeToken(unescaped_blinded_sig);
if (!token.ok()) {
QUICHE_LOG(WARNING) << "Failed to finalize token: " << token.status();
std::move(callback)(token.status());
return;
}
absl::StatusOr<std::string> marshaled_token =
anonymous_tokens::MarshalToken(*token);
if (!marshaled_token.ok()) {
QUICHE_LOG(WARNING) << "Failed to marshal token: "
<< marshaled_token.status();
std::move(callback)(marshaled_token.status());
return;
}
privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;
privacy_pass_token_data.mutable_token()->assign(
absl::WebSafeBase64Escape(*marshaled_token));
privacy_pass_token_data.mutable_encoded_extensions()->assign(
absl::WebSafeBase64Escape(encoded_extensions));
privacy_pass_token_data.set_use_case_override(use_case);
tokens_vec.push_back(
BlindSignToken{privacy_pass_token_data.SerializeAsString(),
public_key_expiry_time, geo_hint});
}
std::move(callback)(absl::Span<BlindSignToken>(tokens_vec));
}
privacy::ppn::ProxyLayer BlindSignAuth::QuicheProxyLayerToPpnProxyLayer(
quiche::ProxyLayer proxy_layer) {
switch (proxy_layer) {
case ProxyLayer::kProxyA: {
return privacy::ppn::ProxyLayer::PROXY_A;
}
case ProxyLayer::kProxyB: {
return privacy::ppn::ProxyLayer::PROXY_B;
}
}
}
std::string BlindSignAuthServiceTypeToString(
quiche::BlindSignAuthServiceType service_type) {
switch (service_type) {
case BlindSignAuthServiceType::kChromeIpBlinding: {
return "chromeipblinding";
}
case BlindSignAuthServiceType::kCronetIpBlinding: {
return "cronetipblinding";
}
case BlindSignAuthServiceType::kWebviewIpBlinding: {
return "chromeipblinding";
}
}
}
} | #include "quiche/blind_sign_auth/blind_sign_auth.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "anonymous_tokens/cpp/crypto/crypto_utils.h"
#include "anonymous_tokens/cpp/privacy_pass/token_encodings.h"
#include "anonymous_tokens/cpp/testing/utils.h"
#include "openssl/base.h"
#include "openssl/digest.h"
#include "quiche/blind_sign_auth/blind_sign_auth_interface.h"
#include "quiche/blind_sign_auth/blind_sign_auth_protos.h"
#include "quiche/blind_sign_auth/blind_sign_message_interface.h"
#include "quiche/blind_sign_auth/blind_sign_message_response.h"
#include "quiche/blind_sign_auth/test_tools/mock_blind_sign_message_interface.h"
#include "quiche/common/platform/api/quiche_mutex.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
namespace quiche {
namespace test {
namespace {
using ::testing::_;
using ::testing::Eq;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::StartsWith;
using ::testing::Unused;
class BlindSignAuthTest : public QuicheTest {
protected:
void SetUp() override {
auto [test_rsa_public_key, test_rsa_private_key] =
anonymous_tokens::GetStrongTestRsaKeyPair2048();
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
rsa_public_key_,
anonymous_tokens::CreatePublicKeyRSA(
test_rsa_public_key.n, test_rsa_public_key.e));
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
rsa_private_key_,
anonymous_tokens::CreatePrivateKeyRSA(
test_rsa_private_key.n, test_rsa_private_key.e,
test_rsa_private_key.d, test_rsa_private_key.p,
test_rsa_private_key.q, test_rsa_private_key.dp,
test_rsa_private_key.dq, test_rsa_private_key.crt));
anonymous_tokens::RSAPublicKey public_key;
public_key.set_n(test_rsa_public_key.n);
public_key.set_e(test_rsa_public_key.e);
public_key_proto_.set_key_version(1);
public_key_proto_.set_use_case("TEST_USE_CASE");
public_key_proto_.set_serialized_public_key(public_key.SerializeAsString());
public_key_proto_.set_sig_hash_type(
anonymous_tokens::AT_HASH_TYPE_SHA384);
public_key_proto_.set_mask_gen_function(
anonymous_tokens::AT_MGF_SHA384);
public_key_proto_.set_salt_length(48);
public_key_proto_.set_key_size(256);
public_key_proto_.set_message_mask_type(
anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);
public_key_proto_.set_message_mask_size(0);
expected_get_initial_data_request_.set_use_attestation(false);
expected_get_initial_data_request_.set_service_type("chromeipblinding");
expected_get_initial_data_request_.set_location_granularity(
privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS);
expected_get_initial_data_request_.set_validation_version(2);
expected_get_initial_data_request_.set_proxy_layer(privacy::ppn::PROXY_A);
privacy::ppn::GetInitialDataResponse fake_get_initial_data_response;
*fake_get_initial_data_response.mutable_at_public_metadata_public_key() =
public_key_proto_;
fake_get_initial_data_response_ = fake_get_initial_data_response;
privacy::ppn::GetInitialDataResponse::PrivacyPassData privacy_pass_data;
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
std::string public_key_der,
anonymous_tokens::RsaSsaPssPublicKeyToDerEncoding(
rsa_public_key_.get()));
const EVP_MD* sha256 = EVP_sha256();
ANON_TOKENS_ASSERT_OK_AND_ASSIGN(
token_key_id_, anonymous_tokens::ComputeHash(
public_key_der, *sha256));
anonymous_tokens::ExpirationTimestamp
expiration_timestamp;
int64_t one_hour_away = absl::ToUnixSeconds(absl::Now() + absl::Hours(1));
expiration_timestamp.timestamp = one_hour_away - (one_hour_away % 900);
expiration_timestamp.timestamp_precision = 900;
absl::StatusOr<anonymous_tokens::Extension>
expiration_extension = expiration_timestamp.AsExtension();
QUICHE_EXPECT_OK(expiration_extension);
extensions_.extensions.push_back(*expiration_extension);
anonymous_tokens::GeoHint geo_hint;
geo_hint.geo_hint = "US,US-AL,ALABASTER";
absl::StatusOr<anonymous_tokens::Extension>
geo_hint_extension = geo_hint.AsExtension();
QUICHE_EXPECT_OK(geo_hint_extension);
extensions_.extensions.push_back(*geo_hint_extension);
anonymous_tokens::ServiceType service_type;
service_type.service_type_id =
anonymous_tokens::ServiceType::kChromeIpBlinding;
absl::StatusOr<anonymous_tokens::Extension>
service_type_extension = service_type.AsExtension();
QUICHE_EXPECT_OK(service_type_extension);
extensions_.extensions.push_back(*service_type_extension);
anonymous_tokens::DebugMode debug_mode;
debug_mode.mode = anonymous_tokens::DebugMode::kDebug;
absl::StatusOr<anonymous_tokens::Extension>
debug_mode_extension = debug_mode.AsExtension();
QUICHE_EXPECT_OK(debug_mode_extension);
extensions_.extensions.push_back(*debug_mode_extension);
anonymous_tokens::ProxyLayer proxy_layer;
proxy_layer.layer =
anonymous_tokens::ProxyLayer::kProxyA;
absl::StatusOr<anonymous_tokens::Extension>
proxy_layer_extension = proxy_layer.AsExtension();
QUICHE_EXPECT_OK(proxy_layer_extension);
extensions_.extensions.push_back(*proxy_layer_extension);
absl::StatusOr<std::string> serialized_extensions =
anonymous_tokens::EncodeExtensions(extensions_);
QUICHE_EXPECT_OK(serialized_extensions);
privacy_pass_data.set_token_key_id(token_key_id_);
privacy_pass_data.set_public_metadata_extensions(*serialized_extensions);
*fake_get_initial_data_response.mutable_public_metadata_info() =
public_metadata_info_;
*fake_get_initial_data_response.mutable_privacy_pass_data() =
privacy_pass_data;
fake_get_initial_data_response_ = fake_get_initial_data_response;
privacy::ppn::BlindSignAuthOptions options;
options.set_enable_privacy_pass(true);
blind_sign_auth_ =
std::make_unique<BlindSignAuth>(&mock_message_interface_, options);
}
void TearDown() override { blind_sign_auth_.reset(nullptr); }
public:
void CreateSignResponse(const std::string& body, bool use_privacy_pass) {
privacy::ppn::AuthAndSignRequest request;
ASSERT_TRUE(request.ParseFromString(body));
EXPECT_EQ(request.service_type(), "chromeipblinding");
EXPECT_EQ(request.key_type(), privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE);
EXPECT_EQ(request.public_key_hash(), "");
EXPECT_EQ(request.key_version(), public_key_proto_.key_version());
EXPECT_EQ(request.do_not_use_rsa_public_exponent(), true);
EXPECT_NE(request.blinded_token().size(), 0);
if (use_privacy_pass) {
EXPECT_EQ(request.public_metadata_extensions(),
fake_get_initial_data_response_.privacy_pass_data()
.public_metadata_extensions());
} else {
EXPECT_EQ(request.public_metadata_info().SerializeAsString(),
public_metadata_info_.SerializeAsString());
}
privacy::ppn::AuthAndSignResponse response;
for (const auto& request_token : request.blinded_token()) {
std::string decoded_blinded_token;
ASSERT_TRUE(absl::Base64Unescape(request_token, &decoded_blinded_token));
if (use_privacy_pass) {
absl::StatusOr<std::string> signature =
anonymous_tokens::TestSignWithPublicMetadata(
decoded_blinded_token, request.public_metadata_extensions(),
*rsa_private_key_, false);
QUICHE_EXPECT_OK(signature);
response.add_blinded_token_signature(absl::Base64Escape(*signature));
} else {
absl::StatusOr<std::string> serialized_token =
anonymous_tokens::TestSign(
decoded_blinded_token, rsa_private_key_.get());
QUICHE_EXPECT_OK(serialized_token);
response.add_blinded_token_signature(
absl::Base64Escape(*serialized_token));
}
}
sign_response_ = response;
}
void ValidateGetTokensOutput(absl::Span<BlindSignToken> tokens) {
for (const auto& token : tokens) {
privacy::ppn::SpendTokenData spend_token_data;
ASSERT_TRUE(spend_token_data.ParseFromString(token.token));
EXPECT_EQ(spend_token_data.public_metadata().SerializeAsString(),
public_metadata_info_.public_metadata().SerializeAsString());
EXPECT_THAT(spend_token_data.unblinded_token(), StartsWith("blind:"));
EXPECT_GE(spend_token_data.unblinded_token_signature().size(),
spend_token_data.unblinded_token().size());
EXPECT_EQ(spend_token_data.signing_key_version(),
public_key_proto_.key_version());
EXPECT_NE(spend_token_data.use_case(),
anonymous_tokens::AnonymousTokensUseCase::
ANONYMOUS_TOKENS_USE_CASE_UNDEFINED);
EXPECT_NE(spend_token_data.message_mask(), "");
}
}
void ValidatePrivacyPassTokensOutput(absl::Span<BlindSignToken> tokens) {
for (const auto& token : tokens) {
privacy::ppn::PrivacyPassTokenData privacy_pass_token_data;
ASSERT_TRUE(privacy_pass_token_data.ParseFromString(token.token));
std::string decoded_token;
ASSERT_TRUE(absl::WebSafeBase64Unescape(privacy_pass_token_data.token(),
&decoded_token));
std::string decoded_extensions;
ASSERT_TRUE(absl::WebSafeBase64Unescape(
privacy_pass_token_data.encoded_extensions(), &decoded_extensions));
EXPECT_EQ(token.geo_hint.geo_hint, "US,US-AL,ALABASTER");
EXPECT_EQ(token.geo_hint.country_code, "US");
EXPECT_EQ(token.geo_hint.region, "US-AL");
EXPECT_EQ(token.geo_hint.city, "ALABASTER");
}
}
MockBlindSignMessageInterface mock_message_interface_;
std::unique_ptr<BlindSignAuth> blind_sign_auth_;
anonymous_tokens::RSABlindSignaturePublicKey
public_key_proto_;
bssl::UniquePtr<RSA> rsa_public_key_;
bssl::UniquePtr<RSA> rsa_private_key_;
std::string token_key_id_;
anonymous_tokens::Extensions extensions_;
privacy::ppn::PublicMetadataInfo public_metadata_info_;
privacy::ppn::AuthAndSignResponse sign_response_;
privacy::ppn::GetInitialDataResponse fake_get_initial_data_response_;
std::string oauth_token_ = "oauth_token";
privacy::ppn::GetInitialDataRequest expected_get_initial_data_request_;
};
TEST_F(BlindSignAuthTest, TestGetTokensFailedNetworkError) {
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(
absl::InternalError("Failed to create socket"));
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))
.Times(0);
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestGetTokensFailedBadGetInitialDataResponse) {
*fake_get_initial_data_response_.mutable_at_public_metadata_public_key()
->mutable_use_case() = "SPAM";
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
EXPECT_CALL(
mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _))
.Times(0);
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestGetTokensFailedBadAuthAndSignResponse) {
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
{
InSequence seq;
EXPECT_CALL(
mock_message_interface_,
DoRequest(
Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce(Invoke([this](Unused, Unused, const std::string& body,
BlindSignMessageCallback callback) {
CreateSignResponse(body, false);
sign_response_.add_blinded_token_signature("invalid_signature%");
BlindSignMessageResponse response(absl::StatusCode::kOk,
sign_response_.SerializeAsString());
std::move(callback)(response);
}));
}
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensSucceeds) {
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
{
InSequence seq;
EXPECT_CALL(
mock_message_interface_,
DoRequest(
Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
EXPECT_CALL(mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign),
Eq(oauth_token_), _, _))
.Times(1)
.WillOnce(Invoke([this](Unused, Unused, const std::string& body,
BlindSignMessageCallback callback) {
CreateSignResponse(body, true);
BlindSignMessageResponse response(absl::StatusCode::kOk,
sign_response_.SerializeAsString());
std::move(callback)(response);
}));
}
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[this, &done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
QUICHE_EXPECT_OK(tokens);
ValidatePrivacyPassTokensOutput(*tokens);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensFailsWithBadExtensions) {
privacy::ppn::BlindSignAuthOptions options;
options.set_enable_privacy_pass(true);
blind_sign_auth_ =
std::make_unique<BlindSignAuth>(&mock_message_interface_, options);
public_key_proto_.set_message_mask_type(
anonymous_tokens::AT_MESSAGE_MASK_NO_MASK);
public_key_proto_.set_message_mask_size(0);
*fake_get_initial_data_response_.mutable_at_public_metadata_public_key() =
public_key_proto_;
fake_get_initial_data_response_.mutable_privacy_pass_data()
->set_public_metadata_extensions("spam");
BlindSignMessageResponse fake_public_key_response(
absl::StatusCode::kOk,
fake_get_initial_data_response_.SerializeAsString());
EXPECT_CALL(
mock_message_interface_,
DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData),
Eq(oauth_token_),
Eq(expected_get_initial_data_request_.SerializeAsString()), _))
.Times(1)
.WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) {
std::move(get_initial_data_cb)(fake_public_key_response);
});
int num_tokens = 1;
QuicheNotification done;
SignedTokenCallback callback =
[&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) {
EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument);
done.Notify();
};
blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA,
BlindSignAuthServiceType::kChromeIpBlinding,
std::move(callback));
done.WaitForNotification();
}
}
}
} |
454 | cpp | google/quiche | header_properties | quiche/balsa/header_properties.cc | quiche/balsa/header_properties_test.cc | #ifndef QUICHE_BALSA_HEADER_PROPERTIES_H_
#define QUICHE_BALSA_HEADER_PROPERTIES_H_
#include <cstdint>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche::header_properties {
QUICHE_EXPORT bool IsMultivaluedHeader(absl::string_view header);
inline constexpr char kInvalidHeaderKeyCharList[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
0x1E, 0x1F, ' ', '"', '(', ')', ',', '/', ';', '<',
'=', '>', '?', '@', '[', '\\', ']', '{', '}', 0x7F};
inline constexpr char kInvalidHeaderKeyCharListAllowDoubleQuote[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
0x1E, 0x1F, ' ', '(', ')', ',', '/', ';', '<', '=',
'>', '?', '@', '[', '\\', ']', '{', '}', 0x7F};
inline constexpr char kInvalidHeaderCharList[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x0B,
0x0C, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x7F};
QUICHE_EXPORT bool IsInvalidHeaderKeyChar(uint8_t c);
QUICHE_EXPORT bool IsInvalidHeaderKeyCharAllowDoubleQuote(uint8_t c);
QUICHE_EXPORT bool IsInvalidHeaderChar(uint8_t c);
QUICHE_EXPORT bool HasInvalidHeaderChars(absl::string_view value);
}
#endif
#include "quiche/balsa/header_properties.h"
#include <array>
#include "absl/container/flat_hash_set.h"
#include "absl/strings/string_view.h"
#include "quiche/common/quiche_text_utils.h"
namespace quiche::header_properties {
namespace {
using MultivaluedHeadersSet =
absl::flat_hash_set<absl::string_view, StringPieceCaseHash,
StringPieceCaseEqual>;
MultivaluedHeadersSet* buildMultivaluedHeaders() {
return new MultivaluedHeadersSet({
"accept",
"accept-charset",
"accept-encoding",
"accept-language",
"accept-ranges",
"access-control-allow-headers",
"access-control-allow-methods",
"access-control-expose-headers",
"access-control-request-headers",
"allow",
"cache-control",
"cdn-cache-control",
"connection",
"content-encoding",
"content-language",
"expect",
"if-match",
"if-none-match",
"link",
"pragma",
"proxy-authenticate",
"te",
"sec-websocket-extensions",
"set-cookie",
"trailer",
"transfer-encoding",
"upgrade",
"vary",
"via",
"warning",
"www-authenticate",
"x-forwarded-for",
"x-go" "ogle-cache-control",
});
}
std::array<bool, 256> buildInvalidHeaderKeyCharLookupTable() {
std::array<bool, 256> invalidCharTable;
invalidCharTable.fill(false);
for (uint8_t c : kInvalidHeaderKeyCharList) {
invalidCharTable[c] = true;
}
return invalidCharTable;
}
std::array<bool, 256> buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote() {
std::array<bool, 256> invalidCharTable;
invalidCharTable.fill(false);
for (uint8_t c : kInvalidHeaderKeyCharListAllowDoubleQuote) {
invalidCharTable[c] = true;
}
return invalidCharTable;
}
std::array<bool, 256> buildInvalidCharLookupTable() {
std::array<bool, 256> invalidCharTable;
invalidCharTable.fill(false);
for (uint8_t c : kInvalidHeaderCharList) {
invalidCharTable[c] = true;
}
return invalidCharTable;
}
}
bool IsMultivaluedHeader(absl::string_view header) {
static const MultivaluedHeadersSet* const multivalued_headers =
buildMultivaluedHeaders();
return multivalued_headers->contains(header);
}
bool IsInvalidHeaderKeyChar(uint8_t c) {
static const std::array<bool, 256> invalidHeaderKeyCharTable =
buildInvalidHeaderKeyCharLookupTable();
return invalidHeaderKeyCharTable[c];
}
bool IsInvalidHeaderKeyCharAllowDoubleQuote(uint8_t c) {
static const std::array<bool, 256> invalidHeaderKeyCharTable =
buildInvalidHeaderKeyCharLookupTableAllowDoubleQuote();
return invalidHeaderKeyCharTable[c];
}
bool IsInvalidHeaderChar(uint8_t c) {
static const std::array<bool, 256> invalidCharTable =
buildInvalidCharLookupTable();
return invalidCharTable[c];
}
bool HasInvalidHeaderChars(absl::string_view value) {
for (const char c : value) {
if (IsInvalidHeaderChar(c)) {
return true;
}
}
return false;
}
} | #include "quiche/balsa/header_properties.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quiche::header_properties::test {
namespace {
TEST(HeaderPropertiesTest, IsMultivaluedHeaderIsCaseInsensitive) {
EXPECT_TRUE(IsMultivaluedHeader("content-encoding"));
EXPECT_TRUE(IsMultivaluedHeader("Content-Encoding"));
EXPECT_TRUE(IsMultivaluedHeader("set-cookie"));
EXPECT_TRUE(IsMultivaluedHeader("sEt-cOOkie"));
EXPECT_TRUE(IsMultivaluedHeader("X-Goo" "gle-Cache-Control"));
EXPECT_TRUE(IsMultivaluedHeader("access-control-expose-HEADERS"));
EXPECT_FALSE(IsMultivaluedHeader("set-cook"));
EXPECT_FALSE(IsMultivaluedHeader("content-length"));
EXPECT_FALSE(IsMultivaluedHeader("Content-Length"));
}
TEST(HeaderPropertiesTest, IsInvalidHeaderKeyChar) {
EXPECT_TRUE(IsInvalidHeaderKeyChar(0x00));
EXPECT_TRUE(IsInvalidHeaderKeyChar(0x06));
EXPECT_TRUE(IsInvalidHeaderKeyChar(0x09));
EXPECT_TRUE(IsInvalidHeaderKeyChar(0x1F));
EXPECT_TRUE(IsInvalidHeaderKeyChar(0x7F));
EXPECT_TRUE(IsInvalidHeaderKeyChar(' '));
EXPECT_TRUE(IsInvalidHeaderKeyChar('"'));
EXPECT_TRUE(IsInvalidHeaderKeyChar('\t'));
EXPECT_TRUE(IsInvalidHeaderKeyChar('\r'));
EXPECT_TRUE(IsInvalidHeaderKeyChar('\n'));
EXPECT_TRUE(IsInvalidHeaderKeyChar('}'));
EXPECT_FALSE(IsInvalidHeaderKeyChar('a'));
EXPECT_FALSE(IsInvalidHeaderKeyChar('B'));
EXPECT_FALSE(IsInvalidHeaderKeyChar('7'));
EXPECT_FALSE(IsInvalidHeaderKeyChar(0x42));
EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7C));
EXPECT_FALSE(IsInvalidHeaderKeyChar(0x7E));
}
TEST(HeaderPropertiesTest, IsInvalidHeaderKeyCharAllowDoubleQuote) {
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x00));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x06));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x09));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x1F));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7F));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote(' '));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\t'));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\r'));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('\n'));
EXPECT_TRUE(IsInvalidHeaderKeyCharAllowDoubleQuote('}'));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('"'));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('a'));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('B'));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote('7'));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x42));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7C));
EXPECT_FALSE(IsInvalidHeaderKeyCharAllowDoubleQuote(0x7E));
}
TEST(HeaderPropertiesTest, IsInvalidHeaderChar) {
EXPECT_TRUE(IsInvalidHeaderChar(0x00));
EXPECT_TRUE(IsInvalidHeaderChar(0x06));
EXPECT_TRUE(IsInvalidHeaderChar(0x1F));
EXPECT_TRUE(IsInvalidHeaderChar(0x7F));
EXPECT_FALSE(IsInvalidHeaderChar(0x09));
EXPECT_FALSE(IsInvalidHeaderChar(' '));
EXPECT_FALSE(IsInvalidHeaderChar('\t'));
EXPECT_FALSE(IsInvalidHeaderChar('\r'));
EXPECT_FALSE(IsInvalidHeaderChar('\n'));
EXPECT_FALSE(IsInvalidHeaderChar('a'));
EXPECT_FALSE(IsInvalidHeaderChar('B'));
EXPECT_FALSE(IsInvalidHeaderChar('7'));
EXPECT_FALSE(IsInvalidHeaderChar(0x42));
EXPECT_FALSE(IsInvalidHeaderChar(0x7D));
}
TEST(HeaderPropertiesTest, KeyMoreRestrictiveThanValue) {
for (int c = 0; c < 255; ++c) {
if (IsInvalidHeaderChar(c)) {
EXPECT_TRUE(IsInvalidHeaderKeyChar(c)) << c;
}
}
}
TEST(HeaderPropertiesTest, HasInvalidHeaderChars) {
const char with_null[] = "Here's l\x00king at you, kid";
EXPECT_TRUE(HasInvalidHeaderChars(std::string(with_null, sizeof(with_null))));
EXPECT_TRUE(HasInvalidHeaderChars("Why's \x06 afraid of \x07? \x07\x08\x09"));
EXPECT_TRUE(HasInvalidHeaderChars("\x1Flower power"));
EXPECT_TRUE(HasInvalidHeaderChars("\x7Flowers more powers"));
EXPECT_FALSE(HasInvalidHeaderChars("Plenty of space"));
EXPECT_FALSE(HasInvalidHeaderChars("Keeping \tabs"));
EXPECT_FALSE(HasInvalidHeaderChars("Al\right"));
EXPECT_FALSE(HasInvalidHeaderChars("\new day"));
EXPECT_FALSE(HasInvalidHeaderChars("\x42 is a nice character"));
}
}
} |
455 | cpp | google/quiche | balsa_frame | quiche/balsa/balsa_frame.cc | quiche/balsa/balsa_frame_test.cc | #ifndef QUICHE_BALSA_BALSA_FRAME_H_
#define QUICHE_BALSA_BALSA_FRAME_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
#include "quiche/balsa/balsa_enums.h"
#include "quiche/balsa/balsa_headers.h"
#include "quiche/balsa/balsa_visitor_interface.h"
#include "quiche/balsa/framer_interface.h"
#include "quiche/balsa/http_validation_policy.h"
#include "quiche/balsa/noop_balsa_visitor.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_flag_utils.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quiche {
namespace test {
class BalsaFrameTestPeer;
}
class QUICHE_EXPORT BalsaFrame : public FramerInterface {
public:
typedef std::vector<std::pair<size_t, size_t> > Lines;
typedef BalsaHeaders::HeaderLineDescription HeaderLineDescription;
typedef BalsaHeaders::HeaderLines HeaderLines;
typedef BalsaHeaders::HeaderTokenList HeaderTokenList;
enum class InvalidCharsLevel { kOff, kError };
static constexpr int32_t kValidTerm1 = '\n' << 16 | '\r' << 8 | '\n';
static constexpr int32_t kValidTerm1Mask = 0xFF << 16 | 0xFF << 8 | 0xFF;
static constexpr int32_t kValidTerm2 = '\n' << 8 | '\n';
static constexpr int32_t kValidTerm2Mask = 0xFF << 8 | 0xFF;
BalsaFrame()
: last_char_was_slash_r_(false),
saw_non_newline_char_(false),
start_was_space_(true),
chunk_length_character_extracted_(false),
is_request_(true),
allow_reading_until_close_for_request_(false),
request_was_head_(false),
max_header_length_(16 * 1024),
visitor_(&do_nothing_visitor_),
chunk_length_remaining_(0),
content_length_remaining_(0),
last_slash_n_idx_(0),
term_chars_(0),
parse_state_(BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE),
last_error_(BalsaFrameEnums::BALSA_NO_ERROR),
continue_headers_(nullptr),
headers_(nullptr),
start_of_trailer_line_(0),
trailer_length_(0),
invalid_chars_level_(InvalidCharsLevel::kOff),
use_interim_headers_callback_(false) {}
~BalsaFrame() override {}
void Reset();
void set_balsa_headers(BalsaHeaders* headers) {
if (headers_ != headers) {
headers_ = headers;
}
if (headers_ != nullptr) {
headers_->Clear();
}
}
void set_continue_headers(BalsaHeaders* continue_headers) {
if (continue_headers_ != continue_headers) {
continue_headers_ = continue_headers;
}
if (continue_headers_ != nullptr) {
continue_headers_->Clear();
}
}
void EnableTrailers() {
if (is_request()) {
QUICHE_CODE_COUNT(balsa_trailer_in_request);
}
if (trailers_ == nullptr) {
trailers_ = std::make_unique<BalsaHeaders>();
}
}
void set_balsa_visitor(BalsaVisitorInterface* visitor) {
visitor_ = visitor;
if (visitor_ == nullptr) {
visitor_ = &do_nothing_visitor_;
}
}
void set_invalid_chars_level(InvalidCharsLevel v) {
invalid_chars_level_ = v;
}
bool invalid_chars_error_enabled() {
return invalid_chars_level_ == InvalidCharsLevel::kError;
}
void set_http_validation_policy(const HttpValidationPolicy& policy) {
http_validation_policy_ = policy;
}
const HttpValidationPolicy& http_validation_policy() const {
return http_validation_policy_;
}
void set_is_request(bool is_request) { is_request_ = is_request; }
bool is_request() const { return is_request_; }
void set_request_was_head(bool request_was_head) {
request_was_head_ = request_was_head;
}
void set_max_header_length(size_t max_header_length) {
max_header_length_ = max_header_length;
}
size_t max_header_length() const { return max_header_length_; }
bool MessageFullyRead() const {
return parse_state_ == BalsaFrameEnums::MESSAGE_FULLY_READ;
}
BalsaFrameEnums::ParseState ParseState() const { return parse_state_; }
bool Error() const { return parse_state_ == BalsaFrameEnums::ERROR; }
BalsaFrameEnums::ErrorCode ErrorCode() const { return last_error_; }
const BalsaHeaders* headers() const { return headers_; }
BalsaHeaders* mutable_headers() { return headers_; }
size_t BytesSafeToSplice() const;
void BytesSpliced(size_t bytes_spliced);
size_t ProcessInput(const char* input, size_t size) override;
void set_allow_reading_until_close_for_request(bool set) {
allow_reading_until_close_for_request_ = set;
}
void AllowArbitraryBody() {
parse_state_ = BalsaFrameEnums::READING_UNTIL_CLOSE;
}
void set_use_interim_headers_callback(bool set) {
use_interim_headers_callback_ = set;
}
void set_parse_truncated_headers_even_when_headers_too_long(bool set) {
parse_truncated_headers_even_when_headers_too_long_ = set;
}
protected:
inline BalsaHeadersEnums::ContentLengthStatus ProcessContentLengthLine(
size_t line_idx, size_t* length);
inline void ProcessTransferEncodingLine(size_t line_idx);
void ProcessFirstLine(char* begin, char* end);
void CleanUpKeyValueWhitespace(const char* stream_begin,
const char* line_begin, const char* current,
const char* line_end,
HeaderLineDescription* current_header_line);
void ProcessHeaderLines(const Lines& lines, bool is_trailer,
BalsaHeaders* headers);
bool CheckHeaderLinesForInvalidChars(const Lines& lines,
const BalsaHeaders* headers);
inline size_t ProcessHeaders(const char* message_start,
size_t message_length);
void AssignParseStateAfterHeadersHaveBeenParsed();
inline bool LineFramingFound(char current_char) {
return current_char == '\n';
}
inline int32_t HeaderFramingFound(char current_char) {
if (current_char == '\n' || current_char == '\r') {
term_chars_ <<= 8;
term_chars_ |= current_char & 0xFF;
if ((term_chars_ & kValidTerm1Mask) == kValidTerm1) {
term_chars_ = 0;
return kValidTerm1;
}
if ((term_chars_ & kValidTerm2Mask) == kValidTerm2) {
term_chars_ = 0;
return kValidTerm2;
}
} else {
term_chars_ = 0;
}
return 0;
}
inline bool HeaderFramingMayBeFound() const { return term_chars_ != 0; }
private:
friend class test::BalsaFrameTestPeer;
bool FindColonsAndParseIntoKeyValue(const Lines& lines, bool is_trailer,
BalsaHeaders* headers);
void HandleError(BalsaFrameEnums::ErrorCode error_code);
void HandleWarning(BalsaFrameEnums::ErrorCode error_code);
void HandleHeadersTooLongError();
bool last_char_was_slash_r_;
bool saw_non_newline_char_;
bool start_was_space_;
bool chunk_length_character_extracted_;
bool is_request_;
bool allow_reading_until_close_for_request_;
bool request_was_head_;
size_t max_header_length_;
BalsaVisitorInterface* visitor_;
size_t chunk_length_remaining_;
size_t content_length_remaining_;
size_t last_slash_n_idx_;
uint32_t term_chars_;
BalsaFrameEnums::ParseState parse_state_;
BalsaFrameEnums::ErrorCode last_error_;
Lines lines_;
BalsaHeaders* continue_headers_;
BalsaHeaders* headers_;
NoOpBalsaVisitor do_nothing_visitor_;
Lines trailer_lines_;
size_t start_of_trailer_line_;
size_t trailer_length_;
std::unique_ptr<BalsaHeaders> trailers_;
InvalidCharsLevel invalid_chars_level_;
HttpValidationPolicy http_validation_policy_;
bool use_interim_headers_callback_;
bool parse_truncated_headers_even_when_headers_too_long_ = false;
};
}
#endif
#include "quiche/balsa/balsa_frame.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/string_view.h"
#include "quiche/balsa/balsa_enums.h"
#include "quiche/balsa/balsa_headers.h"
#include "quiche/balsa/balsa_visitor_interface.h"
#include "quiche/balsa/header_properties.h"
#include "quiche/common/platform/api/quiche_logging.h"
#define CHAR_LT(a, b) \
(static_cast<unsigned char>(a) < static_cast<unsigned char>(b))
#define CHAR_LE(a, b) \
(static_cast<unsigned char>(a) <= static_cast<unsigned char>(b))
#define CHAR_GT(a, b) \
(static_cast<unsigned char>(a) > static_cast<unsigned char>(b))
#define CHAR_GE(a, b) \
(static_cast<unsigned char>(a) >= static_cast<unsigned char>(b))
#define QUICHE_DCHECK_CHAR_GE(a, b) \
QUICHE_DCHECK_GE(static_cast<unsigned char>(a), static_cast<unsigned char>(b))
namespace quiche {
namespace {
using FirstLineValidationOption =
HttpValidationPolicy::FirstLineValidationOption;
constexpr size_t kContinueStatusCode = 100;
constexpr size_t kSwitchingProtocolsStatusCode = 101;
constexpr absl::string_view kChunked = "chunked";
constexpr absl::string_view kContentLength = "content-length";
constexpr absl::string_view kIdentity = "identity";
constexpr absl::string_view kTransferEncoding = "transfer-encoding";
bool IsInterimResponse(size_t response_code) {
return response_code >= 100 && response_code < 200;
}
}
void BalsaFrame::Reset() {
last_char_was_slash_r_ = false;
saw_non_newline_char_ = false;
start_was_space_ = true;
chunk_length_character_extracted_ = false;
allow_reading_until_close_for_request_ = false;
chunk_length_remaining_ = 0;
content_length_remaining_ = 0;
last_slash_n_idx_ = 0;
term_chars_ = 0;
parse_state_ = BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE;
last_error_ = BalsaFrameEnums::BALSA_NO_ERROR;
lines_.clear();
if (continue_headers_ != nullptr) {
continue_headers_->Clear();
}
if (headers_ != nullptr) {
headers_->Clear();
}
trailer_lines_.clear();
start_of_trailer_line_ = 0;
trailer_length_ = 0;
if (trailers_ != nullptr) {
trailers_->Clear();
}
}
namespace {
inline char* ParseOneIsland(char* current, char* begin, char* end,
size_t* first_whitespace, size_t* first_nonwhite) {
*first_whitespace = current - begin;
while (current < end && CHAR_LE(*current, ' ')) {
++current;
}
*first_nonwhite = current - begin;
while (current < end && CHAR_GT(*current, ' ')) {
++current;
}
return current;
}
}
bool ParseHTTPFirstLine(char* begin, char* end, bool is_request,
BalsaHeaders* headers,
BalsaFrameEnums::ErrorCode* error_code,
FirstLineValidationOption whitespace_option) {
while (begin < end && (end[-1] == '\n' || end[-1] == '\r')) {
--end;
}
if (whitespace_option != FirstLineValidationOption::NONE) {
constexpr absl::string_view kBadWhitespace = "\r\t";
char* pos = std::find_first_of(begin, end, kBadWhitespace.begin(),
kBadWhitespace.end());
if (pos != end) {
if (whitespace_option == FirstLineValidationOption::REJECT) {
*error_code = static_cast<BalsaFrameEnums::ErrorCode>(
BalsaFrameEnums::INVALID_WS_IN_STATUS_LINE +
static_cast<int>(is_request));
return false;
}
QUICHE_DCHECK(whitespace_option == FirstLineValidationOption::SANITIZE);
std::replace_if(
pos, end, [](char c) { return c == '\r' || c == '\t'; }, ' ');
}
}
char* current = ParseOneIsland(begin, begin, end, &headers->whitespace_1_idx_,
&headers->non_whitespace_1_idx_);
current = ParseOneIsland(current, begin, end, &headers->whitespace_2_idx_,
&headers->non_whitespace_2_idx_);
current = ParseOneIsland(current, begin, end, &headers->whitespace_3_idx_,
&headers->non_whitespace_3_idx_);
const char* last = end;
while (current <= last && CHAR_LE(*last, ' ')) {
--last;
}
headers->whitespace_4_idx_ = last - begin + 1;
QUICHE_DCHECK(begin == end || static_cast<unsigned char>(*begin) > ' ');
QUICHE_DCHECK_EQ(0u, headers->whitespace_1_idx_);
QUICHE_DCHECK_EQ(0u, headers->non_whitespace_1_idx_);
QUICHE_DCHECK(begin == end ||
headers->non_whitespace_1_idx_ < headers->whitespace_2_idx_);
if (headers->non_whitespace_2_idx_ == headers->whitespace_3_idx_) {
*error_code = static_cast<BalsaFrameEnums::ErrorCode>(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION +
static_cast<int>(is_request));
if (!is_request) {
return false;
}
}
if (headers->whitespace_3_idx_ == headers->non_whitespace_3_idx_) {
if (*error_code == BalsaFrameEnums::BALSA_NO_ERROR) {
*error_code = static_cast<BalsaFrameEnums::ErrorCode>(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE +
static_cast<int>(is_request));
}
}
if (!is_request) {
headers->parsed_response_code_ = 0;
if (headers->non_whitespace_2_idx_ < headers->whitespace_3_idx_) {
if (!absl::SimpleAtoi(
absl::string_view(begin + headers->non_whitespace_2_idx_,
headers->non_whitespace_3_idx_ -
headers->non_whitespace_2_idx_),
&headers->parsed_response_code_)) {
*error_code = BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT;
return false;
}
}
}
return true;
}
namespace {
bool IsValidTargetUri(absl::string_view method, absl::string_view target_uri) {
if (target_uri.empty()) {
QUICHE_CODE_COUNT(invalid_target_uri_empty);
return false;
}
if (target_uri == "*") {
if (method == "OPTIONS") {
return true;
}
QUICHE_CODE_COUNT(invalid_target_uri_asterisk_not_options);
return false;
}
if (method == "CONNECT") {
size_t index = target_uri.find_last_of(':');
if (index == absl::string_view::npos || index == 0) {
QUICHE_CODE_COUNT(invalid_target_uri_connect_missing_port);
return false;
}
if (target_uri[0] == '[' && target_uri[index - 1] != ']') {
QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_v6_literal);
return false;
}
int port;
if (!absl::SimpleAtoi(target_uri.substr(index + 1), &port) || port < 0 ||
port > 65535) {
QUICHE_CODE_COUNT(invalid_target_uri_connect_bad_port);
return false;
}
return true;
}
if (target_uri[0] == '/' || absl::StrContains(target_uri, ":
return true;
}
QUICHE_CODE_COUNT(invalid_target_uri_bad_path);
return false;
}
}
void BalsaFrame::ProcessFirstLine(char* begin, char* end) {
BalsaFrameEnums::ErrorCode previous_error = last_error_;
if (!ParseHTTPFirstLine(
begin, end, is_request_, headers_, &last_error_,
http_validation_policy().sanitize_cr_tab_in_first_line)) {
parse_state_ = BalsaFrameEnums::ERROR;
HandleError(last_error_);
return;
}
if (previous_error != last_error_) {
HandleWarning(last_error_);
}
const absl::string_view line_input(
begin + headers_->non_whitespace_1_idx_,
headers_->whitespace_4_idx_ - headers_->non_whitespace_1_idx_);
const absl::string_view part1(
begin + headers_->non_whitespace_1_idx_,
headers_->whitespace_2_idx_ - headers_->non_whitespace_1_idx_);
const absl::string_view part2(
begin + headers_->non_whitespace_2_idx_,
headers_->whitespace_3_idx_ - headers_->non_whitespace_2_idx_);
const absl::string_view part3(
begin + headers_->non_whitespace_3_idx_,
headers_->whitespace_4_idx_ - headers_->non_whitespace_3_idx_);
if (is_request_) {
const bool is_valid_target_uri = IsValidTargetUri(part1, part2);
if (http_validation_policy().disallow_invalid_target_uris &&
!is_valid_target_uri) {
parse_state_ = BalsaFrameEnums::ERROR;
last_error_ = BalsaFrameEnums::INVALID_TARGET_URI;
HandleError(last_error_);
return;
}
visitor_->OnRequestFirstLineInput(line_input, part1, part2, part3);
if (part3.empty()) {
parse_state_ = BalsaFrameEnums::MESSAGE_FULLY_READ;
}
return;
}
visitor_->OnResponseFirstLineInput(line_input, part1, part2, part3);
}
void BalsaFrame::CleanUpKeyValueWhitespace(
const char* stream_begin, const char* line_begin, const char* current,
const char* line_end, HeaderLineDescription* current_header_line) {
const char* colon_loc = current;
QUICHE_DCHECK_LT(colon_loc, line_end);
QUICHE_DCHECK_EQ(':', *colon_loc);
QUICHE_DCHECK_EQ(':', *current);
QUICHE_DCHECK_CHAR_GE(' ', *line_end)
<< "\"" << std::string(line_begin, line_end) << "\"";
--current;
while (current > line_begin && CHAR_LE(*current, ' ')) {
--current;
}
current += static_cast<int>(current != colon_loc);
current_header_line->key_end_idx = current - stream_begin;
current = colon_loc;
QUICHE_DCHECK_EQ(':', *current);
++current;
while (current < line_end && CHAR_LE(*current, ' ')) {
++current;
}
current_header_line->value_begin_idx = current - stream_begin;
QUICHE_DCHECK_GE(current_header_line->key_end_idx,
current_header_line->first_char_idx);
QUICHE_DCHECK_GE(current_header_line->value_begin_idx,
current_header_line->key_end_idx);
QUICHE_DCHECK_GE(current_header_line->last_char_idx,
current_header_line->value_begin_idx);
}
bool BalsaFrame::FindColonsAndParseIntoKeyValue(const Lines& lines,
bool is_trailer,
BalsaHeaders* headers) {
QUICHE_DCHECK(!lines.empty());
const char* stream_begin = headers->OriginalHeaderStreamBegin();
const Lines::size_type lines_size_m1 = lines.size() - 1;
int first_header_idx = (is_trailer ? 0 : 1);
const char* current = stream_begin + lines[first_header_idx].first;
for (Lines::size_type i = first_header_idx; i < lines_size_m1;) {
const char* line_begin = stream_begin + lines[i].first;
for (++i; i < lines_size_m1; ++i) {
const char c = *(stream_begin + lines[i].first);
if (CHAR_GT(c, ' ')) {
break;
}
if ((c != ' ' && c != '\t') ||
http_validation_policy().disallow_header_continuation_lines) {
HandleError(is_trailer ? BalsaFrameEnums::INVALID_TRAILER_FORMAT
: BalsaFrameEnums::INVALID_HEADER_FORMAT);
return false;
}
}
const char* line_end = stream_begin + lines[i - 1].second;
QUICHE_DCHECK_LT(line_begin - stream_begin, line_end - stream_begin);
--line_end;
QUICHE_DCHECK_EQ('\n', *line_end)
<< "\"" << std::string(line_begin, line_end) << "\"";
while (CHAR_LE(*line_end, ' ') && line_end > line_begin) {
--line_end;
}
++line_end;
QUICHE_DCHECK_CHAR_GE(' ', *line_end);
QUICHE_DCHECK_LT(line_begin, line_end);
headers->header_lines_.push_back(HeaderLineDescription(
line_begin - stream_begin, line_end - stream_begin,
line_end - stream_begin, line_end - stream_begin, 0));
if (current >= line_end) {
if (http_validation_policy().require_header_colon) {
HandleError(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON
: BalsaFrameEnums::HEADER_MISSING_COLON);
return false;
}
HandleWarning(is_trailer ? BalsaFrameEnums::TRAILER_MISSING_COLON
: BalsaFrameEnums::HEADER_MISSING_COLON);
continue;
}
if (current < line_begin) {
current = line_begin;
}
for (; current < line_end; ++current) {
if (*current == ':') {
break;
}
if (http_validation_policy().disallow_double_quote_in_header_name) {
if (header_properties::IsInvalidHeaderKeyChar(*current)) {
Ha | #include "quiche/balsa/balsa_frame.h"
#include <stdlib.h>
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/escaping.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "quiche/balsa/balsa_enums.h"
#include "quiche/balsa/balsa_headers.h"
#include "quiche/balsa/balsa_visitor_interface.h"
#include "quiche/balsa/http_validation_policy.h"
#include "quiche/balsa/noop_balsa_visitor.h"
#include "quiche/balsa/simple_buffer.h"
#include "quiche/common/platform/api/quiche_command_line_flags.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_flags.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::AtLeast;
using ::testing::InSequence;
using ::testing::IsEmpty;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::Pointee;
using ::testing::Property;
using ::testing::Range;
using ::testing::StrEq;
using ::testing::StrictMock;
DEFINE_QUICHE_COMMAND_LINE_FLAG(
std::string, randseed, "",
"This is the seed for Pseudo-random number"
" generator used when generating random messages for unittests");
namespace quiche::test {
using RandomEngine = std::mt19937;
class BalsaFrameTestPeer {
public:
static int32_t HeaderFramingFound(BalsaFrame* balsa_frame, char c) {
return balsa_frame->HeaderFramingFound(c);
}
static void FindColonsAndParseIntoKeyValue(BalsaFrame* balsa_frame,
const BalsaFrame::Lines& lines,
bool is_trailer,
BalsaHeaders* headers) {
balsa_frame->FindColonsAndParseIntoKeyValue(lines, is_trailer, headers);
}
};
class BalsaHeadersTestPeer {
public:
static void WriteFromFramer(BalsaHeaders* headers, const char* ptr,
size_t size) {
headers->WriteFromFramer(ptr, size);
}
};
namespace {
class TestSeed {
public:
TestSeed() : test_seed_(0), user_supplied_seed_(false) {}
void Initialize(const std::string& seed_flag) {
if (!seed_flag.empty()) {
ASSERT_TRUE(absl::SimpleAtoi(seed_flag, &test_seed_));
user_supplied_seed_ = true;
}
}
int GetSeed() const {
int seed =
(user_supplied_seed_ ? test_seed_
: testing::UnitTest::GetInstance()->random_seed());
QUICHE_LOG(INFO) << "**** The current seed is " << seed << " ****";
return seed;
}
private:
int test_seed_;
bool user_supplied_seed_;
};
static bool RandomBool(RandomEngine& rng) { return rng() % 2 != 0; }
std::string EscapeString(absl::string_view message) {
return absl::StrReplaceAll(
message, {{"\n", "\\\\n\n"}, {"\\r", "\\\\r"}, {"\\t", "\\\\t"}});
}
char random_lws(RandomEngine& rng) {
if (RandomBool(rng)) {
return '\t';
}
return ' ';
}
const char* random_line_term(RandomEngine& rng) {
if (RandomBool(rng)) {
return "\r\n";
}
return "\n";
}
void AppendRandomWhitespace(RandomEngine& rng, std::stringstream* s) {
for (int i = 0; i < 1000 && RandomBool(rng); ++i) {
*s << random_lws(rng);
}
}
std::string CreateFirstLine(const char* tokens[3], const char* whitespace[4],
const char* line_ending) {
QUICHE_CHECK(tokens != nullptr);
QUICHE_CHECK(whitespace != nullptr);
QUICHE_CHECK(line_ending != nullptr);
QUICHE_CHECK(std::string(line_ending) == "\n" ||
std::string(line_ending) == "\r\n")
<< "line_ending: " << EscapeString(line_ending);
SimpleBuffer firstline_buffer;
firstline_buffer.WriteString(whitespace[0]);
for (int i = 0; i < 3; ++i) {
firstline_buffer.WriteString(tokens[i]);
firstline_buffer.WriteString(whitespace[i + 1]);
}
firstline_buffer.WriteString(line_ending);
return std::string(firstline_buffer.GetReadableRegion());
}
std::string CreateMessage(const char* firstline,
const std::pair<std::string, std::string>* headers,
size_t headers_len, const char* colon,
const char* line_ending, const char* body) {
SimpleBuffer request_buffer;
request_buffer.WriteString(firstline);
if (headers_len > 0) {
QUICHE_CHECK(headers != nullptr);
QUICHE_CHECK(colon != nullptr);
}
QUICHE_CHECK(line_ending != nullptr);
QUICHE_CHECK(std::string(line_ending) == "\n" ||
std::string(line_ending) == "\r\n")
<< "line_ending: " << EscapeString(line_ending);
QUICHE_CHECK(body != nullptr);
for (size_t i = 0; i < headers_len; ++i) {
bool only_whitespace_in_key = true;
{
const char* tmp_key = headers[i].first.c_str();
while (*tmp_key != '\0') {
if (*tmp_key > ' ') {
only_whitespace_in_key = false;
break;
}
++tmp_key;
}
}
const char* tmp_colon = colon;
if (only_whitespace_in_key) {
while (*tmp_colon != ':') {
++tmp_colon;
}
}
request_buffer.WriteString(headers[i].first);
request_buffer.WriteString(tmp_colon);
request_buffer.WriteString(headers[i].second);
request_buffer.WriteString(line_ending);
}
request_buffer.WriteString(line_ending);
request_buffer.WriteString(body);
return std::string(request_buffer.GetReadableRegion());
}
void VerifyRequestFirstLine(const char* tokens[3],
const BalsaHeaders& headers) {
EXPECT_EQ(tokens[0], headers.request_method());
EXPECT_EQ(tokens[1], headers.request_uri());
EXPECT_EQ(0u, headers.parsed_response_code());
EXPECT_EQ(tokens[2], headers.request_version());
}
void VerifyResponseFirstLine(const char* tokens[3],
size_t expected_response_code,
const BalsaHeaders& headers) {
EXPECT_EQ(tokens[0], headers.response_version());
EXPECT_EQ(tokens[1], headers.response_code());
EXPECT_EQ(expected_response_code, headers.parsed_response_code());
EXPECT_EQ(tokens[2], headers.response_reason_phrase());
}
void VerifyHeaderLines(
const std::pair<std::string, std::string>* expected_headers,
size_t headers_len, const BalsaHeaders& headers) {
BalsaHeaders::const_header_lines_iterator it = headers.lines().begin();
for (size_t i = 0; it != headers.lines().end(); ++it, ++i) {
ASSERT_GT(headers_len, i);
std::string actual_key;
std::string actual_value;
if (!it->first.empty()) {
actual_key = std::string(it->first);
}
if (!it->second.empty()) {
actual_value = std::string(it->second);
}
EXPECT_THAT(actual_key, StrEq(expected_headers[i].first));
EXPECT_THAT(actual_value, StrEq(expected_headers[i].second));
}
EXPECT_TRUE(headers.lines().end() == it);
}
void FirstLineParsedCorrectlyHelper(const char* tokens[3],
size_t expected_response_code,
bool is_request, const char* whitespace) {
BalsaHeaders headers;
BalsaFrame framer;
framer.set_is_request(is_request);
framer.set_balsa_headers(&headers);
const char* tmp_tokens[3] = {tokens[0], tokens[1], tokens[2]};
const char* tmp_whitespace[4] = {"", whitespace, whitespace, ""};
for (int j = 2; j >= 0; --j) {
framer.Reset();
std::string firstline = CreateFirstLine(tmp_tokens, tmp_whitespace, "\n");
std::string message =
CreateMessage(firstline.c_str(), nullptr, 0, nullptr, "\n", "");
SCOPED_TRACE(absl::StrFormat("input: \n%s", EscapeString(message)));
EXPECT_GE(message.size(),
framer.ProcessInput(message.data(), message.size()));
if (is_request || j >= 1) {
EXPECT_FALSE(framer.Error());
if (is_request) {
EXPECT_TRUE(framer.MessageFullyRead());
}
if (j == 0) {
expected_response_code = 0;
}
if (is_request) {
VerifyRequestFirstLine(tmp_tokens, *framer.headers());
} else {
VerifyResponseFirstLine(tmp_tokens, expected_response_code,
*framer.headers());
}
} else {
EXPECT_TRUE(framer.Error());
}
tmp_tokens[j] = "";
tmp_whitespace[j] = "";
}
}
TEST(HTTPBalsaFrame, ParseStateToString) {
EXPECT_STREQ("ERROR",
BalsaFrameEnums::ParseStateToString(BalsaFrameEnums::ERROR));
EXPECT_STREQ("READING_HEADER_AND_FIRSTLINE",
BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_HEADER_AND_FIRSTLINE));
EXPECT_STREQ("READING_CHUNK_LENGTH",
BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_CHUNK_LENGTH));
EXPECT_STREQ("READING_CHUNK_EXTENSION",
BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_CHUNK_EXTENSION));
EXPECT_STREQ("READING_CHUNK_DATA", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_CHUNK_DATA));
EXPECT_STREQ("READING_CHUNK_TERM", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_CHUNK_TERM));
EXPECT_STREQ("READING_LAST_CHUNK_TERM",
BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_LAST_CHUNK_TERM));
EXPECT_STREQ("READING_TRAILER", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_TRAILER));
EXPECT_STREQ("READING_UNTIL_CLOSE",
BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_UNTIL_CLOSE));
EXPECT_STREQ("READING_CONTENT", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::READING_CONTENT));
EXPECT_STREQ("MESSAGE_FULLY_READ", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::MESSAGE_FULLY_READ));
EXPECT_STREQ("UNKNOWN_STATE", BalsaFrameEnums::ParseStateToString(
BalsaFrameEnums::NUM_STATES));
EXPECT_STREQ("UNKNOWN_STATE",
BalsaFrameEnums::ParseStateToString(
static_cast<BalsaFrameEnums::ParseState>(-1)));
for (int i = 0; i < BalsaFrameEnums::NUM_STATES; ++i) {
EXPECT_STRNE("UNKNOWN_STATE",
BalsaFrameEnums::ParseStateToString(
static_cast<BalsaFrameEnums::ParseState>(i)));
}
}
TEST(HTTPBalsaFrame, ErrorCodeToString) {
EXPECT_STREQ("NO_STATUS_LINE_IN_RESPONSE",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::NO_STATUS_LINE_IN_RESPONSE));
EXPECT_STREQ("NO_REQUEST_LINE_IN_REQUEST",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST));
EXPECT_STREQ("FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_VERSION));
EXPECT_STREQ("FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD));
EXPECT_STREQ(
"FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_RESPONSE_STATUSCODE));
EXPECT_STREQ(
"FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_REQUEST_URI));
EXPECT_STREQ(
"FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_RESPONSE_REASON_PHRASE));
EXPECT_STREQ(
"FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_TO_FIND_NL_AFTER_REQUEST_HTTP_VERSION));
EXPECT_STREQ("FAILED_CONVERTING_STATUS_CODE_TO_INT",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::FAILED_CONVERTING_STATUS_CODE_TO_INT));
EXPECT_STREQ("HEADERS_TOO_LONG", BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::HEADERS_TOO_LONG));
EXPECT_STREQ("UNPARSABLE_CONTENT_LENGTH",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::UNPARSABLE_CONTENT_LENGTH));
EXPECT_STREQ("MAYBE_BODY_BUT_NO_CONTENT_LENGTH",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::MAYBE_BODY_BUT_NO_CONTENT_LENGTH));
EXPECT_STREQ("HEADER_MISSING_COLON",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::HEADER_MISSING_COLON));
EXPECT_STREQ("INVALID_CHUNK_LENGTH",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::INVALID_CHUNK_LENGTH));
EXPECT_STREQ("CHUNK_LENGTH_OVERFLOW",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::CHUNK_LENGTH_OVERFLOW));
EXPECT_STREQ("CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::CALLED_BYTES_SPLICED_WHEN_UNSAFE_TO_DO_SO));
EXPECT_STREQ("CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::
CALLED_BYTES_SPLICED_AND_EXCEEDED_SAFE_SPLICE_AMOUNT));
EXPECT_STREQ("MULTIPLE_CONTENT_LENGTH_KEYS",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::MULTIPLE_CONTENT_LENGTH_KEYS));
EXPECT_STREQ("MULTIPLE_TRANSFER_ENCODING_KEYS",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::MULTIPLE_TRANSFER_ENCODING_KEYS));
EXPECT_STREQ("INVALID_HEADER_FORMAT",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::INVALID_HEADER_FORMAT));
EXPECT_STREQ("INVALID_TRAILER_FORMAT",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::INVALID_TRAILER_FORMAT));
EXPECT_STREQ("TRAILER_TOO_LONG", BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::TRAILER_TOO_LONG));
EXPECT_STREQ("TRAILER_MISSING_COLON",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::TRAILER_MISSING_COLON));
EXPECT_STREQ("INTERNAL_LOGIC_ERROR",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::INTERNAL_LOGIC_ERROR));
EXPECT_STREQ("INVALID_HEADER_CHARACTER",
BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::INVALID_HEADER_CHARACTER));
EXPECT_STREQ("UNKNOWN_ERROR", BalsaFrameEnums::ErrorCodeToString(
BalsaFrameEnums::NUM_ERROR_CODES));
EXPECT_STREQ("UNKNOWN_ERROR",
BalsaFrameEnums::ErrorCodeToString(
static_cast<BalsaFrameEnums::ErrorCode>(-1)));
for (int i = 0; i < BalsaFrameEnums::NUM_ERROR_CODES; ++i) {
EXPECT_STRNE("UNKNOWN_ERROR",
BalsaFrameEnums::ErrorCodeToString(
static_cast<BalsaFrameEnums::ErrorCode>(i)));
}
}
class FakeHeaders {
public:
struct KeyValuePair {
KeyValuePair(const std::string& key, const std::string& value)
: key(key), value(value) {}
KeyValuePair() {}
std::string key;
std::string value;
};
typedef std::vector<KeyValuePair> KeyValuePairs;
KeyValuePairs key_value_pairs_;
bool operator==(const FakeHeaders& other) const {
if (key_value_pairs_.size() != other.key_value_pairs_.size()) {
return false;
}
for (KeyValuePairs::size_type i = 0; i < key_value_pairs_.size(); ++i) {
if (key_value_pairs_[i].key != other.key_value_pairs_[i].key) {
return false;
}
if (key_value_pairs_[i].value != other.key_value_pairs_[i].value) {
return false;
}
}
return true;
}
void AddKeyValue(const std::string& key, const std::string& value) {
key_value_pairs_.push_back(KeyValuePair(key, value));
}
};
class BalsaVisitorMock : public BalsaVisitorInterface {
public:
~BalsaVisitorMock() override = default;
void ProcessHeaders(const BalsaHeaders& headers) override {
FakeHeaders fake_headers;
GenerateFakeHeaders(headers, &fake_headers);
ProcessHeaders(fake_headers);
}
void OnTrailers(std::unique_ptr<BalsaHeaders> trailers) override {
FakeHeaders fake_trailers;
GenerateFakeHeaders(*trailers, &fake_trailers);
OnTrailers(fake_trailers);
}
MOCK_METHOD(void, OnRawBodyInput, (absl::string_view input), (override));
MOCK_METHOD(void, OnBodyChunkInput, (absl::string_view input), (override));
MOCK_METHOD(void, OnHeaderInput, (absl::string_view input), (override));
MOCK_METHOD(void, OnTrailerInput, (absl::string_view input), (override));
MOCK_METHOD(void, ProcessHeaders, (const FakeHeaders& headers));
MOCK_METHOD(void, OnTrailers, (const FakeHeaders& trailers));
MOCK_METHOD(void, OnRequestFirstLineInput,
(absl::string_view line_input, absl::string_view method_input,
absl::string_view request_uri, absl::string_view version_input),
(override));
MOCK_METHOD(void, OnResponseFirstLineInput,
(absl::string_view line_input, absl::string_view version_input,
absl::string_view status_input, absl::string_view reason_input),
(override));
MOCK_METHOD(void, OnChunkLength, (size_t length), (override));
MOCK_METHOD(void, OnChunkExtensionInput, (absl::string_view input),
(override));
MOCK_METHOD(void, OnInterimHeaders, (std::unique_ptr<BalsaHeaders> headers),
(override));
MOCK_METHOD(void, ContinueHeaderDone, (), (override));
MOCK_METHOD(void, HeaderDone, (), (override));
MOCK_METHOD(void, MessageDone, (), (override));
MOCK_METHOD(void, HandleError, (BalsaFrameEnums::ErrorCode error_code),
(override));
MOCK_METHOD(void, HandleWarning, (BalsaFrameEnums::ErrorCode error_code),
(override));
private:
static void GenerateFakeHeaders(const BalsaHeaders& headers,
FakeHeaders* fake_headers) {
for (const auto& line : headers.lines()) {
fake_headers->AddKeyValue(std::string(line.first),
std::string(line.second));
}
}
};
class HTTPBalsaFrameTest : public QuicheTest {
protected:
void SetUp() override {
balsa_frame_.set_balsa_headers(&headers_);
balsa_frame_.set_balsa_visitor(&visitor_mock_);
balsa_frame_.set_is_request(true);
balsa_frame_.EnableTrailers();
}
void VerifyFirstLineParsing(const std::string& firstline,
BalsaFrameEnums::ErrorCode error_code) {
balsa_frame_.ProcessInput(firstline.data(), firstline.size());
EXPECT_EQ(error_code, balsa_frame_.ErrorCode());
}
BalsaHeaders headers_;
BalsaFrame balsa_frame_;
NiceMock<BalsaVisitorMock> visitor_mock_;
};
TEST_F(HTTPBalsaFrameTest, TestHeaderFramingFound) {
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ' '));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(BalsaFrame::kValidTerm1,
BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\t'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(BalsaFrame::kValidTerm1,
BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, 'a'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(BalsaFrame::kValidTerm2,
BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '1'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(BalsaFrame::kValidTerm2,
BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, ':'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\r'));
EXPECT_EQ(0, BalsaFrameTestPeer::HeaderFramingFound(&balsa_frame_, '\n'));
}
TEST_F(HTTPBalsaFrameTest, MissingColonInTrailer) {
const absl::string_view trailer = "kv\r\n\r\n";
BalsaFrame::Lines lines;
lines.push_back({0, 4});
lines.push_back({4, trailer.length()});
BalsaHeaders trailers;
BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),
trailer.length());
BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(
&balsa_frame_, lines, true , &trailers);
EXPECT_FALSE(balsa_frame_.Error());
EXPECT_EQ(BalsaFrameEnums::TRAILER_MISSING_COLON, balsa_frame_.ErrorCode());
}
TEST_F(HTTPBalsaFrameTest, FindColonsAndParseIntoKeyValueInTrailer) {
const absl::string_view trailer_line1 = "Fraction: 0.23\r\n";
const absl::string_view trailer_line2 = "Some:junk \r\n";
const absl::string_view trailer_line3 = "\r\n";
const std::string trailer =
absl::StrCat(trailer_line1, trailer_line2, trailer_line3);
BalsaFrame::Lines lines;
lines.push_back({0, trailer_line1.length()});
lines.push_back({trailer_line1.length(),
trailer_line1.length() + trailer_line2.length()});
lines.push_back(
{trailer_line1.length() + trailer_line2.length(), trailer.length()});
BalsaHeaders trailers;
BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),
trailer.length());
BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(
&balsa_frame_, lines, true , &trailers);
EXPECT_FALSE(balsa_frame_.Error());
absl::string_view fraction = trailers.GetHeader("Fraction");
EXPECT_EQ("0.23", fraction);
absl::string_view some = trailers.GetHeader("Some");
EXPECT_EQ("junk", some);
}
TEST_F(HTTPBalsaFrameTest, InvalidTrailer) {
const absl::string_view trailer_line1 = "Fraction : 0.23\r\n";
const absl::string_view trailer_line2 = "Some\t :junk \r\n";
const absl::string_view trailer_line3 = "\r\n";
const std::string trailer =
absl::StrCat(trailer_line1, trailer_line2, trailer_line3);
BalsaFrame::Lines lines;
lines.push_back({0, trailer_line1.length()});
lines.push_back({trailer_line1.length(),
trailer_line1.length() + trailer_line2.length()});
lines.push_back(
{trailer_line1.length() + trailer_line2.length(), trailer.length()});
BalsaHeaders trailers;
BalsaHeadersTestPeer::WriteFromFramer(&trailers, trailer.data(),
trailer.length());
BalsaFrameTestPeer::FindColonsAndParseIntoKeyValue(
&balsa_frame_, lines, true , &trailers);
EXPECT_TRUE(balsa_frame_.Error());
EXPECT_EQ(BalsaFrameEnums::INVALID_TRAILER_NAME_CHARACTER,
balsa_frame_.ErrorCode());
}
TEST_F(HTTPBalsaFrameTest, OneCharacterFirstLineParsedAsExpected) {
VerifyFirstLineParsing(
"a\r\n\r\n", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD);
}
TEST_F(HTTPBalsaFrameTest,
OneCharacterFirstLineWithWhitespaceParsedAsExpected) {
VerifyFirstLineParsing(
"a \r\n\r\n", BalsaFrameEnums::FAILED_TO_FIND_WS_AFTER_REQUEST_METHOD);
}
TEST_F(HTTPBalsaFrameTest, WhitespaceOnlyFirstLineIsNotACompleteHeader) {
VerifyFirstLineParsing(" \n\n", BalsaFrameEnums::NO_REQUEST_LINE_IN_REQUEST);
}
TEST(HTTPBalsaFrame, RequestFirstLineParsedCorrectly) {
const char* request_tokens[3] = {"GET", "/jjsdjrqk", "HTTP/1.0"};
FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " ");
FirstLineParsedCorrectlyHelper(request_tokens, 0, true, "\t");
FirstLineParsedCorrectlyHelper(request_tokens, 0, true, "\t ");
FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " \t");
FirstLineParsedCorrectlyHelper(request_tokens, 0, true, " \t \t ");
}
TEST(HTTPBalsaFrame, RequestLineSanitizedProperly) {
SCOPED_TRACE("Testing that the request line is properly sanitized.");
using enum HttpValidationPolicy::FirstLineValidationOption;
using FirstLineValidationOption =
HttpValidationPolicy::FirstLineValidationOption;
struct TestCase {
const absl::string_view input;
const absl::string_view parsed;
FirstLineValidationOption option;
BalsaFrameEnums::ErrorCode expected_error;
};
const std::vector<TestCase> cases = {
{"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", NONE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET / HTTP/1.1\r\n", "GET / HTTP/1.1", REJECT,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET /\rHTTP/1.1\r\n", "GET /\rHTTP/1.1", NONE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET /\rHTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET /\rHTTP/1.1\r\n", "", REJECT,
BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},
{"GET \t/ HTTP/1.1\r\n", "GET \t/ HTTP/1.1", NONE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET \t/ HTTP/1.1\r\n", "GET / HTTP/1.1", SANITIZE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET \t/ HTTP/1.1\r\n", "", REJECT,
BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},
{"GET \t/\rHTTP/1.1 \r\n", "GET \t/\rHTTP/1.1", NONE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET \t/\rHTTP/1.1 \r\n", "GET / HTTP/1.1", SANITIZE,
BalsaFrameEnums::BALSA_NO_ERROR},
{"GET \t/\rHTTP/1.1 \r\n", "", REJECT,
BalsaFrameEnums::INVALID_WS_IN_REQUEST_LINE},
};
const absl::string_view kHeaderLineAndEnding = "Foo: bar\r\n\r\n";
for (auto& [firstline, parsed, ws_option, expected_error] : cases) {
SCOPED_TRACE(
absl::StrCat("Input: ", absl::CEscape(firstline),
" Expected output: ", absl::CEscape(parsed),
" whitespace option: ", static_cast<int>(ws_option)));
const std::string input = absl::StrCat(firstline, kHeaderLineAndEnding);
BalsaHeaders headers;
BalsaFrame framer;
HttpValidationPolicy policy;
policy.sanitize_cr_tab_in_first_line = ws_option;
framer.set_http_validation_policy(policy);
framer.set_is_request(true);
framer.set_balsa_headers(&headers);
framer.ProcessInput(input.data(), input.size());
EXPECT_EQ(headers.first_line(), |
456 | cpp | google/quiche | simple_buffer | quiche/balsa/simple_buffer.cc | quiche/balsa/simple_buffer_test.cc | #ifndef QUICHE_BALSA_SIMPLE_BUFFER_H_
#define QUICHE_BALSA_SIMPLE_BUFFER_H_
#include <cstddef>
#include <memory>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche {
namespace test {
class SimpleBufferTest;
}
class QUICHE_EXPORT SimpleBuffer {
public:
struct ReleasedBuffer {
std::unique_ptr<char[]> buffer;
size_t size;
};
SimpleBuffer() = default;
explicit SimpleBuffer(int size);
SimpleBuffer(const SimpleBuffer&) = delete;
SimpleBuffer& operator=(const SimpleBuffer&) = delete;
virtual ~SimpleBuffer() { delete[] storage_; }
int ReadableBytes() const { return write_idx_ - read_idx_; }
bool Empty() const { return read_idx_ == write_idx_; }
int Write(const char* bytes, int size);
int WriteString(absl::string_view piece) {
return Write(piece.data(), piece.size());
}
void GetWritablePtr(char** ptr, int* size) const {
*ptr = storage_ + write_idx_;
*size = storage_size_ - write_idx_;
}
void GetReadablePtr(char** ptr, int* size) const {
*ptr = storage_ + read_idx_;
*size = write_idx_ - read_idx_;
}
absl::string_view GetReadableRegion() const {
return absl::string_view(storage_ + read_idx_, write_idx_ - read_idx_);
}
int Read(char* bytes, int size);
void Clear() { read_idx_ = write_idx_ = 0; }
void Reserve(int size);
void AdvanceReadablePtr(int amount_to_advance);
void AdvanceWritablePtr(int amount_to_advance);
ReleasedBuffer Release();
private:
friend class test::SimpleBufferTest;
char* storage_ = nullptr;
int write_idx_ = 0;
int read_idx_ = 0;
int storage_size_ = 0;
};
}
#endif
#include "quiche/balsa/simple_buffer.h"
#include <algorithm>
#include <cstring>
#include <memory>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quiche {
constexpr int kMinimumSimpleBufferSize = 10;
SimpleBuffer::SimpleBuffer(int size) { Reserve(size); }
int SimpleBuffer::Write(const char* bytes, int size) {
if (size <= 0) {
QUICHE_BUG_IF(simple_buffer_write_negative_size, size < 0)
<< "size must not be negative: " << size;
return 0;
}
Reserve(size);
memcpy(storage_ + write_idx_, bytes, size);
AdvanceWritablePtr(size);
return size;
}
int SimpleBuffer::Read(char* bytes, int size) {
if (size < 0) {
QUICHE_BUG(simple_buffer_read_negative_size)
<< "size must not be negative: " << size;
return 0;
}
char* read_ptr = nullptr;
int read_size = 0;
GetReadablePtr(&read_ptr, &read_size);
read_size = std::min(read_size, size);
if (read_size == 0) {
return 0;
}
memcpy(bytes, read_ptr, read_size);
AdvanceReadablePtr(read_size);
return read_size;
}
void SimpleBuffer::Reserve(int size) {
if (size < 0) {
QUICHE_BUG(simple_buffer_reserve_negative_size)
<< "size must not be negative: " << size;
return;
}
if (size == 0 || storage_size_ - write_idx_ >= size) {
return;
}
char* read_ptr = nullptr;
int read_size = 0;
GetReadablePtr(&read_ptr, &read_size);
if (read_ptr == nullptr) {
QUICHE_DCHECK_EQ(0, read_size);
size = std::max(size, kMinimumSimpleBufferSize);
storage_ = new char[size];
storage_size_ = size;
return;
}
if (read_size + size <= storage_size_) {
memmove(storage_, read_ptr, read_size);
read_idx_ = 0;
write_idx_ = read_size;
return;
}
storage_size_ = std::max(2 * storage_size_, size + read_size);
char* new_storage = new char[storage_size_];
memcpy(new_storage, read_ptr, read_size);
delete[] storage_;
read_idx_ = 0;
write_idx_ = read_size;
storage_ = new_storage;
}
void SimpleBuffer::AdvanceReadablePtr(int amount_to_advance) {
if (amount_to_advance < 0) {
QUICHE_BUG(simple_buffer_advance_read_negative_arg)
<< "amount_to_advance must not be negative: " << amount_to_advance;
return;
}
read_idx_ += amount_to_advance;
if (read_idx_ > write_idx_) {
QUICHE_BUG(simple_buffer_read_ptr_too_far)
<< "error: readable pointer advanced beyond writable one";
read_idx_ = write_idx_;
}
if (read_idx_ == write_idx_) {
Clear();
}
}
void SimpleBuffer::AdvanceWritablePtr(int amount_to_advance) {
if (amount_to_advance < 0) {
QUICHE_BUG(simple_buffer_advance_write_negative_arg)
<< "amount_to_advance must not be negative: " << amount_to_advance;
return;
}
write_idx_ += amount_to_advance;
if (write_idx_ > storage_size_) {
QUICHE_BUG(simple_buffer_write_ptr_too_far)
<< "error: writable pointer advanced beyond end of storage";
write_idx_ = storage_size_;
}
}
SimpleBuffer::ReleasedBuffer SimpleBuffer::Release() {
if (write_idx_ == 0) {
return ReleasedBuffer{nullptr, 0};
}
ReleasedBuffer buffer{std::unique_ptr<char[]>(storage_),
static_cast<size_t>(write_idx_)};
Clear();
storage_ = nullptr;
storage_size_ = 0;
return buffer;
}
} | #include "quiche/balsa/simple_buffer.h"
#include <string>
#include "absl/strings/string_view.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quiche {
namespace test {
namespace {
constexpr int kMinimumSimpleBufferSize = 10;
const char ibuf[] = {
"123456789!@#$%^&*()abcdefghijklmnopqrstu"
"123456789!@#$%^&*()abcdefghijklmnopqrstu"
"123456789!@#$%^&*()abcdefghijklmnopqrstu"
"123456789!@#$%^&*()abcdefghijklmnopqrstu"
"123456789!@#$%^&*()abcdefghijklmnopqrstu"};
}
class SimpleBufferTest : public QuicheTest {
public:
static char* storage(SimpleBuffer& buffer) { return buffer.storage_; }
static int write_idx(SimpleBuffer& buffer) { return buffer.write_idx_; }
static int read_idx(SimpleBuffer& buffer) { return buffer.read_idx_; }
static int storage_size(SimpleBuffer& buffer) { return buffer.storage_size_; }
};
namespace {
TEST_F(SimpleBufferTest, CreationWithSize) {
SimpleBuffer buffer1(5);
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer1));
SimpleBuffer buffer2(25);
EXPECT_EQ(25, storage_size(buffer2));
}
TEST_F(SimpleBufferTest, CreationWithZeroSize) {
SimpleBuffer buffer(0);
EXPECT_EQ(0, storage_size(buffer));
EXPECT_EQ(4, buffer.Write(ibuf, 4));
EXPECT_EQ(4, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(4, buffer.ReadableBytes());
}
TEST_F(SimpleBufferTest, ReadZeroBytes) {
SimpleBuffer buffer;
EXPECT_EQ(0, buffer.Read(nullptr, 0));
}
TEST_F(SimpleBufferTest, WriteZeroFromNullptr) {
SimpleBuffer buffer;
EXPECT_EQ(0, buffer.Write(nullptr, 0));
}
TEST(SimpleBufferExpectBug, ReserveNegativeSize) {
SimpleBuffer buffer;
EXPECT_QUICHE_BUG(buffer.Reserve(-1), "size must not be negative");
}
TEST(SimpleBufferExpectBug, ReadNegativeSize) {
SimpleBuffer buffer;
EXPECT_QUICHE_BUG(buffer.Read(nullptr, -1), "size must not be negative");
}
TEST(SimpleBufferExpectBug, WriteNegativeSize) {
SimpleBuffer buffer;
EXPECT_QUICHE_BUG(buffer.Write(nullptr, -1), "size must not be negative");
}
TEST_F(SimpleBufferTest, Basics) {
SimpleBuffer buffer;
EXPECT_TRUE(buffer.Empty());
EXPECT_EQ("", buffer.GetReadableRegion());
EXPECT_EQ(0, storage_size(buffer));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
char* readable_ptr = nullptr;
int readable_size = 0;
buffer.GetReadablePtr(&readable_ptr, &readable_size);
char* writeable_ptr = nullptr;
int writable_size = 0;
buffer.GetWritablePtr(&writeable_ptr, &writable_size);
EXPECT_EQ(storage(buffer), readable_ptr);
EXPECT_EQ(0, readable_size);
EXPECT_EQ(storage(buffer), writeable_ptr);
EXPECT_EQ(0, writable_size);
EXPECT_EQ(0, buffer.ReadableBytes());
const SimpleBuffer buffer2;
EXPECT_EQ(0, buffer2.ReadableBytes());
}
TEST_F(SimpleBufferTest, BasicWR) {
SimpleBuffer buffer;
EXPECT_EQ(4, buffer.Write(ibuf, 4));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(4, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(4, buffer.ReadableBytes());
EXPECT_EQ("1234", buffer.GetReadableRegion());
int bytes_written = 4;
EXPECT_TRUE(!buffer.Empty());
char* readable_ptr = nullptr;
int readable_size = 0;
buffer.GetReadablePtr(&readable_ptr, &readable_size);
char* writeable_ptr = nullptr;
int writable_size = 0;
buffer.GetWritablePtr(&writeable_ptr, &writable_size);
EXPECT_EQ(storage(buffer), readable_ptr);
EXPECT_EQ(4, readable_size);
EXPECT_EQ(storage(buffer) + 4, writeable_ptr);
EXPECT_EQ(6, writable_size);
char obuf[ABSL_ARRAYSIZE(ibuf)];
int bytes_read = 0;
EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 40));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(0, buffer.ReadableBytes());
EXPECT_EQ("", buffer.GetReadableRegion());
bytes_read += 4;
EXPECT_TRUE(buffer.Empty());
buffer.GetReadablePtr(&readable_ptr, &readable_size);
buffer.GetWritablePtr(&writeable_ptr, &writable_size);
EXPECT_EQ(storage(buffer), readable_ptr);
EXPECT_EQ(0, readable_size);
EXPECT_EQ(storage(buffer), writeable_ptr);
EXPECT_EQ(kMinimumSimpleBufferSize, writable_size);
EXPECT_EQ(bytes_written, bytes_read);
for (int i = 0; i < bytes_read; ++i) {
EXPECT_EQ(obuf[i], ibuf[i]);
}
EXPECT_EQ(10, buffer.Write(ibuf + bytes_written, 10));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(10, write_idx(buffer));
EXPECT_EQ(10, storage_size(buffer));
EXPECT_EQ(10, buffer.ReadableBytes());
bytes_written += 10;
EXPECT_TRUE(!buffer.Empty());
EXPECT_EQ(6, buffer.Read(obuf + bytes_read, 6));
EXPECT_EQ(6, read_idx(buffer));
EXPECT_EQ(10, write_idx(buffer));
EXPECT_EQ(10, storage_size(buffer));
EXPECT_EQ(4, buffer.ReadableBytes());
bytes_read += 6;
EXPECT_TRUE(!buffer.Empty());
EXPECT_EQ(4, buffer.Read(obuf + bytes_read, 7));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(10, storage_size(buffer));
EXPECT_EQ(0, buffer.ReadableBytes());
bytes_read += 4;
EXPECT_TRUE(buffer.Empty());
EXPECT_EQ(bytes_written, bytes_read);
for (int i = 0; i < bytes_read; ++i) {
EXPECT_EQ(obuf[i], ibuf[i]);
}
}
TEST_F(SimpleBufferTest, Reserve) {
SimpleBuffer buffer;
EXPECT_EQ(0, storage_size(buffer));
buffer.WriteString("foo");
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
buffer.Reserve(kMinimumSimpleBufferSize + 1);
EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));
buffer.Clear();
buffer.AdvanceWritablePtr(kMinimumSimpleBufferSize);
buffer.AdvanceReadablePtr(kMinimumSimpleBufferSize - 2);
EXPECT_EQ(kMinimumSimpleBufferSize, write_idx(buffer));
EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));
buffer.Reserve(kMinimumSimpleBufferSize + 1);
EXPECT_EQ(2, write_idx(buffer));
EXPECT_EQ(2 * kMinimumSimpleBufferSize, storage_size(buffer));
}
TEST_F(SimpleBufferTest, Extend) {
SimpleBuffer buffer;
EXPECT_EQ(7, buffer.Write(ibuf, 7));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(7, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(7, buffer.ReadableBytes());
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(7, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(7, buffer.ReadableBytes());
int bytes_written = 7;
EXPECT_EQ(4, buffer.Write(ibuf + bytes_written, 4));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(11, write_idx(buffer));
EXPECT_EQ(20, storage_size(buffer));
EXPECT_EQ(11, buffer.ReadableBytes());
bytes_written += 4;
char obuf[ABSL_ARRAYSIZE(ibuf)];
EXPECT_EQ(11, buffer.Read(obuf, 11));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(20, storage_size(buffer));
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(0, buffer.ReadableBytes());
const int bytes_read = 11;
EXPECT_EQ(bytes_written, bytes_read);
for (int i = 0; i < bytes_read; ++i) {
EXPECT_EQ(obuf[i], ibuf[i]);
}
}
TEST_F(SimpleBufferTest, Clear) {
SimpleBuffer buffer;
buffer.Clear();
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(0, storage_size(buffer));
EXPECT_EQ(0, buffer.ReadableBytes());
buffer.WriteString("foo");
buffer.Clear();
EXPECT_EQ(0, read_idx(buffer));
EXPECT_EQ(0, write_idx(buffer));
EXPECT_EQ(kMinimumSimpleBufferSize, storage_size(buffer));
EXPECT_EQ(0, buffer.ReadableBytes());
}
TEST_F(SimpleBufferTest, LongWrite) {
SimpleBuffer buffer;
std::string s1 = "HTTP/1.1 500 Service Unavailable";
buffer.Write(s1.data(), s1.size());
buffer.Write("\r\n", 2);
std::string key = "Connection";
std::string value = "close";
buffer.Write(key.data(), key.size());
buffer.Write(": ", 2);
buffer.Write(value.data(), value.size());
buffer.Write("\r\n", 2);
buffer.Write("\r\n", 2);
std::string message =
"<html><head>\n"
"<meta http-equiv=\"content-type\""
" content=\"text/html;charset=us-ascii\">\n"
"<style><!--\n"
"body {font-family: arial,sans-serif}\n"
"div.nav {margin-top: 1ex}\n"
"div.nav A {font-size: 10pt; font-family: arial,sans-serif}\n"
"span.nav {font-size: 10pt; font-family: arial,sans-serif;"
" font-weight: bold}\n"
"div.nav A,span.big {font-size: 12pt; color: #0000cc}\n"
"div.nav A {font-size: 10pt; color: black}\n"
"A.l:link {color: #6f6f6f}\n"
"A.u:link {color: green}\n"
"
"</head>\n"
"<body text=#000000 bgcolor=#ffffff>\n"
"<table border=0 cellpadding=2 cellspacing=0 width=100%>"
"<tr><td rowspan=3 width=1% nowrap>\n"
"<b>"
"<font face=times color=#0039b6 size=10>G</font>"
"<font face=times color=#c41200 size=10>o</font>"
"<font face=times color=#f3c518 size=10>o</font>"
"<font face=times color=#0039b6 size=10>g</font>"
"<font face=times color=#30a72f size=10>l</font>"
"<font face=times color=#c41200 size=10>e</font>"
" </b>\n"
"<td> </td></tr>\n"
"<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff>"
" <b>Error</b></td></tr>\n"
"<tr><td> </td></tr></table>\n"
"<blockquote>\n"
"<H1> Internal Server Error</H1>\n"
" This server was unable to complete the request\n"
"<p></blockquote>\n"
"<table width=100% cellpadding=0 cellspacing=0>"
"<tr><td bgcolor=#3366cc><img alt=\"\" width=1 height=4></td></tr>"
"</table>"
"</body></html>\n";
buffer.Write(message.data(), message.size());
const std::string correct_result =
"HTTP/1.1 500 Service Unavailable\r\n"
"Connection: close\r\n"
"\r\n"
"<html><head>\n"
"<meta http-equiv=\"content-type\""
" content=\"text/html;charset=us-ascii\">\n"
"<style><!--\n"
"body {font-family: arial,sans-serif}\n"
"div.nav {margin-top: 1ex}\n"
"div.nav A {font-size: 10pt; font-family: arial,sans-serif}\n"
"span.nav {font-size: 10pt; font-family: arial,sans-serif;"
" font-weight: bold}\n"
"div.nav A,span.big {font-size: 12pt; color: #0000cc}\n"
"div.nav A {font-size: 10pt; color: black}\n"
"A.l:link {color: #6f6f6f}\n"
"A.u:link {color: green}\n"
"
"</head>\n"
"<body text=#000000 bgcolor=#ffffff>\n"
"<table border=0 cellpadding=2 cellspacing=0 width=100%>"
"<tr><td rowspan=3 width=1% nowrap>\n"
"<b>"
"<font face=times color=#0039b6 size=10>G</font>"
"<font face=times color=#c41200 size=10>o</font>"
"<font face=times color=#f3c518 size=10>o</font>"
"<font face=times color=#0039b6 size=10>g</font>"
"<font face=times color=#30a72f size=10>l</font>"
"<font face=times color=#c41200 size=10>e</font>"
" </b>\n"
"<td> </td></tr>\n"
"<tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff>"
" <b>Error</b></td></tr>\n"
"<tr><td> </td></tr></table>\n"
"<blockquote>\n"
"<H1> Internal Server Error</H1>\n"
" This server was unable to complete the request\n"
"<p></blockquote>\n"
"<table width=100% cellpadding=0 cellspacing=0>"
"<tr><td bgcolor=#3366cc><img alt=\"\" width=1 height=4></td></tr>"
"</table>"
"</body></html>\n";
EXPECT_EQ(correct_result, buffer.GetReadableRegion());
}
TEST_F(SimpleBufferTest, ReleaseAsSlice) {
SimpleBuffer buffer;
buffer.WriteString("abc");
SimpleBuffer::ReleasedBuffer released = buffer.Release();
EXPECT_EQ("abc", absl::string_view(released.buffer.get(), released.size));
char* readable_ptr = nullptr;
int readable_size = 0;
buffer.GetReadablePtr(&readable_ptr, &readable_size);
EXPECT_EQ(nullptr, readable_ptr);
EXPECT_EQ(0, readable_size);
buffer.WriteString("def");
released = buffer.Release();
buffer.GetReadablePtr(&readable_ptr, &readable_size);
EXPECT_EQ(nullptr, readable_ptr);
EXPECT_EQ(0, readable_size);
EXPECT_EQ("def", absl::string_view(released.buffer.get(), released.size));
}
TEST_F(SimpleBufferTest, EmptyBufferReleaseAsSlice) {
SimpleBuffer buffer;
char* readable_ptr = nullptr;
int readable_size = 0;
SimpleBuffer::ReleasedBuffer released = buffer.Release();
buffer.GetReadablePtr(&readable_ptr, &readable_size);
EXPECT_EQ(nullptr, readable_ptr);
EXPECT_EQ(0, readable_size);
EXPECT_TRUE(released.buffer == nullptr);
EXPECT_EQ(released.size, 0u);
}
}
}
} |
457 | cpp | google/quiche | balsa_headers_sequence | quiche/balsa/balsa_headers_sequence.cc | quiche/balsa/balsa_headers_sequence_test.cc | #ifndef QUICHE_BALSA_BALSA_HEADERS_SEQUENCE_H_
#define QUICHE_BALSA_BALSA_HEADERS_SEQUENCE_H_
#include <cstddef>
#include <memory>
#include "absl/container/inlined_vector.h"
#include "quiche/balsa/balsa_headers.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace quiche {
class QUICHE_EXPORT BalsaHeadersSequence {
public:
void Append(std::unique_ptr<BalsaHeaders> headers);
bool HasNext() const;
bool IsEmpty() const { return sequence_.empty(); }
BalsaHeaders* Next();
BalsaHeaders* PeekNext();
void Clear();
private:
absl::InlinedVector<std::unique_ptr<BalsaHeaders>, 2> sequence_;
size_t next_ = 0;
};
}
#endif
#include "quiche/balsa/balsa_headers_sequence.h"
#include <memory>
#include <utility>
#include "quiche/balsa/balsa_headers.h"
namespace quiche {
void BalsaHeadersSequence::Append(std::unique_ptr<BalsaHeaders> headers) {
sequence_.push_back(std::move(headers));
}
bool BalsaHeadersSequence::HasNext() const { return next_ < sequence_.size(); }
BalsaHeaders* BalsaHeadersSequence::PeekNext() {
if (!HasNext()) {
return nullptr;
}
return sequence_[next_].get();
}
BalsaHeaders* BalsaHeadersSequence::Next() {
if (!HasNext()) {
return nullptr;
}
return sequence_[next_++].get();
}
void BalsaHeadersSequence::Clear() {
sequence_.clear();
next_ = 0;
}
} | #include "quiche/balsa/balsa_headers_sequence.h"
#include <memory>
#include <utility>
#include "quiche/balsa/balsa_headers.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quiche {
namespace test {
namespace {
TEST(BalsaHeadersSequenceTest, Initial) {
BalsaHeadersSequence sequence;
EXPECT_FALSE(sequence.HasNext());
EXPECT_EQ(sequence.Next(), nullptr);
EXPECT_TRUE(sequence.IsEmpty());
}
TEST(BalsaHeadersSequenceTest, Basic) {
BalsaHeadersSequence sequence;
auto headers_one = std::make_unique<BalsaHeaders>();
headers_one->AppendHeader("one", "fish");
sequence.Append(std::move(headers_one));
EXPECT_TRUE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
auto headers_two = std::make_unique<BalsaHeaders>();
headers_two->AppendHeader("two", "fish");
sequence.Append(std::move(headers_two));
EXPECT_TRUE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
const BalsaHeaders* headers = sequence.Next();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("one"));
EXPECT_TRUE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
headers = sequence.Next();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("two"));
EXPECT_FALSE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
EXPECT_EQ(sequence.Next(), nullptr);
}
TEST(BalsaHeadersSequenceTest, Clear) {
BalsaHeadersSequence sequence;
auto headers_one = std::make_unique<BalsaHeaders>();
headers_one->AppendHeader("one", "fish");
sequence.Append(std::move(headers_one));
EXPECT_TRUE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
auto headers_two = std::make_unique<BalsaHeaders>();
headers_two->AppendHeader("two", "fish");
sequence.Append(std::move(headers_two));
EXPECT_TRUE(sequence.HasNext());
EXPECT_FALSE(sequence.IsEmpty());
sequence.Clear();
EXPECT_FALSE(sequence.HasNext());
EXPECT_EQ(sequence.Next(), nullptr);
EXPECT_TRUE(sequence.IsEmpty());
}
TEST(BalsaHeadersSequenceTest, PeekNext) {
BalsaHeadersSequence sequence;
EXPECT_EQ(sequence.PeekNext(), nullptr);
auto headers_one = std::make_unique<BalsaHeaders>();
headers_one->AppendHeader("one", "fish");
sequence.Append(std::move(headers_one));
EXPECT_TRUE(sequence.HasNext());
const BalsaHeaders* headers = sequence.PeekNext();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("one"));
EXPECT_TRUE(sequence.HasNext());
EXPECT_EQ(sequence.PeekNext(), headers);
auto headers_two = std::make_unique<BalsaHeaders>();
headers_two->AppendHeader("two", "fish");
sequence.Append(std::move(headers_two));
EXPECT_TRUE(sequence.HasNext());
EXPECT_EQ(sequence.PeekNext(), headers);
headers = sequence.Next();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("one"));
EXPECT_TRUE(sequence.HasNext());
headers = sequence.PeekNext();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("two"));
EXPECT_TRUE(sequence.HasNext());
headers = sequence.Next();
ASSERT_NE(headers, nullptr);
EXPECT_TRUE(headers->HasHeader("two"));
EXPECT_FALSE(sequence.HasNext());
EXPECT_EQ(sequence.PeekNext(), nullptr);
}
TEST(BalsaHeadersSequenceTest, CanRetainValidReference) {
BalsaHeadersSequence sequence;
auto headers = std::make_unique<BalsaHeaders>();
headers->AppendHeader("one", "fish");
BalsaHeaders* headers_ptr = headers.get();
sequence.Append(std::move(headers));
ASSERT_TRUE(sequence.HasNext());
EXPECT_EQ(sequence.Next(), headers_ptr);
}
}
}
} |
458 | cpp | google/quiche | balsa_headers | quiche/balsa/balsa_headers.cc | quiche/balsa/balsa_headers_test.cc | #ifndef QUICHE_BALSA_BALSA_HEADERS_H_
#define QUICHE_BALSA_BALSA_HEADERS_H_
#include <cstddef>
#include <cstring>
#include <functional>
#include <iterator>
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "quiche/balsa/balsa_enums.h"
#include "quiche/balsa/header_api.h"
#include "quiche/balsa/http_validation_policy.h"
#include "quiche/balsa/standard_header_map.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_callbacks.h"
namespace gfe2 {
class Http2HeaderValidator;
}
namespace quiche {
namespace test {
class BalsaHeadersTestPeer;
}
class QUICHE_EXPORT BalsaBuffer {
public:
static constexpr size_t kDefaultBlocksize = 4096;
struct QUICHE_EXPORT BufferBlock {
public:
std::unique_ptr<char[]> buffer;
size_t buffer_size = 0;
size_t bytes_free = 0;
size_t bytes_used() const { return buffer_size - bytes_free; }
char* start_of_unused_bytes() const { return buffer.get() + bytes_used(); }
BufferBlock() {}
BufferBlock(std::unique_ptr<char[]> buf, size_t size, size_t free)
: buffer(std::move(buf)), buffer_size(size), bytes_free(free) {}
BufferBlock(const BufferBlock&) = delete;
BufferBlock& operator=(const BufferBlock&) = delete;
BufferBlock(BufferBlock&&) = default;
BufferBlock& operator=(BufferBlock&&) = default;
void CopyFrom(const BufferBlock& rhs) {
QUICHE_DCHECK(this != &rhs);
buffer_size = rhs.buffer_size;
bytes_free = rhs.bytes_free;
if (rhs.buffer == nullptr) {
buffer = nullptr;
} else {
buffer = std::make_unique<char[]>(buffer_size);
memcpy(buffer.get(), rhs.buffer.get(), rhs.bytes_used());
}
}
};
typedef std::vector<BufferBlock> Blocks;
BalsaBuffer()
: blocksize_(kDefaultBlocksize), can_write_to_contiguous_buffer_(true) {}
explicit BalsaBuffer(size_t blocksize)
: blocksize_(blocksize), can_write_to_contiguous_buffer_(true) {}
BalsaBuffer(const BalsaBuffer&) = delete;
BalsaBuffer& operator=(const BalsaBuffer&) = delete;
BalsaBuffer(BalsaBuffer&&) = default;
BalsaBuffer& operator=(BalsaBuffer&&) = default;
size_t GetTotalBufferBlockSize() const {
size_t buffer_size = 0;
for (Blocks::const_iterator iter = blocks_.begin(); iter != blocks_.end();
++iter) {
buffer_size += iter->buffer_size;
}
return buffer_size;
}
size_t GetTotalBytesUsed() const {
size_t bytes_used = 0;
for (const auto& b : blocks_) {
bytes_used += b.bytes_used();
}
return bytes_used;
}
const char* GetPtr(Blocks::size_type block_idx) const {
QUICHE_DCHECK_LT(block_idx, blocks_.size())
<< block_idx << ", " << blocks_.size();
return block_idx >= blocks_.size() ? nullptr
: blocks_[block_idx].buffer.get();
}
char* GetPtr(Blocks::size_type block_idx) {
QUICHE_DCHECK_LT(block_idx, blocks_.size())
<< block_idx << ", " << blocks_.size();
return block_idx >= blocks_.size() ? nullptr
: blocks_[block_idx].buffer.get();
}
void WriteToContiguousBuffer(absl::string_view sp) {
if (sp.empty()) {
return;
}
QUICHE_CHECK(can_write_to_contiguous_buffer_);
if (blocks_.empty()) {
blocks_.push_back(AllocBlock());
}
QUICHE_DCHECK_GE(blocks_.size(), 1u);
if (blocks_[0].buffer == nullptr && sp.size() <= blocksize_) {
blocks_[0] = AllocBlock();
memcpy(blocks_[0].start_of_unused_bytes(), sp.data(), sp.size());
} else if (blocks_[0].bytes_free < sp.size()) {
const size_t old_storage_size_used = blocks_[0].bytes_used();
const size_t new_storage_size =
old_storage_size_used + (old_storage_size_used < sp.size()
? sp.size()
: old_storage_size_used);
std::unique_ptr<char[]> new_storage{new char[new_storage_size]};
char* old_storage = blocks_[0].buffer.get();
if (old_storage_size_used != 0u) {
memcpy(new_storage.get(), old_storage, old_storage_size_used);
}
memcpy(new_storage.get() + old_storage_size_used, sp.data(), sp.size());
blocks_[0].buffer = std::move(new_storage);
blocks_[0].bytes_free = new_storage_size - old_storage_size_used;
blocks_[0].buffer_size = new_storage_size;
} else {
memcpy(blocks_[0].start_of_unused_bytes(), sp.data(), sp.size());
}
blocks_[0].bytes_free -= sp.size();
}
void NoMoreWriteToContiguousBuffer() {
can_write_to_contiguous_buffer_ = false;
}
char* Reserve(size_t size, Blocks::size_type* block_buffer_idx) {
if (blocks_.empty()) {
blocks_.push_back(AllocBlock());
}
QUICHE_DCHECK_GE(blocks_.size(), 1u);
BufferBlock* block = nullptr;
Blocks::size_type block_idx = can_write_to_contiguous_buffer_ ? 1 : 0;
for (; block_idx < blocks_.size(); ++block_idx) {
if (blocks_[block_idx].bytes_free >= size) {
block = &blocks_[block_idx];
break;
}
}
if (block == nullptr) {
if (blocksize_ < size) {
blocks_.push_back(AllocCustomBlock(size));
} else {
blocks_.push_back(AllocBlock());
}
block = &blocks_.back();
}
char* storage = block->start_of_unused_bytes();
block->bytes_free -= size;
if (block_buffer_idx != nullptr) {
*block_buffer_idx = block_idx;
}
return storage;
}
void Clear() {
blocks_.clear();
blocks_.shrink_to_fit();
can_write_to_contiguous_buffer_ = true;
}
void CopyFrom(const BalsaBuffer& b) {
blocks_.resize(b.blocks_.size());
for (Blocks::size_type i = 0; i < blocks_.size(); ++i) {
blocks_[i].CopyFrom(b.blocks_[i]);
}
blocksize_ = b.blocksize_;
can_write_to_contiguous_buffer_ = b.can_write_to_contiguous_buffer_;
}
char* StartOfFirstBlock() const {
QUICHE_BUG_IF(bug_if_1182_1, blocks_.empty())
<< "First block not allocated yet!";
return blocks_.empty() ? nullptr : blocks_[0].buffer.get();
}
char* EndOfFirstBlock() const {
QUICHE_BUG_IF(bug_if_1182_2, blocks_.empty())
<< "First block not allocated yet!";
return blocks_.empty() ? nullptr : blocks_[0].start_of_unused_bytes();
}
size_t GetReadableBytesOfFirstBlock() const {
return blocks_.empty() ? 0 : blocks_[0].bytes_used();
}
bool can_write_to_contiguous_buffer() const {
return can_write_to_contiguous_buffer_;
}
size_t blocksize() const { return blocksize_; }
Blocks::size_type num_blocks() const { return blocks_.size(); }
size_t buffer_size(size_t idx) const { return blocks_[idx].buffer_size; }
size_t bytes_used(size_t idx) const { return blocks_[idx].bytes_used(); }
private:
BufferBlock AllocBlock() { return AllocCustomBlock(blocksize_); }
BufferBlock AllocCustomBlock(size_t blocksize) {
return BufferBlock{std::make_unique<char[]>(blocksize), blocksize,
blocksize};
}
Blocks blocks_;
size_t blocksize_;
bool can_write_to_contiguous_buffer_;
};
class QUICHE_EXPORT BalsaHeaders : public HeaderApi {
public:
struct QUICHE_EXPORT HeaderLineDescription {
HeaderLineDescription(size_t first_character_index, size_t key_end_index,
size_t value_begin_index, size_t last_character_index,
size_t buffer_base_index)
: first_char_idx(first_character_index),
key_end_idx(key_end_index),
value_begin_idx(value_begin_index),
last_char_idx(last_character_index),
buffer_base_idx(buffer_base_index),
skip(false) {}
HeaderLineDescription()
: first_char_idx(0),
key_end_idx(0),
value_begin_idx(0),
last_char_idx(0),
buffer_base_idx(0),
skip(false) {}
size_t KeyLength() const {
QUICHE_DCHECK_GE(key_end_idx, first_char_idx);
return key_end_idx - first_char_idx;
}
size_t ValuesLength() const {
QUICHE_DCHECK_GE(last_char_idx, value_begin_idx);
return last_char_idx - value_begin_idx;
}
size_t first_char_idx;
size_t key_end_idx;
size_t value_begin_idx;
size_t last_char_idx;
BalsaBuffer::Blocks::size_type buffer_base_idx;
bool skip;
};
using HeaderTokenList = std::vector<absl::string_view>;
class const_header_lines_iterator;
class const_header_lines_key_iterator;
template <typename IteratorType>
class QUICHE_EXPORT iterator_range {
public:
using iterator = IteratorType;
using const_iterator = IteratorType;
using value_type = typename std::iterator_traits<IteratorType>::value_type;
iterator_range(IteratorType begin_iterator, IteratorType end_iterator)
: begin_iterator_(std::move(begin_iterator)),
end_iterator_(std::move(end_iterator)) {}
IteratorType begin() const { return begin_iterator_; }
IteratorType end() const { return end_iterator_; }
private:
IteratorType begin_iterator_, end_iterator_;
};
using MultivaluedHeadersSet =
absl::flat_hash_set<absl::string_view, StringPieceCaseHash,
StringPieceCaseEqual>;
using MultivaluedHeadersValuesMap =
absl::flat_hash_map<absl::string_view, std::vector<absl::string_view>,
StringPieceCaseHash, StringPieceCaseEqual>;
BalsaHeaders()
: balsa_buffer_(4096),
content_length_(0),
content_length_status_(BalsaHeadersEnums::NO_CONTENT_LENGTH),
parsed_response_code_(0),
firstline_buffer_base_idx_(0),
whitespace_1_idx_(0),
non_whitespace_1_idx_(0),
whitespace_2_idx_(0),
non_whitespace_2_idx_(0),
whitespace_3_idx_(0),
non_whitespace_3_idx_(0),
whitespace_4_idx_(0),
transfer_encoding_is_chunked_(false) {}
explicit BalsaHeaders(size_t bufsize)
: balsa_buffer_(bufsize),
content_length_(0),
content_length_status_(BalsaHeadersEnums::NO_CONTENT_LENGTH),
parsed_response_code_(0),
firstline_buffer_base_idx_(0),
whitespace_1_idx_(0),
non_whitespace_1_idx_(0),
whitespace_2_idx_(0),
non_whitespace_2_idx_(0),
whitespace_3_idx_(0),
non_whitespace_3_idx_(0),
whitespace_4_idx_(0),
transfer_encoding_is_chunked_(false) {}
BalsaHeaders(const BalsaHeaders&) = delete;
BalsaHeaders& operator=(const BalsaHeaders&) = delete;
BalsaHeaders(BalsaHeaders&&) = default;
BalsaHeaders& operator=(BalsaHeaders&&) = default;
iterator_range<const_header_lines_iterator> lines() const;
iterator_range<const_header_lines_key_iterator> lines(
absl::string_view key) const;
const_header_lines_key_iterator GetIteratorForKey(
absl::string_view key) const;
const_header_lines_key_iterator header_lines_key_end() const;
void erase(const const_header_lines_iterator& it);
void Clear();
BalsaHeaders Copy() const {
BalsaHeaders copy;
copy.CopyFrom(*this);
return copy;
}
void CopyFrom(const BalsaHeaders& other);
void ReplaceOrAppendHeader(absl::string_view key,
absl::string_view value) override;
void AppendHeader(absl::string_view key, absl::string_view value) override;
void AppendToHeader(absl::string_view key, absl::string_view value) override;
void AppendToHeaderWithCommaAndSpace(absl::string_view key,
absl::string_view value) override;
using HeaderApi::GetHeader;
absl::string_view GetHeader(absl::string_view key) const override;
using HeaderApi::GetAllOfHeader;
void GetAllOfHeader(absl::string_view key,
std::vector<absl::string_view>* out) const override;
void GetAllOfHeaderIncludeRemoved(absl::string_view key,
std::vector<absl::string_view>* out) const;
using HeaderApi::GetAllOfHeaderAsString;
std::string GetAllOfHeaderAsString(absl::string_view key) const override;
inline bool HasHeader(absl::string_view key) const override {
return GetConstHeaderLinesIterator(key) != header_lines_.end();
}
bool HeaderHasValue(absl::string_view key,
absl::string_view value) const override {
return HeaderHasValueHelper(key, value, true);
}
bool HeaderHasValueIgnoreCase(absl::string_view key,
absl::string_view value) const override {
return HeaderHasValueHelper(key, value, false);
}
bool HasNonEmptyHeader(absl::string_view key) const override;
const_header_lines_iterator GetHeaderPosition(absl::string_view key) const;
void RemoveAllOfHeaderInList(const HeaderTokenList& keys) override;
void RemoveAllOfHeader(absl::string_view key) override;
void RemoveAllHeadersWithPrefix(absl::string_view prefix) override;
bool HasHeadersWithPrefix(absl::string_view prefix) const override;
void GetAllOfHeaderWithPrefix(
absl::string_view prefix,
std::vector<std::pair<absl::string_view, absl::string_view>>* out)
const override;
void GetAllHeadersWithLimit(
std::vector<std::pair<absl::string_view, absl::string_view>>* out,
int limit) const override;
size_t RemoveValue(absl::string_view key, absl::string_view value);
size_t GetSizeForWriteBuffer() const override;
enum class CaseOption { kNoModification, kLowercase, kPropercase };
enum class CoalesceOption { kNoCoalesce, kCoalesce };
template <typename Buffer>
void WriteHeaderAndEndingToBuffer(Buffer* buffer, CaseOption case_option,
CoalesceOption coalesce_option) const {
WriteToBuffer(buffer, case_option, coalesce_option);
WriteHeaderEndingToBuffer(buffer);
}
template <typename Buffer>
void WriteHeaderAndEndingToBuffer(Buffer* buffer) const {
WriteHeaderAndEndingToBuffer(buffer, CaseOption::kNoModification,
CoalesceOption::kNoCoalesce);
}
template <typename Buffer>
static void WriteHeaderEndingToBuffer(Buffer* buffer) {
buffer->WriteString("\r\n");
}
template <typename Buffer>
void WriteToBuffer(Buffer* buffer, CaseOption case_option,
CoalesceOption coalesce_option) const;
template <typename Buffer>
void WriteToBuffer(Buffer* buffer) const {
WriteToBuffer(buffer, CaseOption::kNoModification,
CoalesceOption::kNoCoalesce);
}
template <typename Buffer>
void WriteToBufferCoalescingMultivaluedHeaders(
Buffer* buffer, const MultivaluedHeadersSet& multivalued_headers,
CaseOption case_option) const;
void GetValuesOfMultivaluedHeaders(
const MultivaluedHeadersSet& multivalued_headers,
MultivaluedHeadersValuesMap* multivalues) const;
static std::string ToPropercase(absl::string_view header) {
std::string copy = std::string(header);
bool should_uppercase = true;
for (char& c : copy) {
if (!absl::ascii_isalnum(c)) {
should_uppercase = true;
} else if (should_uppercase) {
c = absl::ascii_toupper(c);
should_uppercase = false;
} else {
c = absl::ascii_tolower(c);
}
}
return copy;
}
template <typename Buffer>
void WriteHeaderKeyToBuffer(Buffer* buffer, absl::string_view key,
CaseOption case_option) const {
if (case_option == CaseOption::kLowercase) {
buffer->WriteString(absl::AsciiStrToLower(key));
} else if (case_option == CaseOption::kPropercase) {
const auto& header_set = quiche::GetStandardHeaderSet();
auto it = header_set.find(key);
if (it != header_set.end()) {
buffer->WriteString(*it);
} else {
buffer->WriteString(ToPropercase(key));
}
} else {
buffer->WriteString(key);
}
}
template <typename Buffer>
void WriteHeaderLineToBuffer(Buffer* buffer, absl::string_view key,
absl::string_view value,
CaseOption case_option) const {
if (!key.empty()) {
WriteHeaderKeyToBuffer(buffer, key, case_option);
buffer->WriteString(": ");
buffer->WriteString(value);
buffer->WriteString("\r\n");
}
} | #include "quiche/balsa/balsa_headers.h"
#include <cstring>
#include <limits>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/macros.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "quiche/balsa/balsa_enums.h"
#include "quiche/balsa/balsa_frame.h"
#include "quiche/balsa/simple_buffer.h"
#include "quiche/common/platform/api/quiche_expect_bug.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/platform/api/quiche_test.h"
using absl::make_unique;
using testing::AnyOf;
using testing::Combine;
using testing::ElementsAre;
using testing::Eq;
using testing::StrEq;
using testing::ValuesIn;
namespace quiche {
namespace test {
class BalsaHeadersTestPeer {
public:
static void WriteFromFramer(BalsaHeaders* headers, const char* ptr,
size_t size) {
headers->WriteFromFramer(ptr, size);
}
};
namespace {
class BalsaBufferTest : public QuicheTest {
public:
void CreateBuffer(size_t blocksize) {
buffer_ = std::make_unique<BalsaBuffer>(blocksize);
}
void CreateBuffer() { buffer_ = std::make_unique<BalsaBuffer>(); }
static std::unique_ptr<BalsaBuffer> CreateUnmanagedBuffer(size_t blocksize) {
return std::make_unique<BalsaBuffer>(blocksize);
}
absl::string_view Write(absl::string_view sp, size_t* block_buffer_idx) {
if (sp.empty()) {
return sp;
}
char* storage = buffer_->Reserve(sp.size(), block_buffer_idx);
memcpy(storage, sp.data(), sp.size());
return absl::string_view(storage, sp.size());
}
protected:
std::unique_ptr<BalsaBuffer> buffer_;
};
using BufferBlock = BalsaBuffer::BufferBlock;
BufferBlock MakeBufferBlock(const std::string& s) {
BufferBlock block{make_unique<char[]>(s.size()), s.size() * 2, s.size()};
std::memcpy(block.buffer.get(), s.data(), s.size());
return block;
}
BalsaHeaders CreateHTTPHeaders(bool request, absl::string_view s) {
BalsaHeaders headers;
BalsaFrame framer;
framer.set_is_request(request);
framer.set_balsa_headers(&headers);
QUICHE_CHECK_EQ(s.size(), framer.ProcessInput(s.data(), s.size()));
QUICHE_CHECK(framer.MessageFullyRead());
return headers;
}
class BufferBlockTest
: public QuicheTestWithParam<std::tuple<const char*, const char*>> {};
TEST_P(BufferBlockTest, CopyFrom) {
const std::string s1 = std::get<0>(GetParam());
const std::string s2 = std::get<1>(GetParam());
BufferBlock block;
block.CopyFrom(MakeBufferBlock(s1));
EXPECT_EQ(s1.size(), block.bytes_free);
ASSERT_EQ(2 * s1.size(), block.buffer_size);
EXPECT_EQ(0, memcmp(s1.data(), block.buffer.get(), s1.size()));
block.CopyFrom(MakeBufferBlock(s2));
EXPECT_EQ(s2.size(), block.bytes_free);
ASSERT_EQ(2 * s2.size(), block.buffer_size);
EXPECT_EQ(0, memcmp(s2.data(), block.buffer.get(), s2.size()));
}
const char* block_strings[] = {"short string", "longer than the other string"};
INSTANTIATE_TEST_SUITE_P(VariousSizes, BufferBlockTest,
Combine(ValuesIn(block_strings),
ValuesIn(block_strings)));
TEST_F(BalsaBufferTest, BlocksizeSet) {
CreateBuffer();
EXPECT_EQ(BalsaBuffer::kDefaultBlocksize, buffer_->blocksize());
CreateBuffer(1024);
EXPECT_EQ(1024u, buffer_->blocksize());
}
TEST_F(BalsaBufferTest, GetMemorySize) {
CreateBuffer(10);
EXPECT_EQ(0u, buffer_->GetTotalBytesUsed());
EXPECT_EQ(0u, buffer_->GetTotalBufferBlockSize());
BalsaBuffer::Blocks::size_type index;
buffer_->Reserve(1024, &index);
EXPECT_EQ(10u + 1024u, buffer_->GetTotalBufferBlockSize());
EXPECT_EQ(1024u, buffer_->GetTotalBytesUsed());
}
TEST_F(BalsaBufferTest, ManyWritesToContiguousBuffer) {
CreateBuffer(0);
std::string data = "0123456789";
for (int i = 0; i < 120 * 1000; ++i) {
buffer_->WriteToContiguousBuffer(data);
}
}
TEST_F(BalsaBufferTest, CopyFrom) {
CreateBuffer(10);
std::unique_ptr<BalsaBuffer> ptr = CreateUnmanagedBuffer(1024);
ASSERT_EQ(1024u, ptr->blocksize());
EXPECT_EQ(0u, ptr->num_blocks());
std::string data1 = "foobarbaz01";
buffer_->WriteToContiguousBuffer(data1);
buffer_->NoMoreWriteToContiguousBuffer();
std::string data2 = "12345";
Write(data2, nullptr);
std::string data3 = "6789";
Write(data3, nullptr);
std::string data4 = "123456789012345";
Write(data3, nullptr);
ptr->CopyFrom(*buffer_);
EXPECT_EQ(ptr->can_write_to_contiguous_buffer(),
buffer_->can_write_to_contiguous_buffer());
ASSERT_EQ(ptr->num_blocks(), buffer_->num_blocks());
for (size_t i = 0; i < buffer_->num_blocks(); ++i) {
ASSERT_EQ(ptr->bytes_used(i), buffer_->bytes_used(i));
ASSERT_EQ(ptr->buffer_size(i), buffer_->buffer_size(i));
EXPECT_EQ(0,
memcmp(ptr->GetPtr(i), buffer_->GetPtr(i), ptr->bytes_used(i)));
}
}
TEST_F(BalsaBufferTest, ClearWorks) {
CreateBuffer(10);
std::string data1 = "foobarbaz01";
buffer_->WriteToContiguousBuffer(data1);
buffer_->NoMoreWriteToContiguousBuffer();
std::string data2 = "12345";
Write(data2, nullptr);
std::string data3 = "6789";
Write(data3, nullptr);
std::string data4 = "123456789012345";
Write(data3, nullptr);
buffer_->Clear();
EXPECT_TRUE(buffer_->can_write_to_contiguous_buffer());
EXPECT_EQ(10u, buffer_->blocksize());
EXPECT_EQ(0u, buffer_->num_blocks());
}
TEST_F(BalsaBufferTest, ClearWorksWhenLargerThanBlocksize) {
CreateBuffer(10);
std::string data1 = "foobarbaz01lkjasdlkjasdlkjasd";
buffer_->WriteToContiguousBuffer(data1);
buffer_->NoMoreWriteToContiguousBuffer();
std::string data2 = "12345";
Write(data2, nullptr);
std::string data3 = "6789";
Write(data3, nullptr);
std::string data4 = "123456789012345";
Write(data3, nullptr);
buffer_->Clear();
EXPECT_TRUE(buffer_->can_write_to_contiguous_buffer());
EXPECT_EQ(10u, buffer_->blocksize());
EXPECT_EQ(0u, buffer_->num_blocks());
}
TEST_F(BalsaBufferTest, ContiguousWriteSmallerThanBlocksize) {
CreateBuffer(1024);
std::string data1 = "foo";
buffer_->WriteToContiguousBuffer(data1);
std::string composite = data1;
const char* buf_ptr = buffer_->GetPtr(0);
ASSERT_LE(composite.size(), buffer_->buffer_size(0));
EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size()));
std::string data2 = "barbaz";
buffer_->WriteToContiguousBuffer(data2);
composite += data2;
buf_ptr = buffer_->GetPtr(0);
ASSERT_LE(composite.size(), buffer_->buffer_size(0));
EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size()));
}
TEST_F(BalsaBufferTest, SingleContiguousWriteLargerThanBlocksize) {
CreateBuffer(10);
std::string data1 = "abracadabrawords";
buffer_->WriteToContiguousBuffer(data1);
std::string composite = data1;
const char* buf_ptr = buffer_->GetPtr(0);
ASSERT_LE(data1.size(), buffer_->buffer_size(0));
EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size()))
<< composite << "\n"
<< absl::string_view(buf_ptr, buffer_->bytes_used(0));
}
TEST_F(BalsaBufferTest, ContiguousWriteLargerThanBlocksize) {
CreateBuffer(10);
std::string data1 = "123456789";
buffer_->WriteToContiguousBuffer(data1);
std::string composite = data1;
ASSERT_LE(10u, buffer_->buffer_size(0));
std::string data2 = "0123456789";
buffer_->WriteToContiguousBuffer(data2);
composite += data2;
const char* buf_ptr = buffer_->GetPtr(0);
ASSERT_LE(composite.size(), buffer_->buffer_size(0));
EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size()))
<< "composite: " << composite << "\n"
<< " actual: " << absl::string_view(buf_ptr, buffer_->bytes_used(0));
}
TEST_F(BalsaBufferTest, TwoContiguousWritesLargerThanBlocksize) {
CreateBuffer(5);
std::string data1 = "123456";
buffer_->WriteToContiguousBuffer(data1);
std::string composite = data1;
ASSERT_LE(composite.size(), buffer_->buffer_size(0));
std::string data2 = "7890123";
buffer_->WriteToContiguousBuffer(data2);
composite += data2;
const char* buf_ptr = buffer_->GetPtr(0);
ASSERT_LE(composite.size(), buffer_->buffer_size(0));
EXPECT_EQ(0, memcmp(composite.data(), buf_ptr, composite.size()))
<< "composite: " << composite << "\n"
<< " actual: " << absl::string_view(buf_ptr, buffer_->bytes_used(0));
}
TEST_F(BalsaBufferTest, WriteSmallerThanBlocksize) {
CreateBuffer(5);
std::string data1 = "1234";
size_t block_idx = 0;
absl::string_view write_result = Write(data1, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
CreateBuffer(5);
data1 = "1234";
block_idx = 0;
write_result = Write(data1, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
}
TEST_F(BalsaBufferTest, TwoWritesSmallerThanBlocksizeThenAnotherWrite) {
CreateBuffer(10);
std::string data1 = "12345";
size_t block_idx = 0;
absl::string_view write_result = Write(data1, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
std::string data2 = "data2";
block_idx = 0;
write_result = Write(data2, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data2));
std::string data3 = "data3";
block_idx = 0;
write_result = Write(data3, &block_idx);
ASSERT_EQ(2u, block_idx);
EXPECT_THAT(write_result, StrEq(data3));
CreateBuffer(10);
buffer_->NoMoreWriteToContiguousBuffer();
data1 = "12345";
block_idx = 0;
write_result = Write(data1, &block_idx);
ASSERT_EQ(0u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
data2 = "data2";
block_idx = 0;
write_result = Write(data2, &block_idx);
ASSERT_EQ(0u, block_idx);
EXPECT_THAT(write_result, StrEq(data2));
data3 = "data3";
block_idx = 0;
write_result = Write(data3, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data3));
}
TEST_F(BalsaBufferTest, WriteLargerThanBlocksize) {
CreateBuffer(5);
std::string data1 = "123456789";
size_t block_idx = 0;
absl::string_view write_result = Write(data1, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
CreateBuffer(5);
buffer_->NoMoreWriteToContiguousBuffer();
data1 = "123456789";
block_idx = 0;
write_result = Write(data1, &block_idx);
ASSERT_EQ(1u, block_idx);
EXPECT_THAT(write_result, StrEq(data1));
}
TEST_F(BalsaBufferTest, ContiguousThenTwoSmallerThanBlocksize) {
CreateBuffer(5);
std::string data1 = "1234567890";
buffer_->WriteToContiguousBuffer(data1);
size_t block_idx = 0;
std::string data2 = "1234";
absl::string_view write_result = Write(data2, &block_idx);
ASSERT_EQ(1u, block_idx);
std::string data3 = "1234";
write_result = Write(data3, &block_idx);
ASSERT_EQ(2u, block_idx);
}
TEST_F(BalsaBufferTest, AccessFirstBlockUninitialized) {
CreateBuffer(5);
EXPECT_EQ(0u, buffer_->GetReadableBytesOfFirstBlock());
EXPECT_QUICHE_BUG(buffer_->StartOfFirstBlock(),
"First block not allocated yet!");
EXPECT_QUICHE_BUG(buffer_->EndOfFirstBlock(),
"First block not allocated yet!");
}
TEST_F(BalsaBufferTest, AccessFirstBlockInitialized) {
CreateBuffer(5);
std::string data1 = "1234567890";
buffer_->WriteToContiguousBuffer(data1);
const char* start = buffer_->StartOfFirstBlock();
EXPECT_TRUE(start != nullptr);
const char* end = buffer_->EndOfFirstBlock();
EXPECT_TRUE(end != nullptr);
EXPECT_EQ(data1.length(), static_cast<size_t>(end - start));
EXPECT_EQ(data1.length(), buffer_->GetReadableBytesOfFirstBlock());
}
TEST(BalsaHeaders, CanAssignBeginToIterator) {
{
BalsaHeaders header;
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
static_cast<void>(chli);
}
{
const BalsaHeaders header;
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
static_cast<void>(chli);
}
}
TEST(BalsaHeaders, CanAssignEndToIterator) {
{
BalsaHeaders header;
BalsaHeaders::const_header_lines_iterator chli = header.lines().end();
static_cast<void>(chli);
}
{
const BalsaHeaders header;
BalsaHeaders::const_header_lines_iterator chli = header.lines().end();
static_cast<void>(chli);
}
}
TEST(BalsaHeaders, ReplaceOrAppendHeaderTestAppending) {
BalsaHeaders header;
std::string key_1 = "key_1";
std::string value_1 = "value_1";
header.ReplaceOrAppendHeader(key_1, value_1);
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(absl::string_view("key_1"), chli->first);
ASSERT_EQ(absl::string_view("value_1"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, ReplaceOrAppendHeaderTestReplacing) {
BalsaHeaders header;
std::string key_1 = "key_1";
std::string value_1 = "value_1";
std::string key_2 = "key_2";
header.ReplaceOrAppendHeader(key_1, value_1);
header.ReplaceOrAppendHeader(key_2, value_1);
std::string value_2 = "value_2_string";
header.ReplaceOrAppendHeader(key_1, value_2);
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(key_1, chli->first);
ASSERT_EQ(value_2, chli->second);
++chli;
ASSERT_EQ(key_2, chli->first);
ASSERT_EQ(value_1, chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, ReplaceOrAppendHeaderTestReplacingMultiple) {
BalsaHeaders header;
std::string key_1 = "key_1";
std::string key_2 = "key_2";
std::string value_1 = "val_1";
std::string value_2 = "val_2";
std::string value_3 =
"value_3_is_longer_than_value_1_and_value_2_and_their_keys";
header.AppendHeader(key_1, value_1);
header.AppendHeader(key_1, value_2);
header.AppendHeader(key_2, value_1);
header.ReplaceOrAppendHeader(key_1, value_3);
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(key_1, chli->first);
ASSERT_EQ(value_3, chli->second);
++chli;
ASSERT_EQ(key_2, chli->first);
ASSERT_EQ(value_1, chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
header.ReplaceOrAppendHeader(key_1, value_1);
chli = header.lines().begin();
ASSERT_EQ(key_1, chli->first);
ASSERT_EQ(value_1, chli->second);
++chli;
ASSERT_EQ(key_2, chli->first);
ASSERT_EQ(value_1, chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, AppendHeaderAndIteratorTest1) {
BalsaHeaders header;
ASSERT_EQ(header.lines().begin(), header.lines().end());
{
std::string key_1 = "key_1";
std::string value_1 = "value_1";
header.AppendHeader(key_1, value_1);
key_1 = "garbage";
value_1 = "garbage";
}
ASSERT_NE(header.lines().begin(), header.lines().end());
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_1"), chli->first);
ASSERT_EQ(absl::string_view("value_1"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, AppendHeaderAndIteratorTest2) {
BalsaHeaders header;
ASSERT_EQ(header.lines().begin(), header.lines().end());
{
std::string key_1 = "key_1";
std::string value_1 = "value_1";
header.AppendHeader(key_1, value_1);
key_1 = "garbage";
value_1 = "garbage";
}
{
std::string key_2 = "key_2";
std::string value_2 = "value_2";
header.AppendHeader(key_2, value_2);
key_2 = "garbage";
value_2 = "garbage";
}
ASSERT_NE(header.lines().begin(), header.lines().end());
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_1"), chli->first);
ASSERT_EQ(absl::string_view("value_1"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_2"), chli->first);
ASSERT_EQ(absl::string_view("value_2"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, AppendHeaderAndIteratorTest3) {
BalsaHeaders header;
ASSERT_EQ(header.lines().begin(), header.lines().end());
{
std::string key_1 = "key_1";
std::string value_1 = "value_1";
header.AppendHeader(key_1, value_1);
key_1 = "garbage";
value_1 = "garbage";
}
{
std::string key_2 = "key_2";
std::string value_2 = "value_2";
header.AppendHeader(key_2, value_2);
key_2 = "garbage";
value_2 = "garbage";
}
{
std::string key_3 = "key_3";
std::string value_3 = "value_3";
header.AppendHeader(key_3, value_3);
key_3 = "garbage";
value_3 = "garbage";
}
ASSERT_NE(header.lines().begin(), header.lines().end());
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
ASSERT_EQ(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_1"), chli->first);
ASSERT_EQ(absl::string_view("value_1"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_2"), chli->first);
ASSERT_EQ(absl::string_view("value_2"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_3"), chli->first);
ASSERT_EQ(absl::string_view("value_3"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, AppendHeaderAndTestEraseWithIterator) {
BalsaHeaders header;
ASSERT_EQ(header.lines().begin(), header.lines().end());
{
std::string key_1 = "key_1";
std::string value_1 = "value_1";
header.AppendHeader(key_1, value_1);
key_1 = "garbage";
value_1 = "garbage";
}
{
std::string key_2 = "key_2";
std::string value_2 = "value_2";
header.AppendHeader(key_2, value_2);
key_2 = "garbage";
value_2 = "garbage";
}
{
std::string key_3 = "key_3";
std::string value_3 = "value_3";
header.AppendHeader(key_3, value_3);
key_3 = "garbage";
value_3 = "garbage";
}
BalsaHeaders::const_header_lines_iterator chli = header.lines().begin();
++chli;
ASSERT_EQ(absl::string_view("key_2"), chli->first);
header.erase(chli);
chli = header.lines().begin();
ASSERT_NE(header.lines().begin(), header.lines().end());
ASSERT_EQ(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_1"), chli->first);
ASSERT_EQ(absl::string_view("value_1"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_NE(header.lines().end(), chli);
ASSERT_EQ(absl::string_view("key_3"), chli->first);
ASSERT_EQ(absl::string_view("value_3"), chli->second);
++chli;
ASSERT_NE(header.lines().begin(), chli);
ASSERT_EQ(header.lines().end(), chli);
}
TEST(BalsaHeaders, TestSetFirstlineInAdditionalBuffer) {
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0"));
}
TEST(BalsaHeaders, TestSetFirstlineInOriginalBufferAndIsShorterThanOriginal) {
BalsaHeaders headers = CreateHTTPHeaders(true,
"GET /foobar HTTP/1.0\r\n"
"\r\n");
ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0"));
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0"));
}
TEST(BalsaHeaders, TestSetFirstlineInOriginalBufferAndIsLongerThanOriginal) {
BalsaHeaders headers = CreateHTTPHeaders(true,
"GET / HTTP/1.0\r\n"
"some_key: some_value\r\n"
"another_key: another_value\r\n"
"\r\n");
ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0"));
headers.erase(headers.lines().begin());
headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0"));
}
TEST(BalsaHeaders, TestSetFirstlineInAdditionalDataAndIsShorterThanOriginal) {
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0"));
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0"));
}
TEST(BalsaHeaders, TestSetFirstlineInAdditionalDataAndIsLongerThanOriginal) {
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET / HTTP/1.0"));
headers.SetRequestFirstlineFromStringPieces("GET", "/foobar", "HTTP/1.0");
ASSERT_THAT(headers.first_line(), StrEq("GET /foobar HTTP/1.0"));
}
TEST(BalsaHeaders, TestDeletingSubstring) {
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
headers.AppendHeader("key1", "value1");
headers.AppendHeader("key2", "value2");
headers.AppendHeader("key", "value");
headers.AppendHeader("unrelated", "value");
headers.RemoveAllOfHeader("key");
EXPECT_TRUE(headers.HasHeader("key1"));
EXPECT_TRUE(headers.HasHeader("key2"));
EXPECT_TRUE(headers.HasHeader("unrelated"));
EXPECT_FALSE(headers.HasHeader("key"));
EXPECT_TRUE(headers.HasHeadersWithPrefix("key"));
EXPECT_TRUE(headers.HasHeadersWithPrefix("KeY"));
EXPECT_TRUE(headers.HasHeadersWithPrefix("UNREL"));
EXPECT_FALSE(headers.HasHeadersWithPrefix("key3"));
EXPECT_FALSE(headers.GetHeader("key1").empty());
EXPECT_FALSE(headers.GetHeader("KEY1").empty());
EXPECT_FALSE(headers.GetHeader("key2").empty());
EXPECT_FALSE(headers.GetHeader("unrelated").empty());
EXPECT_TRUE(headers.GetHeader("key").empty());
headers.AppendHeader("key", "");
EXPECT_TRUE(headers.HasHeader("key"));
EXPECT_TRUE(headers.HasHeadersWithPrefix("key"));
EXPECT_TRUE(headers.GetHeader("key").empty());
headers.RemoveAllHeadersWithPrefix("key");
EXPECT_FALSE(headers.HasHeader("key1"));
EXPECT_FALSE(headers.HasHeader("key2"));
EXPECT_TRUE(headers.HasHeader("unrelated"));
EXPECT_FALSE(headers.HasHeader("key"));
EXPECT_FALSE(headers.HasHeadersWithPrefix("key"));
EXPECT_FALSE(headers.HasHeadersWithPrefix("key1"));
EXPECT_FALSE(headers.HasHeadersWithPrefix("key2"));
EXPECT_FALSE(headers.HasHeadersWithPrefix("kEy"));
EXPECT_TRUE(headers.HasHeadersWithPrefix("unrelated"));
EXPECT_TRUE(headers.GetHeader("key1").empty());
EXPECT_TRUE(headers.GetHeader("key2").empty());
EXPECT_FALSE(headers.GetHeader("unrelated").empty());
EXPECT_TRUE(headers.GetHeader("key").empty());
}
TEST(BalsaHeaders, TestRemovingValues) {
{
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
headers.AppendHeader("hi", "hello");
headers.AppendHeader("key1", "val1");
headers.AppendHeader("key1", "value2");
headers.AppendHeader("key1", "value3");
headers.AppendHeader("key2", "value4");
headers.AppendHeader("unrelated", "value");
EXPECT_EQ(0u, headers.RemoveValue("key1", ""));
EXPECT_EQ(1u, headers.RemoveValue("key1", "value2"));
std::string key1_vals = headers.GetAllOfHeaderAsString("key1");
EXPECT_THAT(key1_vals, StrEq("val1,value3"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "val1"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "value3"));
EXPECT_EQ("value4", headers.GetHeader("key2"));
EXPECT_EQ("hello", headers.GetHeader("hi"));
EXPECT_EQ("value", headers.GetHeader("unrelated"));
EXPECT_FALSE(headers.HeaderHasValue("key1", "value2"));
EXPECT_EQ(1u, headers.RemoveValue("key1", "value3"));
key1_vals = headers.GetAllOfHeaderAsString("key1");
EXPECT_THAT(key1_vals, StrEq("val1"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "val1"));
EXPECT_EQ("value4", headers.GetHeader("key2"));
EXPECT_EQ("hello", headers.GetHeader("hi"));
EXPECT_EQ("value", headers.GetHeader("unrelated"));
EXPECT_FALSE(headers.HeaderHasValue("key1", "value3"));
EXPECT_FALSE(headers.HeaderHasValue("key1", "value2"));
}
{
BalsaHeaders headers;
headers.SetRequestFirstlineFromStringPieces("GET", "/", "HTTP/1.0");
headers.AppendHeader("key1", "value1");
headers.AppendHeader("key1", "value2, value3,value2");
headers.AppendHeader("key1", "value4 ,value2,value5,val6");
headers.AppendHeader("key1", "value2, value2 , value2");
headers.AppendHeader("key1", " value2 , value2 ");
headers.AppendHeader("key1", " value2 a");
headers.AppendHeader("key1", "");
headers.AppendHeader("key1", ", ,,");
headers.AppendHeader("unrelated", "value");
EXPECT_EQ(8u, headers.RemoveValue("key1", "value2"));
std::string key1_vals = headers.GetAllOfHeaderAsString("key1");
EXPECT_THAT(key1_vals,
StrEq("value1,value3,value4 ,value5,val6,value2 a,,, ,,"));
EXPECT_EQ("value", headers.GetHeader("unrelated"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "value1"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "value3"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "value4"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "value5"));
EXPECT_TRUE(headers.HeaderHasValue("key1", "val6"));
EXPECT_FALSE(headers.HeaderHasValue("key1", "value2"));
}
{
const absl::string_view key("key");
const absl::string_view value1("foo\0bar", 7);
const absl::string_view value2("value2");
const std::string value = absl::StrCat(value1, ",", value2);
{
BalsaHeaders headers;
headers.AppendHeader(key, value);
EXPECT_TRUE(headers.HeaderHasValue(key, value1));
EXPECT_TRUE(headers.HeaderHasValue(key, value2));
EXPECT_EQ(value, headers.GetAllOfHeaderAsString(key));
EXPECT_EQ(1u, headers.RemoveValue(key, value2));
EXPECT_TRUE(headers.HeaderHasValue(key, value1));
EXPECT_FALSE(headers.HeaderHasValue(key, value2));
EXPECT_EQ(value1, headers.GetAllOfHeaderAsString(key));
}
{
BalsaHeaders headers;
headers.AppendHeader(key, value1);
headers.AppendHeader(key, value2);
EXPECT_TRUE(headers.HeaderHasValue(key, value1));
EXPECT_TRUE(headers.HeaderHasValue(key, value2));
EXPECT_EQ(value, headers.GetAllOfHeaderAsString(key));
EXPECT_EQ(1u, headers.RemoveValue(key, value2));
EXPECT_TRUE(headers.HeaderHasValue(key, value1));
EXPECT_FALSE(headers.HeaderHasValue(key, value2));
EXPECT_EQ(value1, headers.GetAllOfHeaderAsString(key));
}
}
}
TEST(BalsaHeaders, ZeroAppendToHeaderWithCommaAndSpace) {
BalsaHeaders headers = CreateHTTPHeaders(true,
"GET / HTTP/1.0\r\n"
"\r\n");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "1.1.1.1");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "2.2.2.2");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4");
EXPECT_THAT(headers.GetAllOfHeader("X-Forwarded-For"),
ElementsAre("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4"));
}
TEST(BalsaHeaders, SingleAppendToHeaderWithCommaAndSpace) {
BalsaHeaders headers = CreateHTTPHeaders(true,
"GET / HTTP/1.0\r\n"
"X-Forwarded-For: 1.1.1.1\r\n"
"\r\n");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "2.2.2.2");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "5.5.5.5");
EXPECT_THAT(headers.GetAllOfHeader("X-Forwarded-For"),
ElementsAre("1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 5.5.5.5"));
}
TEST(BalsaHeaders, MultipleAppendToHeaderWithCommaAndSpace) {
BalsaHeaders headers = CreateHTTPHeaders(true,
"GET / HTTP/1.0\r\n"
"X-Forwarded-For: 1.1.1.1\r\n"
"X-Forwarded-For: 2.2.2.2\r\n"
"\r\n");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "3.3.3.3");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "4.4.4.4");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "5.5.5.5");
headers.AppendToHeaderWithCommaAndSpace("X-Forwarded-For", "6.6.6.6"); |
459 | cpp | google/quiche | web_transport_priority_scheduler | quiche/web_transport/web_transport_priority_scheduler.cc | quiche/web_transport/web_transport_priority_scheduler_test.cc | #ifndef QUICHE_WEB_TRANSPORT_WEB_TRANSPORT_PRIORITY_SCHEDULER_H_
#define QUICHE_WEB_TRANSPORT_WEB_TRANSPORT_PRIORITY_SCHEDULER_H_
#include <cstddef>
#include <optional>
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "absl/container/node_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "quiche/common/btree_scheduler.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/web_transport/web_transport.h"
namespace webtransport {
class QUICHE_EXPORT PriorityScheduler {
public:
bool HasRegistered() const { return active_groups_.HasRegistered(); }
bool HasScheduled() const { return active_groups_.HasScheduled(); }
size_t NumScheduled() const {
size_t total = 0;
for (const auto& [group_id, group_scheduler] : per_group_schedulers_) {
total += group_scheduler.NumScheduled();
}
return total;
}
absl::Status Register(StreamId stream_id, const StreamPriority& priority);
absl::Status Unregister(StreamId stream_id);
absl::Status UpdateSendOrder(StreamId stream_id, SendOrder new_send_order);
absl::Status UpdateSendGroup(StreamId stream_id, SendGroupId new_send_group);
absl::StatusOr<bool> ShouldYield(StreamId id) const;
std::optional<StreamPriority> GetPriorityFor(StreamId stream_id) const;
absl::StatusOr<StreamId> PopFront();
absl::Status Schedule(StreamId stream_id);
bool IsScheduled(StreamId stream_id) const;
private:
class SinglePriority {
public:
bool operator==(const SinglePriority&) const { return true; }
bool operator!=(const SinglePriority&) const { return false; }
bool operator<(const SinglePriority&) const { return false; }
bool operator>(const SinglePriority&) const { return false; }
bool operator<=(const SinglePriority&) const { return true; }
bool operator>=(const SinglePriority&) const { return true; }
};
using PerGroupScheduler = quiche::BTreeScheduler<StreamId, SendOrder>;
using GroupSchedulerPair = std::pair<const SendGroupId, PerGroupScheduler>;
quiche::BTreeScheduler<SendGroupId, SinglePriority> active_groups_;
absl::node_hash_map<SendGroupId, PerGroupScheduler> per_group_schedulers_;
absl::flat_hash_map<StreamId, GroupSchedulerPair*> stream_to_group_map_;
PerGroupScheduler* SchedulerForStream(StreamId stream_id) {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return nullptr;
}
return &it->second->second;
}
const PerGroupScheduler* SchedulerForStream(StreamId stream_id) const {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return nullptr;
}
return &it->second->second;
}
};
}
#endif
#include "quiche/web_transport/web_transport_priority_scheduler.h"
#include <optional>
#include <utility>
#include "absl/cleanup/cleanup.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "quiche/common/quiche_status_utils.h"
#include "quiche/web_transport/web_transport.h"
namespace webtransport {
absl::Status PriorityScheduler::Register(StreamId stream_id,
const StreamPriority& priority) {
auto [it, success] = stream_to_group_map_.insert({stream_id, nullptr});
if (!success) {
return absl::AlreadyExistsError("Provided stream ID already registered");
}
auto cleanup_nullptr_map_entry =
absl::MakeCleanup([&] { stream_to_group_map_.erase(stream_id); });
auto [scheduler_it, scheduler_created] =
per_group_schedulers_.try_emplace(priority.send_group_id);
if (scheduler_created) {
QUICHE_RETURN_IF_ERROR(active_groups_.Register(priority.send_group_id, {}));
}
PerGroupScheduler& scheduler = scheduler_it->second;
QUICHE_RETURN_IF_ERROR(scheduler.Register(stream_id, priority.send_order));
it->second = &*scheduler_it;
std::move(cleanup_nullptr_map_entry).Cancel();
return absl::OkStatus();
}
absl::Status PriorityScheduler::Unregister(StreamId stream_id) {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return absl::NotFoundError("Stream ID not registered");
}
SendGroupId group_id = it->second->first;
PerGroupScheduler* group_scheduler = &it->second->second;
stream_to_group_map_.erase(it);
QUICHE_RETURN_IF_ERROR(group_scheduler->Unregister(stream_id));
if (!group_scheduler->HasRegistered()) {
per_group_schedulers_.erase(group_id);
QUICHE_RETURN_IF_ERROR(active_groups_.Unregister(group_id));
}
return absl::OkStatus();
}
absl::Status PriorityScheduler::UpdateSendOrder(StreamId stream_id,
SendOrder new_send_order) {
PerGroupScheduler* scheduler = SchedulerForStream(stream_id);
if (scheduler == nullptr) {
return absl::NotFoundError("Stream ID not registered");
}
return scheduler->UpdatePriority(stream_id, new_send_order);
}
absl::Status PriorityScheduler::UpdateSendGroup(StreamId stream_id,
SendGroupId new_send_group) {
PerGroupScheduler* scheduler = SchedulerForStream(stream_id);
if (scheduler == nullptr) {
return absl::NotFoundError("Stream ID not registered");
}
bool is_scheduled = scheduler->IsScheduled(stream_id);
std::optional<SendOrder> send_order = scheduler->GetPriorityFor(stream_id);
if (!send_order.has_value()) {
return absl::InternalError(
"Stream registered at the top level scheduler, but not at the "
"per-group one");
}
QUICHE_RETURN_IF_ERROR(Unregister(stream_id));
QUICHE_RETURN_IF_ERROR(
Register(stream_id, StreamPriority{new_send_group, *send_order}));
if (is_scheduled) {
QUICHE_RETURN_IF_ERROR(Schedule(stream_id));
}
return absl::OkStatus();
}
std::optional<StreamPriority> PriorityScheduler::GetPriorityFor(
StreamId stream_id) const {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return std::nullopt;
}
const auto& [group_id, group_scheduler] = *it->second;
std::optional<SendOrder> send_order =
group_scheduler.GetPriorityFor(stream_id);
if (!send_order.has_value()) {
return std::nullopt;
}
return StreamPriority{group_id, *send_order};
}
absl::StatusOr<bool> PriorityScheduler::ShouldYield(StreamId stream_id) const {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return absl::NotFoundError("Stream ID not registered");
}
const auto& [group_id, group_scheduler] = *it->second;
absl::StatusOr<bool> per_group_result = active_groups_.ShouldYield(group_id);
QUICHE_RETURN_IF_ERROR(per_group_result.status());
if (*per_group_result) {
return true;
}
return group_scheduler.ShouldYield(stream_id);
}
absl::StatusOr<StreamId> PriorityScheduler::PopFront() {
absl::StatusOr<SendGroupId> group_id = active_groups_.PopFront();
QUICHE_RETURN_IF_ERROR(group_id.status());
auto it = per_group_schedulers_.find(*group_id);
if (it == per_group_schedulers_.end()) {
return absl::InternalError(
"Scheduled a group with no per-group scheduler attached");
}
PerGroupScheduler& scheduler = it->second;
absl::StatusOr<StreamId> result = scheduler.PopFront();
if (!result.ok()) {
return absl::InternalError("Inactive group found in top-level schedule");
}
if (scheduler.HasScheduled()) {
QUICHE_RETURN_IF_ERROR(active_groups_.Schedule(*group_id));
}
return result;
}
absl::Status PriorityScheduler::Schedule(StreamId stream_id) {
auto it = stream_to_group_map_.find(stream_id);
if (it == stream_to_group_map_.end()) {
return absl::NotFoundError("Stream ID not registered");
}
auto& [group_id, group_scheduler] = *it->second;
QUICHE_RETURN_IF_ERROR(active_groups_.Schedule(group_id));
return group_scheduler.Schedule(stream_id);
}
bool PriorityScheduler::IsScheduled(StreamId stream_id) const {
const PerGroupScheduler* scheduler = SchedulerForStream(stream_id);
if (scheduler == nullptr) {
return false;
}
return scheduler->IsScheduled(stream_id);
}
} | #include "quiche/web_transport/web_transport_priority_scheduler.h"
#include <optional>
#include <vector>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
#include "quiche/web_transport/web_transport.h"
namespace webtransport {
namespace {
using ::quiche::test::IsOkAndHolds;
using ::quiche::test::StatusIs;
using ::testing::ElementsAre;
void ScheduleIds(PriorityScheduler& scheduler, absl::Span<const StreamId> ids) {
for (StreamId id : ids) {
QUICHE_EXPECT_OK(scheduler.Schedule(id));
}
}
std::vector<StreamId> PopAll(PriorityScheduler& scheduler) {
std::vector<StreamId> result;
result.reserve(scheduler.NumScheduled());
for (;;) {
absl::StatusOr<StreamId> id = scheduler.PopFront();
if (!id.ok()) {
EXPECT_THAT(id, StatusIs(absl::StatusCode::kNotFound));
break;
}
result.push_back(*id);
}
return result;
}
TEST(WebTransportSchedulerTest, Register) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0}));
QUICHE_EXPECT_OK(scheduler.Register(4, StreamPriority{0, 0}));
EXPECT_THAT(scheduler.Register(4, StreamPriority{0, 0}),
StatusIs(absl::StatusCode::kAlreadyExists));
EXPECT_THAT(scheduler.Register(4, StreamPriority{1, 0}),
StatusIs(absl::StatusCode::kAlreadyExists));
}
TEST(WebTransportSchedulerTest, Unregister) {
PriorityScheduler scheduler;
EXPECT_FALSE(scheduler.HasRegistered());
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
EXPECT_TRUE(scheduler.HasRegistered());
QUICHE_EXPECT_OK(scheduler.Unregister(1));
EXPECT_TRUE(scheduler.HasRegistered());
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
ScheduleIds(scheduler, {0, 1});
QUICHE_EXPECT_OK(scheduler.Unregister(0));
QUICHE_EXPECT_OK(scheduler.Unregister(1));
EXPECT_FALSE(scheduler.HasRegistered());
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
EXPECT_TRUE(scheduler.HasRegistered());
EXPECT_FALSE(scheduler.HasScheduled());
}
TEST(WebTransportSchedulerTest, UpdatePriority) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 10}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 20}));
EXPECT_EQ(scheduler.GetPriorityFor(0), (StreamPriority{0, 10}));
EXPECT_EQ(scheduler.GetPriorityFor(1), (StreamPriority{0, 20}));
QUICHE_EXPECT_OK(scheduler.UpdateSendGroup(0, 1));
QUICHE_EXPECT_OK(scheduler.UpdateSendOrder(1, 40));
EXPECT_EQ(scheduler.GetPriorityFor(0), (StreamPriority{1, 10}));
EXPECT_EQ(scheduler.GetPriorityFor(1), (StreamPriority{0, 40}));
EXPECT_THAT(scheduler.UpdateSendGroup(1000, 1),
StatusIs(absl::StatusCode::kNotFound));
EXPECT_THAT(scheduler.UpdateSendOrder(1000, 1),
StatusIs(absl::StatusCode::kNotFound));
EXPECT_EQ(scheduler.GetPriorityFor(1000), std::nullopt);
}
TEST(WebTransportSchedulerTest, Schedule) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
EXPECT_FALSE(scheduler.IsScheduled(0));
EXPECT_FALSE(scheduler.IsScheduled(1));
EXPECT_FALSE(scheduler.IsScheduled(1000));
QUICHE_EXPECT_OK(scheduler.Schedule(0));
EXPECT_TRUE(scheduler.IsScheduled(0));
EXPECT_FALSE(scheduler.IsScheduled(1));
QUICHE_EXPECT_OK(scheduler.Schedule(1));
EXPECT_TRUE(scheduler.IsScheduled(0));
EXPECT_TRUE(scheduler.IsScheduled(1));
EXPECT_THAT(scheduler.Schedule(0), StatusIs(absl::StatusCode::kOk));
EXPECT_THAT(scheduler.Schedule(2), StatusIs(absl::StatusCode::kNotFound));
}
TEST(WebTransportSchedulerTest, SamePriority) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{0, 0}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_EQ(scheduler.NumScheduled(), 4);
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3));
ScheduleIds(scheduler, {3, 1, 2});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2));
}
TEST(WebTransportSchedulerTest, SingleBucketOrdered) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 1}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 2}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{0, 3}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 2, 1, 0));
ScheduleIds(scheduler, {3, 1, 2, 0});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 2, 1, 0));
}
TEST(WebTransportSchedulerTest, EveryStreamInItsOwnBucket) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{1, 1}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{2, 2}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{3, 3}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3));
ScheduleIds(scheduler, {3, 1, 2});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2));
}
TEST(WebTransportSchedulerTest, TwoBucketsNoSendOrder) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3));
ScheduleIds(scheduler, {0, 2, 1, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3));
ScheduleIds(scheduler, {3, 2, 1, 0});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2, 0));
ScheduleIds(scheduler, {0, 2});
EXPECT_THAT(scheduler.PopFront(), IsOkAndHolds(0));
ScheduleIds(scheduler, {1, 3, 0});
EXPECT_THAT(PopAll(scheduler), ElementsAre(2, 1, 3, 0));
}
TEST(WebTransportSchedulerTest, TwoBucketsWithSendOrder) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 10}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 20}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 30}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 3, 0, 2));
ScheduleIds(scheduler, {3, 2, 1, 0});
EXPECT_THAT(PopAll(scheduler), ElementsAre(3, 1, 2, 0));
}
TEST(WebTransportSchedulerTest, ShouldYield) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{0, 10}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0}));
EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(4), StatusIs(absl::StatusCode::kNotFound));
QUICHE_EXPECT_OK(scheduler.Schedule(0));
EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(true));
PopAll(scheduler);
QUICHE_EXPECT_OK(scheduler.Schedule(2));
EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(false));
EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(true));
PopAll(scheduler);
QUICHE_EXPECT_OK(scheduler.Schedule(3));
EXPECT_THAT(scheduler.ShouldYield(0), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(1), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(2), IsOkAndHolds(true));
EXPECT_THAT(scheduler.ShouldYield(3), IsOkAndHolds(false));
PopAll(scheduler);
}
TEST(WebTransportSchedulerTest, UpdatePriorityWhileScheduled) {
PriorityScheduler scheduler;
QUICHE_EXPECT_OK(scheduler.Register(0, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(1, StreamPriority{0, 0}));
QUICHE_EXPECT_OK(scheduler.Register(2, StreamPriority{1, 0}));
QUICHE_EXPECT_OK(scheduler.Register(3, StreamPriority{1, 0}));
ScheduleIds(scheduler, {0, 1, 2, 3});
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 2, 1, 3));
ScheduleIds(scheduler, {0, 1, 2, 3});
QUICHE_EXPECT_OK(scheduler.UpdateSendOrder(1, 10));
EXPECT_THAT(PopAll(scheduler), ElementsAre(1, 2, 0, 3));
ScheduleIds(scheduler, {0, 1, 2, 3});
QUICHE_EXPECT_OK(scheduler.UpdateSendGroup(1, 1));
EXPECT_THAT(PopAll(scheduler), ElementsAre(0, 1, 2, 3));
}
}
} |
460 | cpp | google/quiche | web_transport_headers | quiche/web_transport/web_transport_headers.cc | quiche/web_transport/web_transport_headers_test.cc | #ifndef QUICHE_WEB_TRANSPORT_WEB_TRANSPORT_HEADERS_H_
#define QUICHE_WEB_TRANSPORT_WEB_TRANSPORT_HEADERS_H_
#include <cstdint>
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/common/platform/api/quiche_export.h"
namespace webtransport {
inline constexpr absl::string_view kSubprotocolRequestHeader =
"WebTransport-Subprotocols-Available";
inline constexpr absl::string_view kSubprotocolResponseHeader =
"WebTransport-Subprotocol";
QUICHE_EXPORT absl::StatusOr<std::vector<std::string>>
ParseSubprotocolRequestHeader(absl::string_view value);
QUICHE_EXPORT absl::StatusOr<std::string> SerializeSubprotocolRequestHeader(
absl::Span<const std::string> subprotocols);
QUICHE_EXPORT absl::StatusOr<std::string> ParseSubprotocolResponseHeader(
absl::string_view value);
QUICHE_EXPORT absl::StatusOr<std::string> SerializeSubprotocolResponseHeader(
absl::string_view subprotocol);
inline constexpr absl::string_view kInitHeader = "WebTransport-Init";
struct QUICHE_EXPORT WebTransportInitHeader {
uint64_t initial_unidi_limit = 0;
uint64_t initial_incoming_bidi_limit = 0;
uint64_t initial_outgoing_bidi_limit = 0;
bool operator==(const WebTransportInitHeader& other) const {
return initial_unidi_limit == other.initial_unidi_limit &&
initial_incoming_bidi_limit == other.initial_incoming_bidi_limit &&
initial_outgoing_bidi_limit == other.initial_outgoing_bidi_limit;
}
};
QUICHE_EXPORT absl::StatusOr<WebTransportInitHeader> ParseInitHeader(
absl::string_view header);
QUICHE_EXPORT absl::StatusOr<std::string> SerializeInitHeader(
const WebTransportInitHeader& header);
}
#endif
#include "quiche/web_transport/web_transport_headers.h"
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/common/quiche_status_utils.h"
#include "quiche/common/structured_headers.h"
namespace webtransport {
namespace {
using ::quiche::structured_headers::Dictionary;
using ::quiche::structured_headers::DictionaryMember;
using ::quiche::structured_headers::Item;
using ::quiche::structured_headers::ItemTypeToString;
using ::quiche::structured_headers::List;
using ::quiche::structured_headers::ParameterizedItem;
using ::quiche::structured_headers::ParameterizedMember;
absl::Status CheckItemType(const ParameterizedItem& item,
Item::ItemType expected_type) {
if (item.item.Type() != expected_type) {
return absl::InvalidArgumentError(absl::StrCat(
"Expected all members to be of type ", ItemTypeToString(expected_type),
", found ", ItemTypeToString(item.item.Type()), " instead"));
}
return absl::OkStatus();
}
absl::Status CheckMemberType(const ParameterizedMember& member,
Item::ItemType expected_type) {
if (member.member_is_inner_list || member.member.size() != 1) {
return absl::InvalidArgumentError(absl::StrCat(
"Expected all members to be of type", ItemTypeToString(expected_type),
", found a nested list instead"));
}
return CheckItemType(member.member[0], expected_type);
}
ABSL_CONST_INIT std::array kInitHeaderFields{
std::make_pair("u", &WebTransportInitHeader::initial_unidi_limit),
std::make_pair("bl", &WebTransportInitHeader::initial_incoming_bidi_limit),
std::make_pair("br", &WebTransportInitHeader::initial_outgoing_bidi_limit),
};
}
absl::StatusOr<std::vector<std::string>> ParseSubprotocolRequestHeader(
absl::string_view value) {
std::optional<List> parsed = quiche::structured_headers::ParseList(value);
if (!parsed.has_value()) {
return absl::InvalidArgumentError(
"Failed to parse the header as an sf-list");
}
std::vector<std::string> result;
result.reserve(parsed->size());
for (ParameterizedMember& member : *parsed) {
QUICHE_RETURN_IF_ERROR(CheckMemberType(member, Item::kTokenType));
result.push_back(std::move(member.member[0].item).TakeString());
}
return result;
}
absl::StatusOr<std::string> SerializeSubprotocolRequestHeader(
absl::Span<const std::string> subprotocols) {
for (const std::string& token : subprotocols) {
if (!quiche::structured_headers::IsValidToken(token)) {
return absl::InvalidArgumentError(absl::StrCat("Invalid token: ", token));
}
}
return absl::StrJoin(subprotocols, ", ");
}
absl::StatusOr<std::string> ParseSubprotocolResponseHeader(
absl::string_view value) {
std::optional<ParameterizedItem> parsed =
quiche::structured_headers::ParseItem(value);
if (!parsed.has_value()) {
return absl::InvalidArgumentError("Failed to parse sf-item");
}
QUICHE_RETURN_IF_ERROR(CheckItemType(*parsed, Item::kTokenType));
return std::move(parsed->item).TakeString();
}
absl::StatusOr<std::string> SerializeSubprotocolResponseHeader(
absl::string_view subprotocol) {
if (!quiche::structured_headers::IsValidToken(subprotocol)) {
return absl::InvalidArgumentError("Invalid token value supplied");
}
return std::string(subprotocol);
}
absl::StatusOr<WebTransportInitHeader> ParseInitHeader(
absl::string_view header) {
std::optional<Dictionary> parsed =
quiche::structured_headers::ParseDictionary(header);
if (!parsed.has_value()) {
return absl::InvalidArgumentError(
"Failed to parse WebTransport-Init header as an sf-dictionary");
}
WebTransportInitHeader output;
for (const auto& [field_name_a, field_value] : *parsed) {
for (const auto& [field_name_b, field_accessor] : kInitHeaderFields) {
if (field_name_a != field_name_b) {
continue;
}
QUICHE_RETURN_IF_ERROR(CheckMemberType(field_value, Item::kIntegerType));
int64_t value = field_value.member[0].item.GetInteger();
if (value < 0) {
return absl::InvalidArgumentError(
absl::StrCat("Received negative value for ", field_name_a));
}
output.*field_accessor = value;
}
}
return output;
}
absl::StatusOr<std::string> SerializeInitHeader(
const WebTransportInitHeader& header) {
std::vector<DictionaryMember> members;
members.reserve(kInitHeaderFields.size());
for (const auto& [field_name, field_accessor] : kInitHeaderFields) {
Item item(static_cast<int64_t>(header.*field_accessor));
members.push_back(std::make_pair(
field_name, ParameterizedMember({ParameterizedItem(item, {})}, false,
{})));
}
std::optional<std::string> result =
quiche::structured_headers::SerializeDictionary(
Dictionary(std::move(members)));
if (!result.has_value()) {
return absl::InternalError("Failed to serialize the dictionary");
}
return *std::move(result);
}
} | #include "quiche/web_transport/web_transport_headers.h"
#include "absl/status/status.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
namespace webtransport {
namespace {
using ::quiche::test::IsOkAndHolds;
using ::quiche::test::StatusIs;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
TEST(WebTransportHeaders, ParseSubprotocolRequestHeader) {
EXPECT_THAT(ParseSubprotocolRequestHeader("test"),
IsOkAndHolds(ElementsAre("test")));
EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01, moqt-draft02"),
IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02")));
EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01; a=b, moqt-draft02"),
IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02")));
EXPECT_THAT(ParseSubprotocolRequestHeader("moqt-draft01, moqt-draft02; a=b"),
IsOkAndHolds(ElementsAre("moqt-draft01", "moqt-draft02")));
EXPECT_THAT(ParseSubprotocolRequestHeader("\"test\""),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found string instead")));
EXPECT_THAT(ParseSubprotocolRequestHeader("42"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found integer instead")));
EXPECT_THAT(ParseSubprotocolRequestHeader("a, (b)"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found a nested list instead")));
EXPECT_THAT(ParseSubprotocolRequestHeader("a, (b c)"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found a nested list instead")));
EXPECT_THAT(ParseSubprotocolRequestHeader("foo, ?1, bar"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found boolean instead")));
EXPECT_THAT(ParseSubprotocolRequestHeader("(a"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("parse the header as an sf-list")));
}
TEST(WebTransportHeaders, SerializeSubprotocolRequestHeader) {
EXPECT_THAT(SerializeSubprotocolRequestHeader({"test"}),
IsOkAndHolds("test"));
EXPECT_THAT(SerializeSubprotocolRequestHeader({"foo", "bar"}),
IsOkAndHolds("foo, bar"));
EXPECT_THAT(SerializeSubprotocolRequestHeader({"moqt-draft01", "a/b/c"}),
IsOkAndHolds("moqt-draft01, a/b/c"));
EXPECT_THAT(
SerializeSubprotocolRequestHeader({"abcd", "0123", "efgh"}),
StatusIs(absl::StatusCode::kInvalidArgument, "Invalid token: 0123"));
}
TEST(WebTransportHeader, ParseSubprotocolResponseHeader) {
EXPECT_THAT(ParseSubprotocolResponseHeader("foo"), IsOkAndHolds("foo"));
EXPECT_THAT(ParseSubprotocolResponseHeader("foo; a=b"), IsOkAndHolds("foo"));
EXPECT_THAT(
ParseSubprotocolResponseHeader("1234"),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("found integer")));
EXPECT_THAT(
ParseSubprotocolResponseHeader("(a"),
StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("parse sf-item")));
}
TEST(WebTransportHeader, SerializeSubprotocolResponseHeader) {
EXPECT_THAT(SerializeSubprotocolResponseHeader("foo"), IsOkAndHolds("foo"));
EXPECT_THAT(SerializeSubprotocolResponseHeader("moqt-draft01"),
IsOkAndHolds("moqt-draft01"));
EXPECT_THAT(SerializeSubprotocolResponseHeader("123abc"),
StatusIs(absl::StatusCode::kInvalidArgument));
}
TEST(WebTransportHeader, ParseInitHeader) {
WebTransportInitHeader expected_header;
expected_header.initial_unidi_limit = 100;
expected_header.initial_incoming_bidi_limit = 200;
expected_header.initial_outgoing_bidi_limit = 400;
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=100"),
IsOkAndHolds(expected_header));
EXPECT_THAT(ParseInitHeader("br=300, bl=200, u=100, br=400"),
IsOkAndHolds(expected_header));
EXPECT_THAT(ParseInitHeader("br=400, bl=200; foo=bar, u=100"),
IsOkAndHolds(expected_header));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=100.0"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found decimal instead")));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=?1"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found boolean instead")));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=(a b)"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found a nested list instead")));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=:abcd:"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("found byte sequence instead")));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=-1"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("negative value")));
EXPECT_THAT(ParseInitHeader("br=400, bl=200, u=18446744073709551615"),
StatusIs(absl::StatusCode::kInvalidArgument,
HasSubstr("Failed to parse")));
}
TEST(WebTransportHeaders, SerializeInitHeader) {
EXPECT_THAT(SerializeInitHeader(WebTransportInitHeader{}),
IsOkAndHolds("u=0, bl=0, br=0"));
WebTransportInitHeader test_header;
test_header.initial_unidi_limit = 100;
test_header.initial_incoming_bidi_limit = 200;
test_header.initial_outgoing_bidi_limit = 400;
EXPECT_THAT(SerializeInitHeader(test_header),
IsOkAndHolds("u=100, bl=200, br=400"));
}
}
} |
461 | cpp | google/quiche | encapsulated_web_transport | quiche/web_transport/encapsulated/encapsulated_web_transport.cc | quiche/web_transport/encapsulated/encapsulated_web_transport_test.cc | #ifndef QUICHE_WEB_TRANSPORT_ENCAPSULATED_ENCAPSULATED_WEB_TRANSPORT_H_
#define QUICHE_WEB_TRANSPORT_ENCAPSULATED_ENCAPSULATED_WEB_TRANSPORT_H_
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/container/node_hash_map.h"
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "quiche/common/capsule.h"
#include "quiche/common/http/http_header_block.h"
#include "quiche/common/platform/api/quiche_export.h"
#include "quiche/common/quiche_buffer_allocator.h"
#include "quiche/common/quiche_callbacks.h"
#include "quiche/common/quiche_circular_deque.h"
#include "quiche/common/quiche_stream.h"
#include "quiche/common/simple_buffer_allocator.h"
#include "quiche/web_transport/web_transport.h"
#include "quiche/web_transport/web_transport_priority_scheduler.h"
namespace webtransport {
constexpr bool IsUnidirectionalId(StreamId id) { return id & 0b10; }
constexpr bool IsBidirectionalId(StreamId id) {
return !IsUnidirectionalId(id);
}
constexpr bool IsIdOpenedBy(StreamId id, Perspective perspective) {
return (id & 0b01) ^ (perspective == Perspective::kClient);
}
using FatalErrorCallback = quiche::SingleUseCallback<void(absl::string_view)>;
class QUICHE_EXPORT EncapsulatedSession
: public webtransport::Session,
public quiche::WriteStreamVisitor,
public quiche::ReadStreamVisitor,
public quiche::CapsuleParser::Visitor {
public:
enum State {
kUninitialized,
kWaitingForHeaders,
kSessionOpen,
kSessionClosing,
kSessionClosed,
};
EncapsulatedSession(Perspective perspective,
FatalErrorCallback fatal_error_callback);
void InitializeClient(std::unique_ptr<SessionVisitor> visitor,
quiche::HttpHeaderBlock& outgoing_headers,
quiche::WriteStream* writer,
quiche::ReadStream* reader);
void InitializeServer(std::unique_ptr<SessionVisitor> visitor,
const quiche::HttpHeaderBlock& incoming_headers,
quiche::HttpHeaderBlock& outgoing_headers,
quiche::WriteStream* writer,
quiche::ReadStream* reader);
void ProcessIncomingServerHeaders(const quiche::HttpHeaderBlock& headers);
void CloseSession(SessionErrorCode error_code,
absl::string_view error_message) override;
Stream* AcceptIncomingBidirectionalStream() override;
Stream* AcceptIncomingUnidirectionalStream() override;
bool CanOpenNextOutgoingBidirectionalStream() override;
bool CanOpenNextOutgoingUnidirectionalStream() override;
Stream* OpenOutgoingBidirectionalStream() override;
Stream* OpenOutgoingUnidirectionalStream() override;
DatagramStatus SendOrQueueDatagram(absl::string_view datagram) override;
uint64_t GetMaxDatagramSize() const override;
void SetDatagramMaxTimeInQueue(absl::Duration max_time_in_queue) override;
Stream* GetStreamById(StreamId id) override;
DatagramStats GetDatagramStats() override;
SessionStats GetSessionStats() override;
void NotifySessionDraining() override;
void SetOnDraining(quiche::SingleUseCallback<void()> callback) override;
void OnCanWrite() override;
void OnCanRead() override;
bool OnCapsule(const quiche::Capsule& capsule) override;
void OnCapsuleParseFailure(absl::string_view error_message) override;
State state() const { return state_; }
void GarbageCollectStreams();
private:
static constexpr size_t kDefaultMaxBufferedStreamData = 16 * 1024;
class InnerStream : public Stream {
public:
InnerStream(EncapsulatedSession* session, StreamId id);
InnerStream(const InnerStream&) = delete;
InnerStream(InnerStream&&) = delete;
InnerStream& operator=(const InnerStream&) = delete;
InnerStream& operator=(InnerStream&&) = delete;
ABSL_MUST_USE_RESULT ReadResult Read(absl::Span<char> output) override;
ABSL_MUST_USE_RESULT ReadResult Read(std::string* output) override;
size_t ReadableBytes() const override;
PeekResult PeekNextReadableRegion() const override;
bool SkipBytes(size_t bytes) override;
absl::Status Writev(absl::Span<const absl::string_view> data,
const quiche::StreamWriteOptions& options) override;
bool CanWrite() const override;
void AbruptlyTerminate(absl::Status error) override;
StreamId GetStreamId() const override { return id_; }
StreamVisitor* visitor() override { return visitor_.get(); }
void SetVisitor(std::unique_ptr<StreamVisitor> visitor) override {
visitor_ = std::move(visitor);
}
void ResetWithUserCode(StreamErrorCode error) override;
void SendStopSending(StreamErrorCode error) override;
void ResetDueToInternalError() override { ResetWithUserCode(0); }
void MaybeResetDueToStreamObjectGone() override { ResetWithUserCode(0); }
void SetPriority(const StreamPriority& priority) override;
void CloseReadSide(std::optional<StreamErrorCode> error);
void CloseWriteSide(std::optional<StreamErrorCode> error);
bool CanBeGarbageCollected() const {
return read_side_closed_ && write_side_closed_;
}
bool HasPendingWrite() const { return !pending_write_.empty(); }
void FlushPendingWrite();
void ProcessCapsule(const quiche::Capsule& capsule);
private:
struct IncomingRead {
absl::string_view data;
std::string storage;
size_t size() const { return data.size(); }
};
[[nodiscard]] size_t WriteInner(absl::Span<const absl::string_view> data,
bool fin);
EncapsulatedSession* session_;
StreamId id_;
std::unique_ptr<StreamVisitor> visitor_;
quiche::QuicheCircularDeque<IncomingRead> incoming_reads_;
std::string pending_write_;
bool read_side_closed_;
bool write_side_closed_;
bool reset_frame_sent_ = false;
bool stop_sending_sent_ = false;
bool fin_received_ = false;
bool fin_consumed_ = false;
bool fin_buffered_ = false;
};
struct BufferedClose {
SessionErrorCode error_code = 0;
std::string error_message;
};
Perspective perspective_;
State state_ = kUninitialized;
std::unique_ptr<SessionVisitor> visitor_ = nullptr;
FatalErrorCallback fatal_error_callback_;
quiche::SingleUseCallback<void()> draining_callback_;
quiche::WriteStream* writer_ = nullptr;
quiche::ReadStream* reader_ = nullptr;
quiche::QuicheBufferAllocator* allocator_ =
quiche::SimpleBufferAllocator::Get();
quiche::CapsuleParser capsule_parser_;
size_t max_stream_data_buffered_ = kDefaultMaxBufferedStreamData;
PriorityScheduler scheduler_;
absl::node_hash_map<StreamId, InnerStream>
streams_;
quiche::QuicheCircularDeque<StreamId> incoming_bidirectional_streams_;
quiche::QuicheCircularDeque<StreamId> incoming_unidirectional_streams_;
std::vector<StreamId> streams_to_garbage_collect_;
StreamId next_outgoing_bidi_stream_;
StreamId next_outgoing_unidi_stream_;
bool session_close_notified_ = false;
bool fin_sent_ = false;
BufferedClose buffered_session_close_;
quiche::QuicheCircularDeque<quiche::QuicheBuffer> control_capsule_queue_;
void OpenSession();
absl::Status SendFin(absl::string_view data);
void OnSessionClosed(SessionErrorCode error_code,
const std::string& error_message);
void OnFatalError(absl::string_view error_message);
void OnWriteError(absl::Status error);
bool IsOutgoing(StreamId id) { return IsIdOpenedBy(id, perspective_); }
bool IsIncoming(StreamId id) { return !IsOutgoing(id); }
template <typename CapsuleType>
void SendControlCapsule(CapsuleType capsule) {
control_capsule_queue_.push_back(quiche::SerializeCapsule(
quiche::Capsule(std::move(capsule)), allocator_));
OnCanWrite();
}
Stream* AcceptIncomingStream(quiche::QuicheCircularDeque<StreamId>& queue);
Stream* OpenOutgoingStream(StreamId& counter);
void ProcessStreamCapsule(const quiche::Capsule& capsule, StreamId stream_id);
};
}
#endif
#include "quiche/web_transport/encapsulated/encapsulated_web_transport.h"
#include <stdbool.h>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/node_hash_map.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "quiche/common/capsule.h"
#include "quiche/common/http/http_header_block.h"
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_buffer_allocator.h"
#include "quiche/common/quiche_callbacks.h"
#include "quiche/common/quiche_circular_deque.h"
#include "quiche/common/quiche_status_utils.h"
#include "quiche/common/quiche_stream.h"
#include "quiche/web_transport/web_transport.h"
namespace webtransport {
namespace {
using ::quiche::Capsule;
using ::quiche::CapsuleType;
using ::quiche::CloseWebTransportSessionCapsule;
constexpr uint64_t kEncapsulatedMaxDatagramSize = 9000;
constexpr StreamPriority kDefaultPriority = StreamPriority{0, 0};
}
EncapsulatedSession::EncapsulatedSession(
Perspective perspective, FatalErrorCallback fatal_error_callback)
: perspective_(perspective),
fatal_error_callback_(std::move(fatal_error_callback)),
capsule_parser_(this),
next_outgoing_bidi_stream_(perspective == Perspective::kClient ? 0 : 1),
next_outgoing_unidi_stream_(perspective == Perspective::kClient ? 2 : 3) {
QUICHE_DCHECK(IsIdOpenedBy(next_outgoing_bidi_stream_, perspective));
QUICHE_DCHECK(IsIdOpenedBy(next_outgoing_unidi_stream_, perspective));
}
void EncapsulatedSession::InitializeClient(
std::unique_ptr<SessionVisitor> visitor,
quiche::HttpHeaderBlock& , quiche::WriteStream* writer,
quiche::ReadStream* reader) {
if (state_ != kUninitialized) {
OnFatalError("Called InitializeClient() in an invalid state");
return;
}
if (perspective_ != Perspective::kClient) {
OnFatalError("Called InitializeClient() on a server session");
return;
}
visitor_ = std::move(visitor);
writer_ = writer;
reader_ = reader;
state_ = kWaitingForHeaders;
}
void EncapsulatedSession::InitializeServer(
std::unique_ptr<SessionVisitor> visitor,
const quiche::HttpHeaderBlock& ,
quiche::HttpHeaderBlock& , quiche::WriteStream* writer,
quiche::ReadStream* reader) {
if (state_ != kUninitialized) {
OnFatalError("Called InitializeServer() in an invalid state");
return;
}
if (perspective_ != Perspective::kServer) {
OnFatalError("Called InitializeServer() on a client session");
return;
}
visitor_ = std::move(visitor);
writer_ = writer;
reader_ = reader;
OpenSession();
}
void EncapsulatedSession::ProcessIncomingServerHeaders(
const quiche::HttpHeaderBlock& ) {
if (state_ != kWaitingForHeaders) {
OnFatalError("Called ProcessIncomingServerHeaders() in an invalid state");
return;
}
OpenSession();
}
void EncapsulatedSession::CloseSession(SessionErrorCode error_code,
absl::string_view error_message) {
switch (state_) {
case kUninitialized:
case kWaitingForHeaders:
OnFatalError(absl::StrCat(
"Attempted to close a session before it opened with error 0x",
absl::Hex(error_code), ": ", error_message));
return;
case kSessionClosing:
case kSessionClosed:
OnFatalError(absl::StrCat(
"Attempted to close a session that is already closed with error 0x",
absl::Hex(error_code), ": ", error_message));
return;
case kSessionOpen:
break;
}
state_ = kSessionClosing;
buffered_session_close_ =
BufferedClose{error_code, std::string(error_message)};
OnCanWrite();
}
Stream* EncapsulatedSession::AcceptIncomingStream(
quiche::QuicheCircularDeque<StreamId>& queue) {
while (!queue.empty()) {
StreamId id = queue.front();
queue.pop_front();
Stream* stream = GetStreamById(id);
if (stream == nullptr) {
continue;
}
return stream;
}
return nullptr;
}
Stream* EncapsulatedSession::AcceptIncomingBidirectionalStream() {
return AcceptIncomingStream(incoming_bidirectional_streams_);
}
Stream* EncapsulatedSession::AcceptIncomingUnidirectionalStream() {
return AcceptIncomingStream(incoming_unidirectional_streams_);
}
bool EncapsulatedSession::CanOpenNextOutgoingBidirectionalStream() {
return true;
}
bool EncapsulatedSession::CanOpenNextOutgoingUnidirectionalStream() {
return true;
}
Stream* EncapsulatedSession::OpenOutgoingStream(StreamId& counter) {
StreamId stream_id = counter;
counter += 4;
auto [it, inserted] = streams_.emplace(
std::piecewise_construct, std::forward_as_tuple(stream_id),
std::forward_as_tuple(this, stream_id));
QUICHE_DCHECK(inserted);
return &it->second;
}
Stream* EncapsulatedSession::OpenOutgoingBidirectionalStream() {
if (!CanOpenNextOutgoingBidirectionalStream()) {
return nullptr;
}
return OpenOutgoingStream(next_outgoing_bidi_stream_);
}
Stream* EncapsulatedSession::OpenOutgoingUnidirectionalStream() {
if (!CanOpenNextOutgoingUnidirectionalStream()) {
return nullptr;
}
return OpenOutgoingStream(next_outgoing_unidi_stream_);
}
Stream* EncapsulatedSession::GetStreamById(StreamId id) {
auto it = streams_.find(id);
if (it == streams_.end()) {
return nullptr;
}
return &it->second;
}
DatagramStats EncapsulatedSession::GetDatagramStats() {
DatagramStats stats;
stats.expired_outgoing = 0;
stats.lost_outgoing = 0;
return stats;
}
SessionStats EncapsulatedSession::GetSessionStats() {
return SessionStats();
}
void EncapsulatedSession::NotifySessionDraining() {
SendControlCapsule(quiche::DrainWebTransportSessionCapsule());
OnCanWrite();
}
void EncapsulatedSession::SetOnDraining(
quiche::SingleUseCallback<void()> callback) {
draining_callback_ = std::move(callback);
}
DatagramStatus EncapsulatedSession::SendOrQueueDatagram(
absl::string_view datagram) {
if (datagram.size() > GetMaxDatagramSize()) {
return DatagramStatus{
DatagramStatusCode::kTooBig,
absl::StrCat("Datagram is ", datagram.size(),
" bytes long, while the specified maximum size is ",
GetMaxDatagramSize())};
}
bool write_blocked;
switch (state_) {
case kUninitialized:
write_blocked = true;
break;
case kWaitingForHeaders:
case kSessionOpen:
write_blocked = !writer_->CanWrite();
break;
case kSessionClosing:
case kSessionClosed:
return DatagramStatus{DatagramStatusCode::kInternalError,
"Writing into an already closed session"};
}
if (write_blocked) {
control_capsule_queue_.push_back(
quiche::SerializeCapsule(Capsule::Datagram(datagram), allocator_));
return DatagramStatus{DatagramStatusCode::kSuccess, ""};
}
quiche::QuicheBuffer buffer =
quiche::SerializeDatagramCapsuleHeader(datagram.size(), allocator_);
std::array spans = {buffer.AsStringView(), datagram};
absl::Status write_status =
writer_->Writev(absl::MakeConstSpan(spans), quiche::StreamWriteOptions());
if (!write_status.ok()) {
OnWriteError(write_status);
return DatagramStatus{
DatagramStatusCode::kInternalError,
absl::StrCat("Write error for datagram: ", write_status.ToString())};
}
return DatagramStatus{DatagramStatusCode::kSuccess, ""};
}
uint64_t EncapsulatedSession::GetMaxDatagramSize() const {
return kEncapsulatedMaxDatagramSize;
}
void EncapsulatedSession::SetDatagramMaxTimeInQueue(
absl::Duration ) {
}
void EncapsulatedSession::OnCanWrite() {
if (state_ == kUninitialized || !writer_) {
OnFatalError("Trying to write before the session is initialized");
return;
}
if (state_ == kSessionClosed) {
OnFatalError("Trying to write before the session is closed");
return;
}
if (state_ == kSessionClosing) {
if (writer_->CanWrite()) {
CloseWebTransportSessionCapsule capsule{
buffered_session_close_.error_code,
buffered_session_close_.error_message};
quiche::QuicheBuffer buffer =
quiche::SerializeCapsule(Capsule(std::move(capsule)), allocator_);
absl::Status write_status = SendFin(buffer.AsStringView());
if (!write_status.ok()) {
OnWriteError(quiche::AppendToStatus(write_status,
" while writing WT_CLOSE_SESSION"));
return;
}
OnSessionClosed(buffered_session_close_.error_code,
buffered_session_close_.error_message);
}
return;
}
while (writer_->CanWrite() && !control_capsule_queue_.empty()) {
absl::Status write_status = quiche::WriteIntoStream(
*writer_, control_capsule_queue_.front().AsStringView());
if (!write_status.ok()) {
OnWriteError(write_status);
return;
}
control_capsule_queue_.pop_front();
}
while (writer_->CanWrite()) {
absl::StatusOr<StreamId> next_id = scheduler_.PopFront();
if (!next_id.ok()) {
QUICHE_DCHECK_EQ(next_id.status().code(), absl::StatusCode::kNotFound);
return;
}
auto it = streams_.find(*next_id);
if (it == streams_.end()) {
QUICHE_BUG(WT_H2_NextStreamNotInTheMap);
OnFatalError("Next scheduled stream is not in the map");
return;
}
QUICHE_DCHECK(it->second.HasPendingWrite());
it->second.FlushPendingWrite();
}
}
void EncapsulatedSession::OnCanRead() {
if (state_ == kSessionClosed || state_ == kSessionClosing) {
return;
}
bool has_fin = quiche::ProcessAllReadableRegions(
*reader_, [&](absl::string_view fragment) {
capsule_parser_.IngestCapsuleFragment(fragment);
});
if (has_fin) {
capsule_parser_.ErrorIfThereIsRemainingBufferedData();
OnSessionClosed(0, "");
}
if (state_ == kSessionOpen) {
GarbageCollectStreams();
}
}
bool EncapsulatedSession::OnCapsule(const quiche::Capsule& capsule) {
switch (capsule.capsule_type()) {
case CapsuleType::DATAGRAM:
visitor_->OnDatagramReceived(
capsule.datagram_capsule().http_datagram_payload);
break;
case CapsuleType::DRAIN_WEBTRANSPORT_SESSION:
if (draining_callback_) {
std::move(draining_callback_)();
}
break;
case CapsuleType::CLOSE_WEBTRANSPORT_SESSION:
OnSessionClosed(
capsule.close_web_transport_session_capsule().error_code,
std::string(
capsule.close_web_transport_session_capsule().error_message));
break;
case CapsuleType::WT_STREAM:
case CapsuleType::WT_STREAM_WITH_FIN:
ProcessStreamCapsule(capsule,
capsule.web_transport_stream_data().stream_id);
break;
case CapsuleType::WT_RESET_STREAM:
ProcessStreamCapsule(capsule,
capsule.web_transport_reset_stream().stream_id);
break;
case CapsuleType::WT_STOP_SENDING:
ProcessStreamCapsule(capsule,
capsule.web_transport_stop_sending().stream_id);
break;
default:
break;
}
return state_ != kSessionClosed;
}
void EncapsulatedSession::OnCapsuleParseFailure(
absl::string_view error_message) {
if (state_ == kSessionClosed) {
return;
}
OnFatalError(absl::StrCat("Stream parse error: ", error_message));
}
void EncapsulatedSession::ProcessStreamCapsule(const quiche::Capsule& capsule,
StreamId stream_id) {
bool new_stream_created = false;
auto it = streams_.find(stream_id);
if (it == streams_.end()) {
if (IsOutgoing(stream_id)) {
return;
}
it = streams_.emplace_hint(it, std::piecewise_construct,
std::forward_as_tuple(stream_id),
std::forward_as_tuple(this, stream_id));
new_stream_created = true;
}
InnerStream& stream = it->second;
stream.ProcessCapsule(capsule);
if (new_stream_created) {
if (IsBidirectionalId(stream_id)) {
incoming_bidirectional_streams_.push_back(stream_id);
visitor_->OnIncomingBidirectionalStreamAvailable();
} else {
incoming_unidirectional_streams_.push_back(stream_id);
visitor_->OnIncomingUnidirectionalStreamAvailable();
}
}
}
void EncapsulatedSession::InnerStream::ProcessCapsule(
const quiche::Capsule& capsule) {
switch (capsule.capsule_type()) {
case CapsuleType::WT_STREAM:
case CapsuleType::WT_STREAM_WITH_FIN: {
if (fin_received_) {
session_->OnFatalError(
"Received stream data for a stream that has already received a "
"FIN");
return;
}
if (read_side_closed_) {
return;
}
fin_received_ = capsule.capsule_type() == CapsuleType::WT_STREAM_WITH_FIN;
const quiche::WebTransportStreamDataCapsule& data =
capsule.web_transport_stream_data();
if (!data.data.empty()) {
incoming_reads_.push_back(IncomingRead{data.data, std::string()});
}
if (visitor_ != nullptr) {
visitor_->OnCanRead();
}
for (IncomingRead& read : incoming_reads_) {
QUICHE_DCHECK(!read.data.empty());
if (read.storage.empty()) {
read.storage = std::string(read.data);
read.data = read.storage;
}
}
return;
}
case CapsuleType::WT_RESET_STREAM:
CloseReadSide(capsule.web_transport_reset_stream().error_code);
return;
case CapsuleType::WT_STOP_SENDING:
CloseWriteSide(capsule.web_transport_stop_sending().error_code);
return;
default:
QUICHE_BUG(WT_H2_ProcessStreamCapsule_Unknown)
<< "Unexpected capsule dispatched to InnerStream: " << capsule;
session_->OnFatalError(
"Internal error: Unexpected capsule dispatched to InnerStream");
return;
}
}
void EncapsulatedSession::OpenSession() {
state_ = kSessionOpen;
visitor_->OnSessionReady();
OnCanWrite();
OnCanRead();
}
absl::Status EncapsulatedSession::SendFin(absl::string_view data) {
QUICHE_DCHECK(!fin_sent_);
fin_sent_ = true;
quiche::StreamWriteOptions options;
options.set_send_fin(true);
return quiche::WriteIntoStream(*writer_, data, options);
}
void EncapsulatedSession::OnSessionClosed(SessionErrorCode error_code,
const std::string& error_message) {
if (!fin_sent_) {
absl::Status status = SendFin("");
if (!status.ok()) {
OnWriteError(status);
return;
}
}
if (session_close_notified_) {
QUICHE_DCHECK_EQ(state_, kSessionClosed);
return;
}
state_ = kSessionClosed;
session_close_notified_ = true;
if (visitor_ != nullptr) {
visitor_->OnSessionClosed(error_code, error_message);
}
}
void EncapsulatedSession::OnFatalError(absl::string_view error_message) {
QUICHE_DLOG(ERROR) << "Fatal error in encapsulated WebTransport: "
<< error_message;
state_ = kSessionClosed;
if (fatal_error_callback_) {
std::move(fatal_error_callback_)(error_message);
fatal_error_callback_ = nullptr;
}
}
void EncapsulatedSession::OnWriteError(absl::Status error) {
OnFatalError(absl::StrCat(
error, " while trying to write encapsulated WebTransport data"));
}
EncapsulatedSession::InnerStream::InnerStream(EncapsulatedSession* session,
StreamId id)
: session_(session),
id_(id),
read_side_closed_(IsUnidirectionalId(id) &&
IsIdOpenedBy(id, session->perspective_)),
write_side_closed_(IsUnidirectionalId(id) &&
!IsIdOpenedBy(id, session->perspective_)) {
if (!write_side_closed_) {
absl::Status status = session_->scheduler_.Register(id_, kDefaultPriority);
if (!status.ok()) {
QUICHE_BUG(WT_H2_FailedToRegisterNewStream) << status;
session_->OnFatalError(
"Failed to register new stream with the scheduler");
return;
}
}
}
quiche::ReadStream::ReadResult EncapsulatedSession::InnerStream::Read(
absl::Span<char> output) {
const size_t total_size = output.size();
for (const IncomingRead& read : incoming_reads_) {
size_t size_to_read = std::min(read.size(), output.size());
if (size_to_read == 0) {
break;
}
memcpy(output.data(), read.data.data(), size_to_read);
output = output.subspan(size_to_read);
}
bool fin_consumed = SkipBytes(total_size);
return ReadResult{total_size, fin_consumed};
}
quiche::ReadStream::ReadResult EncapsulatedSession::InnerStream::Read(
std::string* output) {
const size_t total_size = ReadableBytes();
const size_t initial_offset = output->size();
output->resize(initial_offset + total_size);
return Read(absl::Span<char>(&((*output)[initial_offset]), total_size));
}
size_t EncapsulatedSession::InnerStream::ReadableBytes() const {
size_t total_size = 0;
for (const IncomingRead& read : incoming_reads_) {
total_size += read.size();
}
return total_size;
}
quiche::ReadStream::PeekResult
EncapsulatedSession::InnerStream::PeekNextReadableRegion() const {
if (incoming_reads_.empty()) {
return PeekResult{absl::string_view(), fin_received_, fin_received_};
}
return PeekResult{incoming_reads_.front().data,
fin_received_ && incoming_reads_.size() == 1,
fin_received_};
}
bool EncapsulatedSession::InnerStream::SkipBytes(size_t bytes) {
size_t remaining = bytes;
while (remaining > 0) {
if (incoming_reads_.empty()) {
QUICHE_BUG(WT_H2_SkipBytes_toomuch)
<< "Requested to skip " << remaining
<< " bytes that are not present in the read buffer.";
return false;
}
IncomingRead& current = incoming_reads_.front();
if (remaining < current.size()) {
current.data = current.data.substr(remaining);
return false;
}
remaining -= current.size();
incoming_reads_.pop_front();
}
if (incoming_reads_.empty() && fin_received_) {
fin_consumed_ = true;
CloseReadSide(std::nullopt);
return true;
}
return false;
}
absl::Status EncapsulatedSession::InnerStream::Writev(
const absl::Span<const absl::string_view> data,
const quiche::StreamWriteOptions& options) {
if (write_side_closed_) {
return absl::FailedPreconditionError(
"Trying to write into an already-closed stream");
}
if (fin_buffered_) {
return absl::FailedPreconditionError("FIN already buffered");
}
if (!CanWrite()) {
return absl::FailedPreconditionError(
"Trying to write into a stream when CanWrite() = false");
}
const absl::StatusOr<bool> should_yield =
session_->scheduler_.ShouldYield(id_);
if (!should_yield.ok()) {
QUICHE_BUG(WT_H2_Writev_NotRegistered) << should_yield.status();
session_->OnFatalError("Stream not registered with the scheduler");
return absl::InternalError("Stream not registered with the scheduler");
}
const bool write_blocked = !session_->writer_->CanWrite() || *should_yield ||
!pending_write_.empty();
if (write_blocked) {
fin_buffered_ = options.send_fin();
for (absl::string_view chunk : data) {
absl::StrAppend(&pending_write_, chunk);
}
absl::Status status = session_->scheduler_.Schedule(id_);
if (!status.ok()) {
QUICHE_BUG(WT_H2_Writev_CantSchedule) << status;
session_->OnFatalError("Could not schedule a write-blocked stream");
return absl::InternalError("Could not schedule a write-blocked stream");
}
return absl:: | #include "quiche/web_transport/encapsulated/encapsulated_web_transport.h"
#include <array>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quiche/common/capsule.h"
#include "quiche/common/http/http_header_block.h"
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/common/quiche_buffer_allocator.h"
#include "quiche/common/quiche_stream.h"
#include "quiche/common/simple_buffer_allocator.h"
#include "quiche/common/test_tools/mock_streams.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
#include "quiche/web_transport/test_tools/mock_web_transport.h"
#include "quiche/web_transport/web_transport.h"
namespace webtransport::test {
namespace {
using ::quiche::Capsule;
using ::quiche::CapsuleType;
using ::quiche::test::StatusIs;
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::StrEq;
class EncapsulatedWebTransportTest : public quiche::test::QuicheTest,
public quiche::CapsuleParser::Visitor {
public:
EncapsulatedWebTransportTest() : parser_(this), reader_(&read_buffer_) {
ON_CALL(fatal_error_callback_, Call(_))
.WillByDefault([](absl::string_view error) {
ADD_FAILURE() << "Fatal session error: " << error;
});
ON_CALL(writer_, Writev(_, _))
.WillByDefault([&](absl::Span<const absl::string_view> data,
const quiche::StreamWriteOptions& options) {
for (absl::string_view fragment : data) {
parser_.IngestCapsuleFragment(fragment);
}
writer_.ProcessOptions(options);
return absl::OkStatus();
});
}
std::unique_ptr<EncapsulatedSession> CreateTransport(
Perspective perspective) {
auto transport = std::make_unique<EncapsulatedSession>(
perspective, fatal_error_callback_.AsStdFunction());
session_ = transport.get();
return transport;
}
std::unique_ptr<SessionVisitor> CreateAndStoreVisitor() {
auto visitor = std::make_unique<testing::StrictMock<MockSessionVisitor>>();
visitor_ = visitor.get();
return visitor;
}
MOCK_METHOD(bool, OnCapsule, (const Capsule&), (override));
void OnCapsuleParseFailure(absl::string_view error_message) override {
ADD_FAILURE() << "Written an invalid capsule: " << error_message;
}
void ProcessIncomingCapsule(const Capsule& capsule) {
quiche::QuicheBuffer buffer =
quiche::SerializeCapsule(capsule, quiche::SimpleBufferAllocator::Get());
read_buffer_.append(buffer.data(), buffer.size());
session_->OnCanRead();
}
template <typename CapsuleType>
void ProcessIncomingCapsule(const CapsuleType& capsule) {
quiche::QuicheBuffer buffer = quiche::SerializeCapsule(
quiche::Capsule(capsule), quiche::SimpleBufferAllocator::Get());
read_buffer_.append(buffer.data(), buffer.size());
session_->OnCanRead();
}
void DefaultHandshakeForClient(EncapsulatedSession& session) {
quiche::HttpHeaderBlock outgoing_headers, incoming_headers;
session.InitializeClient(CreateAndStoreVisitor(), outgoing_headers,
&writer_, &reader_);
EXPECT_CALL(*visitor_, OnSessionReady());
session.ProcessIncomingServerHeaders(incoming_headers);
}
protected:
quiche::CapsuleParser parser_;
quiche::test::MockWriteStream writer_;
std::string read_buffer_;
quiche::test::ReadStreamFromString reader_;
MockSessionVisitor* visitor_ = nullptr;
EncapsulatedSession* session_ = nullptr;
testing::MockFunction<void(absl::string_view)> fatal_error_callback_;
};
TEST_F(EncapsulatedWebTransportTest, IsOpenedBy) {
EXPECT_EQ(IsIdOpenedBy(0x00, Perspective::kClient), true);
EXPECT_EQ(IsIdOpenedBy(0x01, Perspective::kClient), false);
EXPECT_EQ(IsIdOpenedBy(0x02, Perspective::kClient), true);
EXPECT_EQ(IsIdOpenedBy(0x03, Perspective::kClient), false);
EXPECT_EQ(IsIdOpenedBy(0x00, Perspective::kServer), false);
EXPECT_EQ(IsIdOpenedBy(0x01, Perspective::kServer), true);
EXPECT_EQ(IsIdOpenedBy(0x02, Perspective::kServer), false);
EXPECT_EQ(IsIdOpenedBy(0x03, Perspective::kServer), true);
}
TEST_F(EncapsulatedWebTransportTest, SetupClientSession) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
quiche::HttpHeaderBlock outgoing_headers, incoming_headers;
EXPECT_EQ(session->state(), EncapsulatedSession::kUninitialized);
session->InitializeClient(CreateAndStoreVisitor(), outgoing_headers, &writer_,
&reader_);
EXPECT_EQ(session->state(), EncapsulatedSession::kWaitingForHeaders);
EXPECT_CALL(*visitor_, OnSessionReady());
session->ProcessIncomingServerHeaders(incoming_headers);
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen);
}
TEST_F(EncapsulatedWebTransportTest, SetupServerSession) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kServer);
quiche::HttpHeaderBlock outgoing_headers, incoming_headers;
EXPECT_EQ(session->state(), EncapsulatedSession::kUninitialized);
std::unique_ptr<SessionVisitor> visitor = CreateAndStoreVisitor();
EXPECT_CALL(*visitor_, OnSessionReady());
session->InitializeServer(std::move(visitor), outgoing_headers,
incoming_headers, &writer_, &reader_);
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen);
}
TEST_F(EncapsulatedWebTransportTest, CloseSession) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::CLOSE_WEBTRANSPORT_SESSION);
EXPECT_EQ(capsule.close_web_transport_session_capsule().error_code, 0x1234);
EXPECT_EQ(capsule.close_web_transport_session_capsule().error_message,
"test close");
return true;
});
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen);
EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test close")));
session->CloseSession(0x1234, "test close");
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosed);
EXPECT_TRUE(writer_.fin_written());
EXPECT_CALL(fatal_error_callback_, Call(_))
.WillOnce([](absl::string_view error) {
EXPECT_THAT(error, HasSubstr("close a session that is already closed"));
});
session->CloseSession(0x1234, "test close");
}
TEST_F(EncapsulatedWebTransportTest, CloseSessionWriteBlocked) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false));
EXPECT_CALL(*this, OnCapsule(_)).Times(0);
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionOpen);
session->CloseSession(0x1234, "test close");
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosing);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::CLOSE_WEBTRANSPORT_SESSION);
EXPECT_EQ(capsule.close_web_transport_session_capsule().error_code, 0x1234);
EXPECT_EQ(capsule.close_web_transport_session_capsule().error_message,
"test close");
return true;
});
EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(true));
EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test close")));
session->OnCanWrite();
EXPECT_EQ(session->state(), EncapsulatedSession::kSessionClosed);
EXPECT_TRUE(writer_.fin_written());
}
TEST_F(EncapsulatedWebTransportTest, ReceiveFin) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnSessionClosed(0, IsEmpty()));
reader_.set_fin();
session->OnCanRead();
EXPECT_TRUE(writer_.fin_written());
}
TEST_F(EncapsulatedWebTransportTest, ReceiveCloseSession) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnSessionClosed(0x1234, StrEq("test")));
ProcessIncomingCapsule(Capsule::CloseWebTransportSession(0x1234, "test"));
EXPECT_TRUE(writer_.fin_written());
reader_.set_fin();
session->OnCanRead();
}
TEST_F(EncapsulatedWebTransportTest, ReceiveMalformedData) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(fatal_error_callback_, Call(HasSubstr("too much capsule data")))
.WillOnce([] {});
read_buffer_ = std::string(2 * 1024 * 1024, '\xff');
session->OnCanRead();
}
TEST_F(EncapsulatedWebTransportTest, SendDatagrams) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), quiche::CapsuleType::DATAGRAM);
EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test");
return true;
});
DatagramStatus status = session->SendOrQueueDatagram("test");
EXPECT_EQ(status.code, DatagramStatusCode::kSuccess);
}
TEST_F(EncapsulatedWebTransportTest, SendDatagramsEarly) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
quiche::HttpHeaderBlock outgoing_headers;
session->InitializeClient(CreateAndStoreVisitor(), outgoing_headers, &writer_,
&reader_);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), quiche::CapsuleType::DATAGRAM);
EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test");
return true;
});
ASSERT_EQ(session->state(), EncapsulatedSession::kWaitingForHeaders);
session->SendOrQueueDatagram("test");
}
TEST_F(EncapsulatedWebTransportTest, SendDatagramsBeforeInitialization) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
quiche::HttpHeaderBlock outgoing_headers;
EXPECT_CALL(*this, OnCapsule(_)).Times(0);
ASSERT_EQ(session->state(), EncapsulatedSession::kUninitialized);
session->SendOrQueueDatagram("test");
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::DATAGRAM);
EXPECT_EQ(capsule.datagram_capsule().http_datagram_payload, "test");
return true;
});
DefaultHandshakeForClient(*session);
}
TEST_F(EncapsulatedWebTransportTest, SendDatagramsTooBig) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*this, OnCapsule(_)).Times(0);
std::string long_string(16 * 1024, 'a');
DatagramStatus status = session->SendOrQueueDatagram(long_string);
EXPECT_EQ(status.code, DatagramStatusCode::kTooBig);
}
TEST_F(EncapsulatedWebTransportTest, ReceiveDatagrams) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnDatagramReceived(_))
.WillOnce([](absl::string_view data) { EXPECT_EQ(data, "test"); });
ProcessIncomingCapsule(Capsule::Datagram("test"));
}
TEST_F(EncapsulatedWebTransportTest, SendDraining) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::DRAIN_WEBTRANSPORT_SESSION);
return true;
});
session->NotifySessionDraining();
}
TEST_F(EncapsulatedWebTransportTest, ReceiveDraining) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
testing::MockFunction<void()> callback;
session->SetOnDraining(callback.AsStdFunction());
EXPECT_CALL(callback, Call());
ProcessIncomingCapsule(Capsule(quiche::DrainWebTransportSessionCapsule()));
}
TEST_F(EncapsulatedWebTransportTest, WriteErrorDatagram) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(writer_, Writev(_, _))
.WillOnce(Return(absl::InternalError("Test write error")));
EXPECT_CALL(fatal_error_callback_, Call(_))
.WillOnce([](absl::string_view error) {
EXPECT_THAT(error, HasSubstr("Test write error"));
});
DatagramStatus status = session->SendOrQueueDatagram("test");
EXPECT_EQ(status.code, DatagramStatusCode::kInternalError);
}
TEST_F(EncapsulatedWebTransportTest, WriteErrorControlCapsule) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(writer_, Writev(_, _))
.WillOnce(Return(absl::InternalError("Test write error")));
EXPECT_CALL(fatal_error_callback_, Call(_))
.WillOnce([](absl::string_view error) {
EXPECT_THAT(error, HasSubstr("Test write error"));
});
session->NotifySessionDraining();
}
TEST_F(EncapsulatedWebTransportTest, SimpleRead) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
bool stream_received = false;
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable())
.WillOnce([&] { stream_received = true; });
std::string data = "test";
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, data, false});
data[0] = 'q';
EXPECT_TRUE(stream_received);
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_EQ(stream->GetStreamId(), 1u);
EXPECT_EQ(stream->visitor(), nullptr);
EXPECT_EQ(stream->ReadableBytes(), 4u);
quiche::ReadStream::PeekResult peek = stream->PeekNextReadableRegion();
EXPECT_EQ(peek.peeked_data, "test");
EXPECT_FALSE(peek.fin_next);
EXPECT_FALSE(peek.all_data_received);
std::string buffer;
quiche::ReadStream::ReadResult read = stream->Read(&buffer);
EXPECT_EQ(read.bytes_read, 4);
EXPECT_FALSE(read.fin);
EXPECT_EQ(buffer, "test");
EXPECT_EQ(stream->ReadableBytes(), 0u);
}
class MockStreamVisitorWithDestructor : public MockStreamVisitor {
public:
~MockStreamVisitorWithDestructor() { OnDelete(); }
MOCK_METHOD(void, OnDelete, (), ());
};
MockStreamVisitorWithDestructor* SetupVisitor(Stream& stream) {
auto visitor = std::make_unique<MockStreamVisitorWithDestructor>();
MockStreamVisitorWithDestructor* result = visitor.get();
stream.SetVisitor(std::move(visitor));
return result;
}
TEST_F(EncapsulatedWebTransportTest, ImmediateRead) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(
quiche::WebTransportStreamDataCapsule{1, "abcd", false});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_EQ(stream->ReadableBytes(), 4u);
MockStreamVisitor* visitor = SetupVisitor(*stream);
EXPECT_CALL(*visitor, OnCanRead()).WillOnce([&] {
std::string output;
(void)stream->Read(&output);
EXPECT_EQ(output, "abcdef");
});
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "ef", false});
}
TEST_F(EncapsulatedWebTransportTest, FinPeek) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(
quiche::WebTransportStreamDataCapsule{1, "abcd", false});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_EQ(stream->ReadableBytes(), 4u);
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "ef", true});
quiche::ReadStream::PeekResult peek = stream->PeekNextReadableRegion();
EXPECT_EQ(peek.peeked_data, "abcd");
EXPECT_FALSE(peek.fin_next);
EXPECT_TRUE(peek.all_data_received);
EXPECT_FALSE(stream->SkipBytes(2));
peek = stream->PeekNextReadableRegion();
EXPECT_FALSE(peek.fin_next);
EXPECT_TRUE(peek.all_data_received);
EXPECT_FALSE(stream->SkipBytes(2));
peek = stream->PeekNextReadableRegion();
EXPECT_EQ(peek.peeked_data, "ef");
EXPECT_TRUE(peek.fin_next);
EXPECT_TRUE(peek.all_data_received);
EXPECT_TRUE(stream->SkipBytes(2));
}
TEST_F(EncapsulatedWebTransportTest, FinRead) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(
quiche::WebTransportStreamDataCapsule{1, "abcdef", true});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_EQ(stream->ReadableBytes(), 6u);
std::array<char, 3> buffer;
quiche::ReadStream::ReadResult read = stream->Read(absl::MakeSpan(buffer));
EXPECT_THAT(buffer, ElementsAre('a', 'b', 'c'));
EXPECT_EQ(read.bytes_read, 3);
EXPECT_FALSE(read.fin);
read = stream->Read(absl::MakeSpan(buffer));
EXPECT_THAT(buffer, ElementsAre('d', 'e', 'f'));
EXPECT_EQ(read.bytes_read, 3);
EXPECT_TRUE(read.fin);
}
TEST_F(EncapsulatedWebTransportTest, LargeRead) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{
1, std::string(64 * 1024, 'a'), true});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_EQ(stream->ReadableBytes(), 65536u);
for (int i = 0; i < 64; i++) {
std::array<char, 1024> buffer;
quiche::ReadStream::ReadResult read = stream->Read(absl::MakeSpan(buffer));
EXPECT_EQ(read.bytes_read, 1024);
EXPECT_EQ(read.fin, i == 63);
}
}
TEST_F(EncapsulatedWebTransportTest, DoubleFinReceived) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "abc", true});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(fatal_error_callback_, Call(_))
.WillOnce([](absl::string_view error) {
EXPECT_THAT(error, HasSubstr("has already received a FIN"));
});
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "def", true});
}
TEST_F(EncapsulatedWebTransportTest, CanWriteUnidiBidi) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "abc", true});
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "abc", true});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_TRUE(stream->CanWrite());
stream = session->AcceptIncomingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_FALSE(stream->CanWrite());
stream = session->OpenOutgoingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_TRUE(stream->CanWrite());
stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_TRUE(stream->CanWrite());
}
TEST_F(EncapsulatedWebTransportTest, ReadOnlyGarbageCollection) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "abc", true});
Stream* stream = session->AcceptIncomingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_TRUE(stream->SkipBytes(3));
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
bool deleted = false;
EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; });
session->GarbageCollectStreams();
EXPECT_TRUE(deleted);
}
TEST_F(EncapsulatedWebTransportTest, WriteOnlyGarbageCollection) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
bool deleted = false;
EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; });
EXPECT_CALL(*this, OnCapsule(_)).WillOnce(Return(true));
quiche::StreamWriteOptions options;
options.set_send_fin(true);
EXPECT_THAT(stream->Writev(absl::Span<const absl::string_view>(), options),
StatusIs(absl::StatusCode::kOk));
session->GarbageCollectStreams();
EXPECT_TRUE(deleted);
}
TEST_F(EncapsulatedWebTransportTest, SimpleWrite) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingBidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{1, "", true});
Stream* stream = session->AcceptIncomingBidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM);
EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 1u);
EXPECT_EQ(capsule.web_transport_stream_data().fin, false);
EXPECT_EQ(capsule.web_transport_stream_data().data, "test");
return true;
});
absl::Status status = quiche::WriteIntoStream(*stream, "test");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
}
TEST_F(EncapsulatedWebTransportTest, WriteWithFin) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM_WITH_FIN);
EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u);
EXPECT_EQ(capsule.web_transport_stream_data().fin, true);
EXPECT_EQ(capsule.web_transport_stream_data().data, "test");
return true;
});
quiche::StreamWriteOptions options;
options.set_send_fin(true);
EXPECT_TRUE(stream->CanWrite());
absl::Status status = quiche::WriteIntoStream(*stream, "test", options);
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_FALSE(stream->CanWrite());
}
TEST_F(EncapsulatedWebTransportTest, FinOnlyWrite) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM_WITH_FIN);
EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u);
EXPECT_EQ(capsule.web_transport_stream_data().fin, true);
EXPECT_EQ(capsule.web_transport_stream_data().data, "");
return true;
});
quiche::StreamWriteOptions options;
options.set_send_fin(true);
EXPECT_TRUE(stream->CanWrite());
absl::Status status =
stream->Writev(absl::Span<const absl::string_view>(), options);
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_FALSE(stream->CanWrite());
}
TEST_F(EncapsulatedWebTransportTest, BufferedWriteThenUnbuffer) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false));
absl::Status status = quiche::WriteIntoStream(*stream, "abc");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_TRUE(stream->CanWrite());
EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true));
status = quiche::WriteIntoStream(*stream, "def");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM);
EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u);
EXPECT_EQ(capsule.web_transport_stream_data().data, "abcdef");
return true;
});
session_->OnCanWrite();
}
TEST_F(EncapsulatedWebTransportTest, BufferedWriteThenFlush) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
EXPECT_CALL(writer_, CanWrite()).Times(2).WillRepeatedly(Return(false));
absl::Status status = quiche::WriteIntoStream(*stream, "abc");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
status = quiche::WriteIntoStream(*stream, "def");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true));
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM);
EXPECT_EQ(capsule.web_transport_stream_data().stream_id, 2u);
EXPECT_EQ(capsule.web_transport_stream_data().data, "abcdef");
return true;
});
session_->OnCanWrite();
}
TEST_F(EncapsulatedWebTransportTest, BufferedStreamBlocksAnother) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream1 = session->OpenOutgoingUnidirectionalStream();
Stream* stream2 = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream1 != nullptr);
ASSERT_TRUE(stream2 != nullptr);
EXPECT_CALL(*this, OnCapsule(_)).Times(0);
EXPECT_CALL(writer_, CanWrite()).WillOnce(Return(false));
absl::Status status = quiche::WriteIntoStream(*stream1, "abc");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
EXPECT_CALL(writer_, CanWrite()).WillRepeatedly(Return(true));
status = quiche::WriteIntoStream(*stream2, "abc");
EXPECT_THAT(status, StatusIs(absl::StatusCode::kOk));
std::vector<StreamId> writes;
EXPECT_CALL(*this, OnCapsule(_)).WillRepeatedly([&](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STREAM);
writes.push_back(capsule.web_transport_stream_data().stream_id);
return true;
});
session_->OnCanWrite();
EXPECT_THAT(writes, ElementsAre(2, 6));
}
TEST_F(EncapsulatedWebTransportTest, SendReset) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([&](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_RESET_STREAM);
EXPECT_EQ(capsule.web_transport_reset_stream().stream_id, 2u);
EXPECT_EQ(capsule.web_transport_reset_stream().error_code, 1234u);
return true;
});
stream->ResetWithUserCode(1234u);
bool deleted = false;
EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; });
session->GarbageCollectStreams();
EXPECT_TRUE(deleted);
}
TEST_F(EncapsulatedWebTransportTest, ReceiveReset) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "", true});
Stream* stream = session->AcceptIncomingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
EXPECT_CALL(*visitor, OnResetStreamReceived(1234u));
EXPECT_TRUE(session->GetStreamById(3) != nullptr);
ProcessIncomingCapsule(quiche::WebTransportResetStreamCapsule{3u, 1234u});
EXPECT_TRUE(session->GetStreamById(3) == nullptr);
}
TEST_F(EncapsulatedWebTransportTest, SendStopSending) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
EXPECT_CALL(*visitor_, OnIncomingUnidirectionalStreamAvailable());
ProcessIncomingCapsule(quiche::WebTransportStreamDataCapsule{3, "", true});
Stream* stream = session->AcceptIncomingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
EXPECT_CALL(*this, OnCapsule(_)).WillOnce([&](const Capsule& capsule) {
EXPECT_EQ(capsule.capsule_type(), CapsuleType::WT_STOP_SENDING);
EXPECT_EQ(capsule.web_transport_stop_sending().stream_id, 3u);
EXPECT_EQ(capsule.web_transport_stop_sending().error_code, 1234u);
return true;
});
stream->SendStopSending(1234u);
bool deleted = false;
EXPECT_CALL(*visitor, OnDelete()).WillOnce([&] { deleted = true; });
session->GarbageCollectStreams();
EXPECT_TRUE(deleted);
}
TEST_F(EncapsulatedWebTransportTest, ReceiveStopSending) {
std::unique_ptr<EncapsulatedSession> session =
CreateTransport(Perspective::kClient);
DefaultHandshakeForClient(*session);
Stream* stream = session->OpenOutgoingUnidirectionalStream();
ASSERT_TRUE(stream != nullptr);
MockStreamVisitorWithDestructor* visitor = SetupVisitor(*stream);
EXPECT_CALL(*visitor, OnStopSendingReceived(1234u));
EXPECT_TRUE(session->GetStreamById(2) != nullptr);
ProcessIncomingCapsule(quiche::WebTransportStopSendingCapsule{2u, 1234u});
EXPECT_TRUE(session->GetStreamById(2) == nullptr);
}
}
} |
462 | cpp | google/leveldb | memenv | helpers/memenv/memenv.cc | helpers/memenv/memenv_test.cc | #ifndef STORAGE_LEVELDB_HELPERS_MEMENV_MEMENV_H_
#define STORAGE_LEVELDB_HELPERS_MEMENV_MEMENV_H_
#include "leveldb/export.h"
namespace leveldb {
class Env;
LEVELDB_EXPORT Env* NewMemEnv(Env* base_env);
}
#endif
#include "helpers/memenv/memenv.h"
#include <cstring>
#include <limits>
#include <map>
#include <string>
#include <vector>
#include "leveldb/env.h"
#include "leveldb/status.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/mutexlock.h"
namespace leveldb {
namespace {
class FileState {
public:
FileState() : refs_(0), size_(0) {}
FileState(const FileState&) = delete;
FileState& operator=(const FileState&) = delete;
void Ref() {
MutexLock lock(&refs_mutex_);
++refs_;
}
void Unref() {
bool do_delete = false;
{
MutexLock lock(&refs_mutex_);
--refs_;
assert(refs_ >= 0);
if (refs_ <= 0) {
do_delete = true;
}
}
if (do_delete) {
delete this;
}
}
uint64_t Size() const {
MutexLock lock(&blocks_mutex_);
return size_;
}
void Truncate() {
MutexLock lock(&blocks_mutex_);
for (char*& block : blocks_) {
delete[] block;
}
blocks_.clear();
size_ = 0;
}
Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const {
MutexLock lock(&blocks_mutex_);
if (offset > size_) {
return Status::IOError("Offset greater than file size.");
}
const uint64_t available = size_ - offset;
if (n > available) {
n = static_cast<size_t>(available);
}
if (n == 0) {
*result = Slice();
return Status::OK();
}
assert(offset / kBlockSize <= std::numeric_limits<size_t>::max());
size_t block = static_cast<size_t>(offset / kBlockSize);
size_t block_offset = offset % kBlockSize;
size_t bytes_to_copy = n;
char* dst = scratch;
while (bytes_to_copy > 0) {
size_t avail = kBlockSize - block_offset;
if (avail > bytes_to_copy) {
avail = bytes_to_copy;
}
std::memcpy(dst, blocks_[block] + block_offset, avail);
bytes_to_copy -= avail;
dst += avail;
block++;
block_offset = 0;
}
*result = Slice(scratch, n);
return Status::OK();
}
Status Append(const Slice& data) {
const char* src = data.data();
size_t src_len = data.size();
MutexLock lock(&blocks_mutex_);
while (src_len > 0) {
size_t avail;
size_t offset = size_ % kBlockSize;
if (offset != 0) {
avail = kBlockSize - offset;
} else {
blocks_.push_back(new char[kBlockSize]);
avail = kBlockSize;
}
if (avail > src_len) {
avail = src_len;
}
std::memcpy(blocks_.back() + offset, src, avail);
src_len -= avail;
src += avail;
size_ += avail;
}
return Status::OK();
}
private:
enum { kBlockSize = 8 * 1024 };
~FileState() { Truncate(); }
port::Mutex refs_mutex_;
int refs_ GUARDED_BY(refs_mutex_);
mutable port::Mutex blocks_mutex_;
std::vector<char*> blocks_ GUARDED_BY(blocks_mutex_);
uint64_t size_ GUARDED_BY(blocks_mutex_);
};
class SequentialFileImpl : public SequentialFile {
public:
explicit SequentialFileImpl(FileState* file) : file_(file), pos_(0) {
file_->Ref();
}
~SequentialFileImpl() override { file_->Unref(); }
Status Read(size_t n, Slice* result, char* scratch) override {
Status s = file_->Read(pos_, n, result, scratch);
if (s.ok()) {
pos_ += result->size();
}
return s;
}
Status Skip(uint64_t n) override {
if (pos_ > file_->Size()) {
return Status::IOError("pos_ > file_->Size()");
}
const uint64_t available = file_->Size() - pos_;
if (n > available) {
n = available;
}
pos_ += n;
return Status::OK();
}
private:
FileState* file_;
uint64_t pos_;
};
class RandomAccessFileImpl : public RandomAccessFile {
public:
explicit RandomAccessFileImpl(FileState* file) : file_(file) { file_->Ref(); }
~RandomAccessFileImpl() override { file_->Unref(); }
Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const override {
return file_->Read(offset, n, result, scratch);
}
private:
FileState* file_;
};
class WritableFileImpl : public WritableFile {
public:
WritableFileImpl(FileState* file) : file_(file) { file_->Ref(); }
~WritableFileImpl() override { file_->Unref(); }
Status Append(const Slice& data) override { return file_->Append(data); }
Status Close() override { return Status::OK(); }
Status Flush() override { return Status::OK(); }
Status Sync() override { return Status::OK(); }
private:
FileState* file_;
};
class NoOpLogger : public Logger {
public:
void Logv(const char* format, std::va_list ap) override {}
};
class InMemoryEnv : public EnvWrapper {
public:
explicit InMemoryEnv(Env* base_env) : EnvWrapper(base_env) {}
~InMemoryEnv() override {
for (const auto& kvp : file_map_) {
kvp.second->Unref();
}
}
Status NewSequentialFile(const std::string& fname,
SequentialFile** result) override {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
*result = nullptr;
return Status::IOError(fname, "File not found");
}
*result = new SequentialFileImpl(file_map_[fname]);
return Status::OK();
}
Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) override {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
*result = nullptr;
return Status::IOError(fname, "File not found");
}
*result = new RandomAccessFileImpl(file_map_[fname]);
return Status::OK();
}
Status NewWritableFile(const std::string& fname,
WritableFile** result) override {
MutexLock lock(&mutex_);
FileSystem::iterator it = file_map_.find(fname);
FileState* file;
if (it == file_map_.end()) {
file = new FileState();
file->Ref();
file_map_[fname] = file;
} else {
file = it->second;
file->Truncate();
}
*result = new WritableFileImpl(file);
return Status::OK();
}
Status NewAppendableFile(const std::string& fname,
WritableFile** result) override {
MutexLock lock(&mutex_);
FileState** sptr = &file_map_[fname];
FileState* file = *sptr;
if (file == nullptr) {
file = new FileState();
file->Ref();
}
*result = new WritableFileImpl(file);
return Status::OK();
}
bool FileExists(const std::string& fname) override {
MutexLock lock(&mutex_);
return file_map_.find(fname) != file_map_.end();
}
Status GetChildren(const std::string& dir,
std::vector<std::string>* result) override {
MutexLock lock(&mutex_);
result->clear();
for (const auto& kvp : file_map_) {
const std::string& filename = kvp.first;
if (filename.size() >= dir.size() + 1 && filename[dir.size()] == '/' &&
Slice(filename).starts_with(Slice(dir))) {
result->push_back(filename.substr(dir.size() + 1));
}
}
return Status::OK();
}
void RemoveFileInternal(const std::string& fname)
EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
if (file_map_.find(fname) == file_map_.end()) {
return;
}
file_map_[fname]->Unref();
file_map_.erase(fname);
}
Status RemoveFile(const std::string& fname) override {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
return Status::IOError(fname, "File not found");
}
RemoveFileInternal(fname);
return Status::OK();
}
Status CreateDir(const std::string& dirname) override { return Status::OK(); }
Status RemoveDir(const std::string& dirname) override { return Status::OK(); }
Status GetFileSize(const std::string& fname, uint64_t* file_size) override {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
return Status::IOError(fname, "File not found");
}
*file_size = file_map_[fname]->Size();
return Status::OK();
}
Status RenameFile(const std::string& src,
const std::string& target) override {
MutexLock lock(&mutex_);
if (file_map_.find(src) == file_map_.end()) {
return Status::IOError(src, "File not found");
}
RemoveFileInternal(target);
file_map_[target] = file_map_[src];
file_map_.erase(src);
return Status::OK();
}
Status LockFile(const std::string& fname, FileLock** lock) override {
*lock = new FileLock;
return Status::OK();
}
Status UnlockFile(FileLock* lock) override {
delete lock;
return Status::OK();
}
Status GetTestDirectory(std::string* path) override {
*path = "/test";
return Status::OK();
}
Status NewLogger(const std::string& fname, Logger** result) override {
*result = new NoOpLogger;
return Status::OK();
}
private:
typedef std::map<std::string, FileState*> FileSystem;
port::Mutex mutex_;
FileSystem file_map_ GUARDED_BY(mutex_);
};
}
Env* NewMemEnv(Env* base_env) { return new InMemoryEnv(base_env); }
} | #include "helpers/memenv/memenv.h"
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "db/db_impl.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "util/testutil.h"
namespace leveldb {
class MemEnvTest : public testing::Test {
public:
MemEnvTest() : env_(NewMemEnv(Env::Default())) {}
~MemEnvTest() { delete env_; }
Env* env_;
};
TEST_F(MemEnvTest, Basics) {
uint64_t file_size;
WritableFile* writable_file;
std::vector<std::string> children;
ASSERT_LEVELDB_OK(env_->CreateDir("/dir"));
ASSERT_TRUE(!env_->FileExists("/dir/non_existent"));
ASSERT_TRUE(!env_->GetFileSize("/dir/non_existent", &file_size).ok());
ASSERT_LEVELDB_OK(env_->GetChildren("/dir", &children));
ASSERT_EQ(0, children.size());
ASSERT_LEVELDB_OK(env_->NewWritableFile("/dir/f", &writable_file));
ASSERT_LEVELDB_OK(env_->GetFileSize("/dir/f", &file_size));
ASSERT_EQ(0, file_size);
delete writable_file;
ASSERT_TRUE(env_->FileExists("/dir/f"));
ASSERT_LEVELDB_OK(env_->GetFileSize("/dir/f", &file_size));
ASSERT_EQ(0, file_size);
ASSERT_LEVELDB_OK(env_->GetChildren("/dir", &children));
ASSERT_EQ(1, children.size());
ASSERT_EQ("f", children[0]);
ASSERT_LEVELDB_OK(env_->NewWritableFile("/dir/f", &writable_file));
ASSERT_LEVELDB_OK(writable_file->Append("abc"));
delete writable_file;
ASSERT_LEVELDB_OK(env_->NewAppendableFile("/dir/f", &writable_file));
ASSERT_LEVELDB_OK(env_->GetFileSize("/dir/f", &file_size));
ASSERT_EQ(3, file_size);
ASSERT_LEVELDB_OK(writable_file->Append("hello"));
delete writable_file;
ASSERT_LEVELDB_OK(env_->GetFileSize("/dir/f", &file_size));
ASSERT_EQ(8, file_size);
ASSERT_TRUE(!env_->RenameFile("/dir/non_existent", "/dir/g").ok());
ASSERT_LEVELDB_OK(env_->RenameFile("/dir/f", "/dir/g"));
ASSERT_TRUE(!env_->FileExists("/dir/f"));
ASSERT_TRUE(env_->FileExists("/dir/g"));
ASSERT_LEVELDB_OK(env_->GetFileSize("/dir/g", &file_size));
ASSERT_EQ(8, file_size);
SequentialFile* seq_file;
RandomAccessFile* rand_file;
ASSERT_TRUE(!env_->NewSequentialFile("/dir/non_existent", &seq_file).ok());
ASSERT_TRUE(!seq_file);
ASSERT_TRUE(!env_->NewRandomAccessFile("/dir/non_existent", &rand_file).ok());
ASSERT_TRUE(!rand_file);
ASSERT_TRUE(!env_->RemoveFile("/dir/non_existent").ok());
ASSERT_LEVELDB_OK(env_->RemoveFile("/dir/g"));
ASSERT_TRUE(!env_->FileExists("/dir/g"));
ASSERT_LEVELDB_OK(env_->GetChildren("/dir", &children));
ASSERT_EQ(0, children.size());
ASSERT_LEVELDB_OK(env_->RemoveDir("/dir"));
}
TEST_F(MemEnvTest, ReadWrite) {
WritableFile* writable_file;
SequentialFile* seq_file;
RandomAccessFile* rand_file;
Slice result;
char scratch[100];
ASSERT_LEVELDB_OK(env_->CreateDir("/dir"));
ASSERT_LEVELDB_OK(env_->NewWritableFile("/dir/f", &writable_file));
ASSERT_LEVELDB_OK(writable_file->Append("hello "));
ASSERT_LEVELDB_OK(writable_file->Append("world"));
delete writable_file;
ASSERT_LEVELDB_OK(env_->NewSequentialFile("/dir/f", &seq_file));
ASSERT_LEVELDB_OK(seq_file->Read(5, &result, scratch));
ASSERT_EQ(0, result.compare("hello"));
ASSERT_LEVELDB_OK(seq_file->Skip(1));
ASSERT_LEVELDB_OK(seq_file->Read(1000, &result, scratch));
ASSERT_EQ(0, result.compare("world"));
ASSERT_LEVELDB_OK(
seq_file->Read(1000, &result, scratch));
ASSERT_EQ(0, result.size());
ASSERT_LEVELDB_OK(seq_file->Skip(100));
ASSERT_LEVELDB_OK(seq_file->Read(1000, &result, scratch));
ASSERT_EQ(0, result.size());
delete seq_file;
ASSERT_LEVELDB_OK(env_->NewRandomAccessFile("/dir/f", &rand_file));
ASSERT_LEVELDB_OK(rand_file->Read(6, 5, &result, scratch));
ASSERT_EQ(0, result.compare("world"));
ASSERT_LEVELDB_OK(rand_file->Read(0, 5, &result, scratch));
ASSERT_EQ(0, result.compare("hello"));
ASSERT_LEVELDB_OK(rand_file->Read(10, 100, &result, scratch));
ASSERT_EQ(0, result.compare("d"));
ASSERT_TRUE(!rand_file->Read(1000, 5, &result, scratch).ok());
delete rand_file;
}
TEST_F(MemEnvTest, Locks) {
FileLock* lock;
ASSERT_LEVELDB_OK(env_->LockFile("some file", &lock));
ASSERT_LEVELDB_OK(env_->UnlockFile(lock));
}
TEST_F(MemEnvTest, Misc) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
ASSERT_TRUE(!test_dir.empty());
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile("/a/b", &writable_file));
ASSERT_LEVELDB_OK(writable_file->Sync());
ASSERT_LEVELDB_OK(writable_file->Flush());
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
}
TEST_F(MemEnvTest, LargeWrite) {
const size_t kWriteSize = 300 * 1024;
char* scratch = new char[kWriteSize * 2];
std::string write_data;
for (size_t i = 0; i < kWriteSize; ++i) {
write_data.append(1, static_cast<char>(i));
}
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile("/dir/f", &writable_file));
ASSERT_LEVELDB_OK(writable_file->Append("foo"));
ASSERT_LEVELDB_OK(writable_file->Append(write_data));
delete writable_file;
SequentialFile* seq_file;
Slice result;
ASSERT_LEVELDB_OK(env_->NewSequentialFile("/dir/f", &seq_file));
ASSERT_LEVELDB_OK(seq_file->Read(3, &result, scratch));
ASSERT_EQ(0, result.compare("foo"));
size_t read = 0;
std::string read_data;
while (read < kWriteSize) {
ASSERT_LEVELDB_OK(seq_file->Read(kWriteSize - read, &result, scratch));
read_data.append(result.data(), result.size());
read += result.size();
}
ASSERT_TRUE(write_data == read_data);
delete seq_file;
delete[] scratch;
}
TEST_F(MemEnvTest, OverwriteOpenFile) {
const char kWrite1Data[] = "Write #1 data";
const size_t kFileDataLen = sizeof(kWrite1Data) - 1;
const std::string kTestFileName = testing::TempDir() + "leveldb-TestFile.dat";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, kWrite1Data, kTestFileName));
RandomAccessFile* rand_file;
ASSERT_LEVELDB_OK(env_->NewRandomAccessFile(kTestFileName, &rand_file));
const char kWrite2Data[] = "Write #2 data";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, kWrite2Data, kTestFileName));
Slice result;
char scratch[kFileDataLen];
ASSERT_LEVELDB_OK(rand_file->Read(0, kFileDataLen, &result, scratch));
ASSERT_EQ(0, result.compare(kWrite2Data));
delete rand_file;
}
TEST_F(MemEnvTest, DBTest) {
Options options;
options.create_if_missing = true;
options.env = env_;
DB* db;
const Slice keys[] = {Slice("aaa"), Slice("bbb"), Slice("ccc")};
const Slice vals[] = {Slice("foo"), Slice("bar"), Slice("baz")};
ASSERT_LEVELDB_OK(DB::Open(options, "/dir/db", &db));
for (size_t i = 0; i < 3; ++i) {
ASSERT_LEVELDB_OK(db->Put(WriteOptions(), keys[i], vals[i]));
}
for (size_t i = 0; i < 3; ++i) {
std::string res;
ASSERT_LEVELDB_OK(db->Get(ReadOptions(), keys[i], &res));
ASSERT_TRUE(res == vals[i]);
}
Iterator* iterator = db->NewIterator(ReadOptions());
iterator->SeekToFirst();
for (size_t i = 0; i < 3; ++i) {
ASSERT_TRUE(iterator->Valid());
ASSERT_TRUE(keys[i] == iterator->key());
ASSERT_TRUE(vals[i] == iterator->value());
iterator->Next();
}
ASSERT_TRUE(!iterator->Valid());
delete iterator;
DBImpl* dbi = reinterpret_cast<DBImpl*>(db);
ASSERT_LEVELDB_OK(dbi->TEST_CompactMemTable());
for (size_t i = 0; i < 3; ++i) {
std::string res;
ASSERT_LEVELDB_OK(db->Get(ReadOptions(), keys[i], &res));
ASSERT_TRUE(res == vals[i]);
}
delete db;
}
} |
463 | cpp | google/leveldb | table | table/table.cc | table/table_test.cc | #ifndef STORAGE_LEVELDB_INCLUDE_TABLE_H_
#define STORAGE_LEVELDB_INCLUDE_TABLE_H_
#include <cstdint>
#include "leveldb/export.h"
#include "leveldb/iterator.h"
namespace leveldb {
class Block;
class BlockHandle;
class Footer;
struct Options;
class RandomAccessFile;
struct ReadOptions;
class TableCache;
class LEVELDB_EXPORT Table {
public:
static Status Open(const Options& options, RandomAccessFile* file,
uint64_t file_size, Table** table);
Table(const Table&) = delete;
Table& operator=(const Table&) = delete;
~Table();
Iterator* NewIterator(const ReadOptions&) const;
uint64_t ApproximateOffsetOf(const Slice& key) const;
private:
friend class TableCache;
struct Rep;
static Iterator* BlockReader(void*, const ReadOptions&, const Slice&);
explicit Table(Rep* rep) : rep_(rep) {}
Status InternalGet(const ReadOptions&, const Slice& key, void* arg,
void (*handle_result)(void* arg, const Slice& k,
const Slice& v));
void ReadMeta(const Footer& footer);
void ReadFilter(const Slice& filter_handle_value);
Rep* const rep_;
};
}
#endif
#include "leveldb/table.h"
#include "leveldb/cache.h"
#include "leveldb/comparator.h"
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/options.h"
#include "table/block.h"
#include "table/filter_block.h"
#include "table/format.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
namespace leveldb {
struct Table::Rep {
~Rep() {
delete filter;
delete[] filter_data;
delete index_block;
}
Options options;
Status status;
RandomAccessFile* file;
uint64_t cache_id;
FilterBlockReader* filter;
const char* filter_data;
BlockHandle metaindex_handle;
Block* index_block;
};
Status Table::Open(const Options& options, RandomAccessFile* file,
uint64_t size, Table** table) {
*table = nullptr;
if (size < Footer::kEncodedLength) {
return Status::Corruption("file is too short to be an sstable");
}
char footer_space[Footer::kEncodedLength];
Slice footer_input;
Status s = file->Read(size - Footer::kEncodedLength, Footer::kEncodedLength,
&footer_input, footer_space);
if (!s.ok()) return s;
Footer footer;
s = footer.DecodeFrom(&footer_input);
if (!s.ok()) return s;
BlockContents index_block_contents;
ReadOptions opt;
if (options.paranoid_checks) {
opt.verify_checksums = true;
}
s = ReadBlock(file, opt, footer.index_handle(), &index_block_contents);
if (s.ok()) {
Block* index_block = new Block(index_block_contents);
Rep* rep = new Table::Rep;
rep->options = options;
rep->file = file;
rep->metaindex_handle = footer.metaindex_handle();
rep->index_block = index_block;
rep->cache_id = (options.block_cache ? options.block_cache->NewId() : 0);
rep->filter_data = nullptr;
rep->filter = nullptr;
*table = new Table(rep);
(*table)->ReadMeta(footer);
}
return s;
}
void Table::ReadMeta(const Footer& footer) {
if (rep_->options.filter_policy == nullptr) {
return;
}
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents contents;
if (!ReadBlock(rep_->file, opt, footer.metaindex_handle(), &contents).ok()) {
return;
}
Block* meta = new Block(contents);
Iterator* iter = meta->NewIterator(BytewiseComparator());
std::string key = "filter.";
key.append(rep_->options.filter_policy->Name());
iter->Seek(key);
if (iter->Valid() && iter->key() == Slice(key)) {
ReadFilter(iter->value());
}
delete iter;
delete meta;
}
void Table::ReadFilter(const Slice& filter_handle_value) {
Slice v = filter_handle_value;
BlockHandle filter_handle;
if (!filter_handle.DecodeFrom(&v).ok()) {
return;
}
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents block;
if (!ReadBlock(rep_->file, opt, filter_handle, &block).ok()) {
return;
}
if (block.heap_allocated) {
rep_->filter_data = block.data.data();
}
rep_->filter = new FilterBlockReader(rep_->options.filter_policy, block.data);
}
Table::~Table() { delete rep_; }
static void DeleteBlock(void* arg, void* ignored) {
delete reinterpret_cast<Block*>(arg);
}
static void DeleteCachedBlock(const Slice& key, void* value) {
Block* block = reinterpret_cast<Block*>(value);
delete block;
}
static void ReleaseBlock(void* arg, void* h) {
Cache* cache = reinterpret_cast<Cache*>(arg);
Cache::Handle* handle = reinterpret_cast<Cache::Handle*>(h);
cache->Release(handle);
}
Iterator* Table::BlockReader(void* arg, const ReadOptions& options,
const Slice& index_value) {
Table* table = reinterpret_cast<Table*>(arg);
Cache* block_cache = table->rep_->options.block_cache;
Block* block = nullptr;
Cache::Handle* cache_handle = nullptr;
BlockHandle handle;
Slice input = index_value;
Status s = handle.DecodeFrom(&input);
if (s.ok()) {
BlockContents contents;
if (block_cache != nullptr) {
char cache_key_buffer[16];
EncodeFixed64(cache_key_buffer, table->rep_->cache_id);
EncodeFixed64(cache_key_buffer + 8, handle.offset());
Slice key(cache_key_buffer, sizeof(cache_key_buffer));
cache_handle = block_cache->Lookup(key);
if (cache_handle != nullptr) {
block = reinterpret_cast<Block*>(block_cache->Value(cache_handle));
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
if (contents.cachable && options.fill_cache) {
cache_handle = block_cache->Insert(key, block, block->size(),
&DeleteCachedBlock);
}
}
}
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
}
}
}
Iterator* iter;
if (block != nullptr) {
iter = block->NewIterator(table->rep_->options.comparator);
if (cache_handle == nullptr) {
iter->RegisterCleanup(&DeleteBlock, block, nullptr);
} else {
iter->RegisterCleanup(&ReleaseBlock, block_cache, cache_handle);
}
} else {
iter = NewErrorIterator(s);
}
return iter;
}
Iterator* Table::NewIterator(const ReadOptions& options) const {
return NewTwoLevelIterator(
rep_->index_block->NewIterator(rep_->options.comparator),
&Table::BlockReader, const_cast<Table*>(this), options);
}
Status Table::InternalGet(const ReadOptions& options, const Slice& k, void* arg,
void (*handle_result)(void*, const Slice&,
const Slice&)) {
Status s;
Iterator* iiter = rep_->index_block->NewIterator(rep_->options.comparator);
iiter->Seek(k);
if (iiter->Valid()) {
Slice handle_value = iiter->value();
FilterBlockReader* filter = rep_->filter;
BlockHandle handle;
if (filter != nullptr && handle.DecodeFrom(&handle_value).ok() &&
!filter->KeyMayMatch(handle.offset(), k)) {
} else {
Iterator* block_iter = BlockReader(this, options, iiter->value());
block_iter->Seek(k);
if (block_iter->Valid()) {
(*handle_result)(arg, block_iter->key(), block_iter->value());
}
s = block_iter->status();
delete block_iter;
}
}
if (s.ok()) {
s = iiter->status();
}
delete iiter;
return s;
}
uint64_t Table::ApproximateOffsetOf(const Slice& key) const {
Iterator* index_iter =
rep_->index_block->NewIterator(rep_->options.comparator);
index_iter->Seek(key);
uint64_t result;
if (index_iter->Valid()) {
BlockHandle handle;
Slice input = index_iter->value();
Status s = handle.DecodeFrom(&input);
if (s.ok()) {
result = handle.offset();
} else {
result = rep_->metaindex_handle.offset();
}
} else {
result = rep_->metaindex_handle.offset();
}
delete index_iter;
return result;
}
} | #include "leveldb/table.h"
#include <map>
#include <string>
#include "gtest/gtest.h"
#include "db/dbformat.h"
#include "db/memtable.h"
#include "db/write_batch_internal.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "leveldb/iterator.h"
#include "leveldb/options.h"
#include "leveldb/table_builder.h"
#include "table/block.h"
#include "table/block_builder.h"
#include "table/format.h"
#include "util/random.h"
#include "util/testutil.h"
namespace leveldb {
static std::string Reverse(const Slice& key) {
std::string str(key.ToString());
std::string rev("");
for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend();
++rit) {
rev.push_back(*rit);
}
return rev;
}
namespace {
class ReverseKeyComparator : public Comparator {
public:
const char* Name() const override {
return "leveldb.ReverseBytewiseComparator";
}
int Compare(const Slice& a, const Slice& b) const override {
return BytewiseComparator()->Compare(Reverse(a), Reverse(b));
}
void FindShortestSeparator(std::string* start,
const Slice& limit) const override {
std::string s = Reverse(*start);
std::string l = Reverse(limit);
BytewiseComparator()->FindShortestSeparator(&s, l);
*start = Reverse(s);
}
void FindShortSuccessor(std::string* key) const override {
std::string s = Reverse(*key);
BytewiseComparator()->FindShortSuccessor(&s);
*key = Reverse(s);
}
};
}
static ReverseKeyComparator reverse_key_comparator;
static void Increment(const Comparator* cmp, std::string* key) {
if (cmp == BytewiseComparator()) {
key->push_back('\0');
} else {
assert(cmp == &reverse_key_comparator);
std::string rev = Reverse(*key);
rev.push_back('\0');
*key = Reverse(rev);
}
}
namespace {
struct STLLessThan {
const Comparator* cmp;
STLLessThan() : cmp(BytewiseComparator()) {}
STLLessThan(const Comparator* c) : cmp(c) {}
bool operator()(const std::string& a, const std::string& b) const {
return cmp->Compare(Slice(a), Slice(b)) < 0;
}
};
}
class StringSink : public WritableFile {
public:
~StringSink() override = default;
const std::string& contents() const { return contents_; }
Status Close() override { return Status::OK(); }
Status Flush() override { return Status::OK(); }
Status Sync() override { return Status::OK(); }
Status Append(const Slice& data) override {
contents_.append(data.data(), data.size());
return Status::OK();
}
private:
std::string contents_;
};
class StringSource : public RandomAccessFile {
public:
StringSource(const Slice& contents)
: contents_(contents.data(), contents.size()) {}
~StringSource() override = default;
uint64_t Size() const { return contents_.size(); }
Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const override {
if (offset >= contents_.size()) {
return Status::InvalidArgument("invalid Read offset");
}
if (offset + n > contents_.size()) {
n = contents_.size() - offset;
}
std::memcpy(scratch, &contents_[offset], n);
*result = Slice(scratch, n);
return Status::OK();
}
private:
std::string contents_;
};
typedef std::map<std::string, std::string, STLLessThan> KVMap;
class Constructor {
public:
explicit Constructor(const Comparator* cmp) : data_(STLLessThan(cmp)) {}
virtual ~Constructor() = default;
void Add(const std::string& key, const Slice& value) {
data_[key] = value.ToString();
}
void Finish(const Options& options, std::vector<std::string>* keys,
KVMap* kvmap) {
*kvmap = data_;
keys->clear();
for (const auto& kvp : data_) {
keys->push_back(kvp.first);
}
data_.clear();
Status s = FinishImpl(options, *kvmap);
ASSERT_TRUE(s.ok()) << s.ToString();
}
virtual Status FinishImpl(const Options& options, const KVMap& data) = 0;
virtual Iterator* NewIterator() const = 0;
const KVMap& data() const { return data_; }
virtual DB* db() const { return nullptr; }
private:
KVMap data_;
};
class BlockConstructor : public Constructor {
public:
explicit BlockConstructor(const Comparator* cmp)
: Constructor(cmp), comparator_(cmp), block_(nullptr) {}
~BlockConstructor() override { delete block_; }
Status FinishImpl(const Options& options, const KVMap& data) override {
delete block_;
block_ = nullptr;
BlockBuilder builder(&options);
for (const auto& kvp : data) {
builder.Add(kvp.first, kvp.second);
}
data_ = builder.Finish().ToString();
BlockContents contents;
contents.data = data_;
contents.cachable = false;
contents.heap_allocated = false;
block_ = new Block(contents);
return Status::OK();
}
Iterator* NewIterator() const override {
return block_->NewIterator(comparator_);
}
private:
const Comparator* const comparator_;
std::string data_;
Block* block_;
BlockConstructor();
};
class TableConstructor : public Constructor {
public:
TableConstructor(const Comparator* cmp)
: Constructor(cmp), source_(nullptr), table_(nullptr) {}
~TableConstructor() override { Reset(); }
Status FinishImpl(const Options& options, const KVMap& data) override {
Reset();
StringSink sink;
TableBuilder builder(options, &sink);
for (const auto& kvp : data) {
builder.Add(kvp.first, kvp.second);
EXPECT_LEVELDB_OK(builder.status());
}
Status s = builder.Finish();
EXPECT_LEVELDB_OK(s);
EXPECT_EQ(sink.contents().size(), builder.FileSize());
source_ = new StringSource(sink.contents());
Options table_options;
table_options.comparator = options.comparator;
return Table::Open(table_options, source_, sink.contents().size(), &table_);
}
Iterator* NewIterator() const override {
return table_->NewIterator(ReadOptions());
}
uint64_t ApproximateOffsetOf(const Slice& key) const {
return table_->ApproximateOffsetOf(key);
}
private:
void Reset() {
delete table_;
delete source_;
table_ = nullptr;
source_ = nullptr;
}
StringSource* source_;
Table* table_;
TableConstructor();
};
class KeyConvertingIterator : public Iterator {
public:
explicit KeyConvertingIterator(Iterator* iter) : iter_(iter) {}
KeyConvertingIterator(const KeyConvertingIterator&) = delete;
KeyConvertingIterator& operator=(const KeyConvertingIterator&) = delete;
~KeyConvertingIterator() override { delete iter_; }
bool Valid() const override { return iter_->Valid(); }
void Seek(const Slice& target) override {
ParsedInternalKey ikey(target, kMaxSequenceNumber, kTypeValue);
std::string encoded;
AppendInternalKey(&encoded, ikey);
iter_->Seek(encoded);
}
void SeekToFirst() override { iter_->SeekToFirst(); }
void SeekToLast() override { iter_->SeekToLast(); }
void Next() override { iter_->Next(); }
void Prev() override { iter_->Prev(); }
Slice key() const override {
assert(Valid());
ParsedInternalKey key;
if (!ParseInternalKey(iter_->key(), &key)) {
status_ = Status::Corruption("malformed internal key");
return Slice("corrupted key");
}
return key.user_key;
}
Slice value() const override { return iter_->value(); }
Status status() const override {
return status_.ok() ? iter_->status() : status_;
}
private:
mutable Status status_;
Iterator* iter_;
};
class MemTableConstructor : public Constructor {
public:
explicit MemTableConstructor(const Comparator* cmp)
: Constructor(cmp), internal_comparator_(cmp) {
memtable_ = new MemTable(internal_comparator_);
memtable_->Ref();
}
~MemTableConstructor() override { memtable_->Unref(); }
Status FinishImpl(const Options& options, const KVMap& data) override {
memtable_->Unref();
memtable_ = new MemTable(internal_comparator_);
memtable_->Ref();
int seq = 1;
for (const auto& kvp : data) {
memtable_->Add(seq, kTypeValue, kvp.first, kvp.second);
seq++;
}
return Status::OK();
}
Iterator* NewIterator() const override {
return new KeyConvertingIterator(memtable_->NewIterator());
}
private:
const InternalKeyComparator internal_comparator_;
MemTable* memtable_;
};
class DBConstructor : public Constructor {
public:
explicit DBConstructor(const Comparator* cmp)
: Constructor(cmp), comparator_(cmp) {
db_ = nullptr;
NewDB();
}
~DBConstructor() override { delete db_; }
Status FinishImpl(const Options& options, const KVMap& data) override {
delete db_;
db_ = nullptr;
NewDB();
for (const auto& kvp : data) {
WriteBatch batch;
batch.Put(kvp.first, kvp.second);
EXPECT_TRUE(db_->Write(WriteOptions(), &batch).ok());
}
return Status::OK();
}
Iterator* NewIterator() const override {
return db_->NewIterator(ReadOptions());
}
DB* db() const override { return db_; }
private:
void NewDB() {
std::string name = testing::TempDir() + "table_testdb";
Options options;
options.comparator = comparator_;
Status status = DestroyDB(name, options);
ASSERT_TRUE(status.ok()) << status.ToString();
options.create_if_missing = true;
options.error_if_exists = true;
options.write_buffer_size = 10000;
status = DB::Open(options, name, &db_);
ASSERT_TRUE(status.ok()) << status.ToString();
}
const Comparator* const comparator_;
DB* db_;
};
enum TestType { TABLE_TEST, BLOCK_TEST, MEMTABLE_TEST, DB_TEST };
struct TestArgs {
TestType type;
bool reverse_compare;
int restart_interval;
};
static const TestArgs kTestArgList[] = {
{TABLE_TEST, false, 16},
{TABLE_TEST, false, 1},
{TABLE_TEST, false, 1024},
{TABLE_TEST, true, 16},
{TABLE_TEST, true, 1},
{TABLE_TEST, true, 1024},
{BLOCK_TEST, false, 16},
{BLOCK_TEST, false, 1},
{BLOCK_TEST, false, 1024},
{BLOCK_TEST, true, 16},
{BLOCK_TEST, true, 1},
{BLOCK_TEST, true, 1024},
{MEMTABLE_TEST, false, 16},
{MEMTABLE_TEST, true, 16},
{DB_TEST, false, 16},
{DB_TEST, true, 16},
};
static const int kNumTestArgs = sizeof(kTestArgList) / sizeof(kTestArgList[0]);
class Harness : public testing::Test {
public:
Harness() : constructor_(nullptr) {}
void Init(const TestArgs& args) {
delete constructor_;
constructor_ = nullptr;
options_ = Options();
options_.block_restart_interval = args.restart_interval;
options_.block_size = 256;
if (args.reverse_compare) {
options_.comparator = &reverse_key_comparator;
}
switch (args.type) {
case TABLE_TEST:
constructor_ = new TableConstructor(options_.comparator);
break;
case BLOCK_TEST:
constructor_ = new BlockConstructor(options_.comparator);
break;
case MEMTABLE_TEST:
constructor_ = new MemTableConstructor(options_.comparator);
break;
case DB_TEST:
constructor_ = new DBConstructor(options_.comparator);
break;
}
}
~Harness() { delete constructor_; }
void Add(const std::string& key, const std::string& value) {
constructor_->Add(key, value);
}
void Test(Random* rnd) {
std::vector<std::string> keys;
KVMap data;
constructor_->Finish(options_, &keys, &data);
TestForwardScan(keys, data);
TestBackwardScan(keys, data);
TestRandomAccess(rnd, keys, data);
}
void TestForwardScan(const std::vector<std::string>& keys,
const KVMap& data) {
Iterator* iter = constructor_->NewIterator();
ASSERT_TRUE(!iter->Valid());
iter->SeekToFirst();
for (KVMap::const_iterator model_iter = data.begin();
model_iter != data.end(); ++model_iter) {
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
iter->Next();
}
ASSERT_TRUE(!iter->Valid());
delete iter;
}
void TestBackwardScan(const std::vector<std::string>& keys,
const KVMap& data) {
Iterator* iter = constructor_->NewIterator();
ASSERT_TRUE(!iter->Valid());
iter->SeekToLast();
for (KVMap::const_reverse_iterator model_iter = data.rbegin();
model_iter != data.rend(); ++model_iter) {
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
iter->Prev();
}
ASSERT_TRUE(!iter->Valid());
delete iter;
}
void TestRandomAccess(Random* rnd, const std::vector<std::string>& keys,
const KVMap& data) {
static const bool kVerbose = false;
Iterator* iter = constructor_->NewIterator();
ASSERT_TRUE(!iter->Valid());
KVMap::const_iterator model_iter = data.begin();
if (kVerbose) std::fprintf(stderr, "---\n");
for (int i = 0; i < 200; i++) {
const int toss = rnd->Uniform(5);
switch (toss) {
case 0: {
if (iter->Valid()) {
if (kVerbose) std::fprintf(stderr, "Next\n");
iter->Next();
++model_iter;
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
}
break;
}
case 1: {
if (kVerbose) std::fprintf(stderr, "SeekToFirst\n");
iter->SeekToFirst();
model_iter = data.begin();
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
break;
}
case 2: {
std::string key = PickRandomKey(rnd, keys);
model_iter = data.lower_bound(key);
if (kVerbose)
std::fprintf(stderr, "Seek '%s'\n", EscapeString(key).c_str());
iter->Seek(Slice(key));
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
break;
}
case 3: {
if (iter->Valid()) {
if (kVerbose) std::fprintf(stderr, "Prev\n");
iter->Prev();
if (model_iter == data.begin()) {
model_iter = data.end();
} else {
--model_iter;
}
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
}
break;
}
case 4: {
if (kVerbose) std::fprintf(stderr, "SeekToLast\n");
iter->SeekToLast();
if (keys.empty()) {
model_iter = data.end();
} else {
std::string last = data.rbegin()->first;
model_iter = data.lower_bound(last);
}
ASSERT_EQ(ToString(data, model_iter), ToString(iter));
break;
}
}
}
delete iter;
}
std::string ToString(const KVMap& data, const KVMap::const_iterator& it) {
if (it == data.end()) {
return "END";
} else {
return "'" + it->first + "->" + it->second + "'";
}
}
std::string ToString(const KVMap& data,
const KVMap::const_reverse_iterator& it) {
if (it == data.rend()) {
return "END";
} else {
return "'" + it->first + "->" + it->second + "'";
}
}
std::string ToString(const Iterator* it) {
if (!it->Valid()) {
return "END";
} else {
return "'" + it->key().ToString() + "->" + it->value().ToString() + "'";
}
}
std::string PickRandomKey(Random* rnd, const std::vector<std::string>& keys) {
if (keys.empty()) {
return "foo";
} else {
const int index = rnd->Uniform(keys.size());
std::string result = keys[index];
switch (rnd->Uniform(3)) {
case 0:
break;
case 1: {
if (!result.empty() && result[result.size() - 1] > '\0') {
result[result.size() - 1]--;
}
break;
}
case 2: {
Increment(options_.comparator, &result);
break;
}
}
return result;
}
}
DB* db() const { return constructor_->db(); }
private:
Options options_;
Constructor* constructor_;
};
TEST_F(Harness, Empty) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 1);
Test(&rnd);
}
}
TEST_F(Harness, ZeroRestartPointsInBlock) {
char data[sizeof(uint32_t)];
memset(data, 0, sizeof(data));
BlockContents contents;
contents.data = Slice(data, sizeof(data));
contents.cachable = false;
contents.heap_allocated = false;
Block block(contents);
Iterator* iter = block.NewIterator(BytewiseComparator());
iter->SeekToFirst();
ASSERT_TRUE(!iter->Valid());
iter->SeekToLast();
ASSERT_TRUE(!iter->Valid());
iter->Seek("foo");
ASSERT_TRUE(!iter->Valid());
delete iter;
}
TEST_F(Harness, SimpleEmptyKey) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 1);
Add("", "v");
Test(&rnd);
}
}
TEST_F(Harness, SimpleSingle) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 2);
Add("abc", "v");
Test(&rnd);
}
}
TEST_F(Harness, SimpleMulti) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 3);
Add("abc", "v");
Add("abcd", "v");
Add("ac", "v2");
Test(&rnd);
}
}
TEST_F(Harness, SimpleSpecialKey) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 4);
Add("\xff\xff", "v3");
Test(&rnd);
}
}
TEST_F(Harness, Randomized) {
for (int i = 0; i < kNumTestArgs; i++) {
Init(kTestArgList[i]);
Random rnd(test::RandomSeed() + 5);
for (int num_entries = 0; num_entries < 2000;
num_entries += (num_entries < 50 ? 1 : 200)) {
if ((num_entries % 10) == 0) {
std::fprintf(stderr, "case %d of %d: num_entries = %d\n", (i + 1),
int(kNumTestArgs), num_entries);
}
for (int e = 0; e < num_entries; e++) {
std::string v;
Add(test::RandomKey(&rnd, rnd.Skewed(4)),
test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
}
Test(&rnd);
}
}
}
TEST_F(Harness, RandomizedLongDB) {
Random rnd(test::RandomSeed());
TestArgs args = {DB_TEST, false, 16};
Init(args);
int num_entries = 100000;
for (int e = 0; e < num_entries; e++) {
std::string v;
Add(test::RandomKey(&rnd, rnd.Skewed(4)),
test::RandomString(&rnd, rnd.Skewed(5), &v).ToString());
}
Test(&rnd);
int files = 0;
for (int level = 0; level < config::kNumLevels; level++) {
std::string value;
char name[100];
std::snprintf(name, sizeof(name), "leveldb.num-files-at-level%d", level);
ASSERT_TRUE(db()->GetProperty(name, &value));
files += atoi(value.c_str());
}
ASSERT_GT(files, 0);
}
TEST(MemTableTest, Simple) {
InternalKeyComparator cmp(BytewiseComparator());
MemTable* memtable = new MemTable(cmp);
memtable->Ref();
WriteBatch batch;
WriteBatchInternal::SetSequence(&batch, 100);
batch.Put(std::string("k1"), std::string("v1"));
batch.Put(std::string("k2"), std::string("v2"));
batch.Put(std::string("k3"), std::string("v3"));
batch.Put(std::string("largekey"), std::string("vlarge"));
ASSERT_TRUE(WriteBatchInternal::InsertInto(&batch, memtable).ok());
Iterator* iter = memtable->NewIterator();
iter->SeekToFirst();
while (iter->Valid()) {
std::fprintf(stderr, "key: '%s' -> '%s'\n", iter->key().ToString().c_str(),
iter->value().ToString().c_str());
iter->Next();
}
delete iter;
memtable->Unref();
}
static bool Between(uint64_t val, uint64_t low, uint64_t high) {
bool result = (val >= low) && (val <= high);
if (!result) {
std::fprintf(stderr, "Value %llu is not in range [%llu, %llu]\n",
(unsigned long long)(val), (unsigned long long)(low),
(unsigned long long)(high));
}
return result;
}
TEST(TableTest, ApproximateOffsetOfPlain) {
TableConstructor c(BytewiseComparator());
c.Add("k01", "hello");
c.Add("k02", "hello2");
c.Add("k03", std::string(10000, 'x'));
c.Add("k04", std::string(200000, 'x'));
c.Add("k05", std::string(300000, 'x'));
c.Add("k06", "hello3");
c.Add("k07", std::string(100000, 'x'));
std::vector<std::string> keys;
KVMap kvmap;
Options options;
options.block_size = 1024;
options.compression = kNoCompression;
c.Finish(options, &keys, &kvmap);
ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01a"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), 0, 0));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), 10000, 11000));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04a"), 210000, 211000));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k05"), 210000, 211000));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k06"), 510000, 511000));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k07"), 510000, 511000));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 610000, 612000));
}
static bool CompressionSupported(CompressionType type) {
std::string out;
Slice in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
if (type == kSnappyCompression) {
return port::Snappy_Compress(in.data(), in.size(), &out);
} else if (type == kZstdCompression) {
return port::Zstd_Compress(1, in.data(), in.size(), &out);
}
return false;
}
class CompressionTableTest
: public ::testing::TestWithParam<std::tuple<CompressionType>> {};
INSTANTIATE_TEST_SUITE_P(CompressionTests, CompressionTableTest,
::testing::Values(kSnappyCompression,
kZstdCompression));
TEST_P(CompressionTableTest, ApproximateOffsetOfCompressed) {
CompressionType type = ::testing::get<0>(GetParam());
if (!CompressionSupported(type)) {
GTEST_SKIP() << "skipping compression test: " << type;
}
Random rnd(301);
TableConstructor c(BytewiseComparator());
std::string tmp;
c.Add("k01", "hello");
c.Add("k02", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
c.Add("k03", "hello3");
c.Add("k04", test::CompressibleString(&rnd, 0.25, 10000, &tmp));
std::vector<std::string> keys;
KVMap kvmap;
Options options;
options.block_size = 1024;
options.compression = type;
c.Finish(options, &keys, &kvmap);
static const int kSlop = 1000;
const int expected = 2500;
const int min_z = expected - kSlop;
const int max_z = expected + kSlop;
ASSERT_TRUE(Between(c.ApproximateOffsetOf("abc"), 0, kSlop));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k01"), 0, kSlop));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k02"), 0, kSlop));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k03"), min_z, max_z));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("k04"), min_z, max_z));
ASSERT_TRUE(Between(c.ApproximateOffsetOf("xyz"), 2 * min_z, 2 * max_z));
}
} |
464 | cpp | google/leveldb | filter_block | table/filter_block.cc | table/filter_block_test.cc | #ifndef STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_
#define STORAGE_LEVELDB_TABLE_FILTER_BLOCK_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
#include "leveldb/slice.h"
#include "util/hash.h"
namespace leveldb {
class FilterPolicy;
class FilterBlockBuilder {
public:
explicit FilterBlockBuilder(const FilterPolicy*);
FilterBlockBuilder(const FilterBlockBuilder&) = delete;
FilterBlockBuilder& operator=(const FilterBlockBuilder&) = delete;
void StartBlock(uint64_t block_offset);
void AddKey(const Slice& key);
Slice Finish();
private:
void GenerateFilter();
const FilterPolicy* policy_;
std::string keys_;
std::vector<size_t> start_;
std::string result_;
std::vector<Slice> tmp_keys_;
std::vector<uint32_t> filter_offsets_;
};
class FilterBlockReader {
public:
FilterBlockReader(const FilterPolicy* policy, const Slice& contents);
bool KeyMayMatch(uint64_t block_offset, const Slice& key);
private:
const FilterPolicy* policy_;
const char* data_;
const char* offset_;
size_t num_;
size_t base_lg_;
};
}
#endif
#include "table/filter_block.h"
#include "leveldb/filter_policy.h"
#include "util/coding.h"
namespace leveldb {
static const size_t kFilterBaseLg = 11;
static const size_t kFilterBase = 1 << kFilterBaseLg;
FilterBlockBuilder::FilterBlockBuilder(const FilterPolicy* policy)
: policy_(policy) {}
void FilterBlockBuilder::StartBlock(uint64_t block_offset) {
uint64_t filter_index = (block_offset / kFilterBase);
assert(filter_index >= filter_offsets_.size());
while (filter_index > filter_offsets_.size()) {
GenerateFilter();
}
}
void FilterBlockBuilder::AddKey(const Slice& key) {
Slice k = key;
start_.push_back(keys_.size());
keys_.append(k.data(), k.size());
}
Slice FilterBlockBuilder::Finish() {
if (!start_.empty()) {
GenerateFilter();
}
const uint32_t array_offset = result_.size();
for (size_t i = 0; i < filter_offsets_.size(); i++) {
PutFixed32(&result_, filter_offsets_[i]);
}
PutFixed32(&result_, array_offset);
result_.push_back(kFilterBaseLg);
return Slice(result_);
}
void FilterBlockBuilder::GenerateFilter() {
const size_t num_keys = start_.size();
if (num_keys == 0) {
filter_offsets_.push_back(result_.size());
return;
}
start_.push_back(keys_.size());
tmp_keys_.resize(num_keys);
for (size_t i = 0; i < num_keys; i++) {
const char* base = keys_.data() + start_[i];
size_t length = start_[i + 1] - start_[i];
tmp_keys_[i] = Slice(base, length);
}
filter_offsets_.push_back(result_.size());
policy_->CreateFilter(&tmp_keys_[0], static_cast<int>(num_keys), &result_);
tmp_keys_.clear();
keys_.clear();
start_.clear();
}
FilterBlockReader::FilterBlockReader(const FilterPolicy* policy,
const Slice& contents)
: policy_(policy), data_(nullptr), offset_(nullptr), num_(0), base_lg_(0) {
size_t n = contents.size();
if (n < 5) return;
base_lg_ = contents[n - 1];
uint32_t last_word = DecodeFixed32(contents.data() + n - 5);
if (last_word > n - 5) return;
data_ = contents.data();
offset_ = data_ + last_word;
num_ = (n - 5 - last_word) / 4;
}
bool FilterBlockReader::KeyMayMatch(uint64_t block_offset, const Slice& key) {
uint64_t index = block_offset >> base_lg_;
if (index < num_) {
uint32_t start = DecodeFixed32(offset_ + index * 4);
uint32_t limit = DecodeFixed32(offset_ + index * 4 + 4);
if (start <= limit && limit <= static_cast<size_t>(offset_ - data_)) {
Slice filter = Slice(data_ + start, limit - start);
return policy_->KeyMayMatch(key, filter);
} else if (start == limit) {
return false;
}
}
return true;
}
} | #include "table/filter_block.h"
#include "gtest/gtest.h"
#include "leveldb/filter_policy.h"
#include "util/coding.h"
#include "util/hash.h"
#include "util/logging.h"
#include "util/testutil.h"
namespace leveldb {
class TestHashFilter : public FilterPolicy {
public:
const char* Name() const override { return "TestHashFilter"; }
void CreateFilter(const Slice* keys, int n, std::string* dst) const override {
for (int i = 0; i < n; i++) {
uint32_t h = Hash(keys[i].data(), keys[i].size(), 1);
PutFixed32(dst, h);
}
}
bool KeyMayMatch(const Slice& key, const Slice& filter) const override {
uint32_t h = Hash(key.data(), key.size(), 1);
for (size_t i = 0; i + 4 <= filter.size(); i += 4) {
if (h == DecodeFixed32(filter.data() + i)) {
return true;
}
}
return false;
}
};
class FilterBlockTest : public testing::Test {
public:
TestHashFilter policy_;
};
TEST_F(FilterBlockTest, EmptyBuilder) {
FilterBlockBuilder builder(&policy_);
Slice block = builder.Finish();
ASSERT_EQ("\\x00\\x00\\x00\\x00\\x0b", EscapeString(block));
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(0, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(100000, "foo"));
}
TEST_F(FilterBlockTest, SingleChunk) {
FilterBlockBuilder builder(&policy_);
builder.StartBlock(100);
builder.AddKey("foo");
builder.AddKey("bar");
builder.AddKey("box");
builder.StartBlock(200);
builder.AddKey("box");
builder.StartBlock(300);
builder.AddKey("hello");
Slice block = builder.Finish();
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(100, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(100, "bar"));
ASSERT_TRUE(reader.KeyMayMatch(100, "box"));
ASSERT_TRUE(reader.KeyMayMatch(100, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(100, "missing"));
ASSERT_TRUE(!reader.KeyMayMatch(100, "other"));
}
TEST_F(FilterBlockTest, MultiChunk) {
FilterBlockBuilder builder(&policy_);
builder.StartBlock(0);
builder.AddKey("foo");
builder.StartBlock(2000);
builder.AddKey("bar");
builder.StartBlock(3100);
builder.AddKey("box");
builder.StartBlock(9000);
builder.AddKey("box");
builder.AddKey("hello");
Slice block = builder.Finish();
FilterBlockReader reader(&policy_, block);
ASSERT_TRUE(reader.KeyMayMatch(0, "foo"));
ASSERT_TRUE(reader.KeyMayMatch(2000, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(0, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(0, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(3100, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(3100, "hello"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "bar"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "box"));
ASSERT_TRUE(!reader.KeyMayMatch(4100, "hello"));
ASSERT_TRUE(reader.KeyMayMatch(9000, "box"));
ASSERT_TRUE(reader.KeyMayMatch(9000, "hello"));
ASSERT_TRUE(!reader.KeyMayMatch(9000, "foo"));
ASSERT_TRUE(!reader.KeyMayMatch(9000, "bar"));
}
} |
465 | cpp | google/leveldb | filename | db/filename.cc | db/filename_test.cc | #ifndef STORAGE_LEVELDB_DB_FILENAME_H_
#define STORAGE_LEVELDB_DB_FILENAME_H_
#include <cstdint>
#include <string>
#include "leveldb/slice.h"
#include "leveldb/status.h"
#include "port/port.h"
namespace leveldb {
class Env;
enum FileType {
kLogFile,
kDBLockFile,
kTableFile,
kDescriptorFile,
kCurrentFile,
kTempFile,
kInfoLogFile
};
std::string LogFileName(const std::string& dbname, uint64_t number);
std::string TableFileName(const std::string& dbname, uint64_t number);
std::string SSTTableFileName(const std::string& dbname, uint64_t number);
std::string DescriptorFileName(const std::string& dbname, uint64_t number);
std::string CurrentFileName(const std::string& dbname);
std::string LockFileName(const std::string& dbname);
std::string TempFileName(const std::string& dbname, uint64_t number);
std::string InfoLogFileName(const std::string& dbname);
std::string OldInfoLogFileName(const std::string& dbname);
bool ParseFileName(const std::string& filename, uint64_t* number,
FileType* type);
Status SetCurrentFile(Env* env, const std::string& dbname,
uint64_t descriptor_number);
}
#endif
#include "db/filename.h"
#include <cassert>
#include <cstdio>
#include "db/dbformat.h"
#include "leveldb/env.h"
#include "util/logging.h"
namespace leveldb {
Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname);
static std::string MakeFileName(const std::string& dbname, uint64_t number,
const char* suffix) {
char buf[100];
std::snprintf(buf, sizeof(buf), "/%06llu.%s",
static_cast<unsigned long long>(number), suffix);
return dbname + buf;
}
std::string LogFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "log");
}
std::string TableFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "ldb");
}
std::string SSTTableFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "sst");
}
std::string DescriptorFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
char buf[100];
std::snprintf(buf, sizeof(buf), "/MANIFEST-%06llu",
static_cast<unsigned long long>(number));
return dbname + buf;
}
std::string CurrentFileName(const std::string& dbname) {
return dbname + "/CURRENT";
}
std::string LockFileName(const std::string& dbname) { return dbname + "/LOCK"; }
std::string TempFileName(const std::string& dbname, uint64_t number) {
assert(number > 0);
return MakeFileName(dbname, number, "dbtmp");
}
std::string InfoLogFileName(const std::string& dbname) {
return dbname + "/LOG";
}
std::string OldInfoLogFileName(const std::string& dbname) {
return dbname + "/LOG.old";
}
bool ParseFileName(const std::string& filename, uint64_t* number,
FileType* type) {
Slice rest(filename);
if (rest == "CURRENT") {
*number = 0;
*type = kCurrentFile;
} else if (rest == "LOCK") {
*number = 0;
*type = kDBLockFile;
} else if (rest == "LOG" || rest == "LOG.old") {
*number = 0;
*type = kInfoLogFile;
} else if (rest.starts_with("MANIFEST-")) {
rest.remove_prefix(strlen("MANIFEST-"));
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
if (!rest.empty()) {
return false;
}
*type = kDescriptorFile;
*number = num;
} else {
uint64_t num;
if (!ConsumeDecimalNumber(&rest, &num)) {
return false;
}
Slice suffix = rest;
if (suffix == Slice(".log")) {
*type = kLogFile;
} else if (suffix == Slice(".sst") || suffix == Slice(".ldb")) {
*type = kTableFile;
} else if (suffix == Slice(".dbtmp")) {
*type = kTempFile;
} else {
return false;
}
*number = num;
}
return true;
}
Status SetCurrentFile(Env* env, const std::string& dbname,
uint64_t descriptor_number) {
std::string manifest = DescriptorFileName(dbname, descriptor_number);
Slice contents = manifest;
assert(contents.starts_with(dbname + "/"));
contents.remove_prefix(dbname.size() + 1);
std::string tmp = TempFileName(dbname, descriptor_number);
Status s = WriteStringToFileSync(env, contents.ToString() + "\n", tmp);
if (s.ok()) {
s = env->RenameFile(tmp, CurrentFileName(dbname));
}
if (!s.ok()) {
env->RemoveFile(tmp);
}
return s;
}
} | #include "db/filename.h"
#include "gtest/gtest.h"
#include "db/dbformat.h"
#include "port/port.h"
#include "util/logging.h"
namespace leveldb {
TEST(FileNameTest, Parse) {
Slice db;
FileType type;
uint64_t number;
static struct {
const char* fname;
uint64_t number;
FileType type;
} cases[] = {
{"100.log", 100, kLogFile},
{"0.log", 0, kLogFile},
{"0.sst", 0, kTableFile},
{"0.ldb", 0, kTableFile},
{"CURRENT", 0, kCurrentFile},
{"LOCK", 0, kDBLockFile},
{"MANIFEST-2", 2, kDescriptorFile},
{"MANIFEST-7", 7, kDescriptorFile},
{"LOG", 0, kInfoLogFile},
{"LOG.old", 0, kInfoLogFile},
{"18446744073709551615.log", 18446744073709551615ull, kLogFile},
};
for (int i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
std::string f = cases[i].fname;
ASSERT_TRUE(ParseFileName(f, &number, &type)) << f;
ASSERT_EQ(cases[i].type, type) << f;
ASSERT_EQ(cases[i].number, number) << f;
}
static const char* errors[] = {"",
"foo",
"foo-dx-100.log",
".log",
"",
"manifest",
"CURREN",
"CURRENTX",
"MANIFES",
"MANIFEST",
"MANIFEST-",
"XMANIFEST-3",
"MANIFEST-3x",
"LOC",
"LOCKx",
"LO",
"LOGx",
"18446744073709551616.log",
"184467440737095516150.log",
"100",
"100.",
"100.lop"};
for (int i = 0; i < sizeof(errors) / sizeof(errors[0]); i++) {
std::string f = errors[i];
ASSERT_TRUE(!ParseFileName(f, &number, &type)) << f;
}
}
TEST(FileNameTest, Construction) {
uint64_t number;
FileType type;
std::string fname;
fname = CurrentFileName("foo");
ASSERT_EQ("foo/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(0, number);
ASSERT_EQ(kCurrentFile, type);
fname = LockFileName("foo");
ASSERT_EQ("foo/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(0, number);
ASSERT_EQ(kDBLockFile, type);
fname = LogFileName("foo", 192);
ASSERT_EQ("foo/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(192, number);
ASSERT_EQ(kLogFile, type);
fname = TableFileName("bar", 200);
ASSERT_EQ("bar/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(200, number);
ASSERT_EQ(kTableFile, type);
fname = DescriptorFileName("bar", 100);
ASSERT_EQ("bar/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(100, number);
ASSERT_EQ(kDescriptorFile, type);
fname = TempFileName("tmp", 999);
ASSERT_EQ("tmp/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(999, number);
ASSERT_EQ(kTempFile, type);
fname = InfoLogFileName("foo");
ASSERT_EQ("foo/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(0, number);
ASSERT_EQ(kInfoLogFile, type);
fname = OldInfoLogFileName("foo");
ASSERT_EQ("foo/", std::string(fname.data(), 4));
ASSERT_TRUE(ParseFileName(fname.c_str() + 4, &number, &type));
ASSERT_EQ(0, number);
ASSERT_EQ(kInfoLogFile, type);
}
} |
466 | cpp | google/leveldb | version_set | db/version_set.cc | db/version_set_test.cc | #ifndef STORAGE_LEVELDB_DB_VERSION_SET_H_
#define STORAGE_LEVELDB_DB_VERSION_SET_H_
#include <map>
#include <set>
#include <vector>
#include "db/dbformat.h"
#include "db/version_edit.h"
#include "port/port.h"
#include "port/thread_annotations.h"
namespace leveldb {
namespace log {
class Writer;
}
class Compaction;
class Iterator;
class MemTable;
class TableBuilder;
class TableCache;
class Version;
class VersionSet;
class WritableFile;
int FindFile(const InternalKeyComparator& icmp,
const std::vector<FileMetaData*>& files, const Slice& key);
bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,
bool disjoint_sorted_files,
const std::vector<FileMetaData*>& files,
const Slice* smallest_user_key,
const Slice* largest_user_key);
class Version {
public:
struct GetStats {
FileMetaData* seek_file;
int seek_file_level;
};
void AddIterators(const ReadOptions&, std::vector<Iterator*>* iters);
Status Get(const ReadOptions&, const LookupKey& key, std::string* val,
GetStats* stats);
bool UpdateStats(const GetStats& stats);
bool RecordReadSample(Slice key);
void Ref();
void Unref();
void GetOverlappingInputs(
int level,
const InternalKey* begin,
const InternalKey* end,
std::vector<FileMetaData*>* inputs);
bool OverlapInLevel(int level, const Slice* smallest_user_key,
const Slice* largest_user_key);
int PickLevelForMemTableOutput(const Slice& smallest_user_key,
const Slice& largest_user_key);
int NumFiles(int level) const { return files_[level].size(); }
std::string DebugString() const;
private:
friend class Compaction;
friend class VersionSet;
class LevelFileNumIterator;
explicit Version(VersionSet* vset)
: vset_(vset),
next_(this),
prev_(this),
refs_(0),
file_to_compact_(nullptr),
file_to_compact_level_(-1),
compaction_score_(-1),
compaction_level_(-1) {}
Version(const Version&) = delete;
Version& operator=(const Version&) = delete;
~Version();
Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;
void ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,
bool (*func)(void*, int, FileMetaData*));
VersionSet* vset_;
Version* next_;
Version* prev_;
int refs_;
std::vector<FileMetaData*> files_[config::kNumLevels];
FileMetaData* file_to_compact_;
int file_to_compact_level_;
double compaction_score_;
int compaction_level_;
};
class VersionSet {
public:
VersionSet(const std::string& dbname, const Options* options,
TableCache* table_cache, const InternalKeyComparator*);
VersionSet(const VersionSet&) = delete;
VersionSet& operator=(const VersionSet&) = delete;
~VersionSet();
Status LogAndApply(VersionEdit* edit, port::Mutex* mu)
EXCLUSIVE_LOCKS_REQUIRED(mu);
Status Recover(bool* save_manifest);
Version* current() const { return current_; }
uint64_t ManifestFileNumber() const { return manifest_file_number_; }
uint64_t NewFileNumber() { return next_file_number_++; }
void ReuseFileNumber(uint64_t file_number) {
if (next_file_number_ == file_number + 1) {
next_file_number_ = file_number;
}
}
int NumLevelFiles(int level) const;
int64_t NumLevelBytes(int level) const;
uint64_t LastSequence() const { return last_sequence_; }
void SetLastSequence(uint64_t s) {
assert(s >= last_sequence_);
last_sequence_ = s;
}
void MarkFileNumberUsed(uint64_t number);
uint64_t LogNumber() const { return log_number_; }
uint64_t PrevLogNumber() const { return prev_log_number_; }
Compaction* PickCompaction();
Compaction* CompactRange(int level, const InternalKey* begin,
const InternalKey* end);
int64_t MaxNextLevelOverlappingBytes();
Iterator* MakeInputIterator(Compaction* c);
bool NeedsCompaction() const {
Version* v = current_;
return (v->compaction_score_ >= 1) || (v->file_to_compact_ != nullptr);
}
void AddLiveFiles(std::set<uint64_t>* live);
uint64_t ApproximateOffsetOf(Version* v, const InternalKey& key);
struct LevelSummaryStorage {
char buffer[100];
};
const char* LevelSummary(LevelSummaryStorage* scratch) const;
private:
class Builder;
friend class Compaction;
friend class Version;
bool ReuseManifest(const std::string& dscname, const std::string& dscbase);
void Finalize(Version* v);
void GetRange(const std::vector<FileMetaData*>& inputs, InternalKey* smallest,
InternalKey* largest);
void GetRange2(const std::vector<FileMetaData*>& inputs1,
const std::vector<FileMetaData*>& inputs2,
InternalKey* smallest, InternalKey* largest);
void SetupOtherInputs(Compaction* c);
Status WriteSnapshot(log::Writer* log);
void AppendVersion(Version* v);
Env* const env_;
const std::string dbname_;
const Options* const options_;
TableCache* const table_cache_;
const InternalKeyComparator icmp_;
uint64_t next_file_number_;
uint64_t manifest_file_number_;
uint64_t last_sequence_;
uint64_t log_number_;
uint64_t prev_log_number_;
WritableFile* descriptor_file_;
log::Writer* descriptor_log_;
Version dummy_versions_;
Version* current_;
std::string compact_pointer_[config::kNumLevels];
};
class Compaction {
public:
~Compaction();
int level() const { return level_; }
VersionEdit* edit() { return &edit_; }
int num_input_files(int which) const { return inputs_[which].size(); }
FileMetaData* input(int which, int i) const { return inputs_[which][i]; }
uint64_t MaxOutputFileSize() const { return max_output_file_size_; }
bool IsTrivialMove() const;
void AddInputDeletions(VersionEdit* edit);
bool IsBaseLevelForKey(const Slice& user_key);
bool ShouldStopBefore(const Slice& internal_key);
void ReleaseInputs();
private:
friend class Version;
friend class VersionSet;
Compaction(const Options* options, int level);
int level_;
uint64_t max_output_file_size_;
Version* input_version_;
VersionEdit edit_;
std::vector<FileMetaData*> inputs_[2];
std::vector<FileMetaData*> grandparents_;
size_t grandparent_index_;
bool seen_key_;
int64_t overlapped_bytes_;
size_t level_ptrs_[config::kNumLevels];
};
}
#endif
#include "db/version_set.h"
#include <algorithm>
#include <cstdio>
#include "db/filename.h"
#include "db/log_reader.h"
#include "db/log_writer.h"
#include "db/memtable.h"
#include "db/table_cache.h"
#include "leveldb/env.h"
#include "leveldb/table_builder.h"
#include "table/merger.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
static size_t TargetFileSize(const Options* options) {
return options->max_file_size;
}
static int64_t MaxGrandParentOverlapBytes(const Options* options) {
return 10 * TargetFileSize(options);
}
static int64_t ExpandedCompactionByteSizeLimit(const Options* options) {
return 25 * TargetFileSize(options);
}
static double MaxBytesForLevel(const Options* options, int level) {
double result = 10. * 1048576.0;
while (level > 1) {
result *= 10;
level--;
}
return result;
}
static uint64_t MaxFileSizeForLevel(const Options* options, int level) {
return TargetFileSize(options);
}
static int64_t TotalFileSize(const std::vector<FileMetaData*>& files) {
int64_t sum = 0;
for (size_t i = 0; i < files.size(); i++) {
sum += files[i]->file_size;
}
return sum;
}
Version::~Version() {
assert(refs_ == 0);
prev_->next_ = next_;
next_->prev_ = prev_;
for (int level = 0; level < config::kNumLevels; level++) {
for (size_t i = 0; i < files_[level].size(); i++) {
FileMetaData* f = files_[level][i];
assert(f->refs > 0);
f->refs--;
if (f->refs <= 0) {
delete f;
}
}
}
}
int FindFile(const InternalKeyComparator& icmp,
const std::vector<FileMetaData*>& files, const Slice& key) {
uint32_t left = 0;
uint32_t right = files.size();
while (left < right) {
uint32_t mid = (left + right) / 2;
const FileMetaData* f = files[mid];
if (icmp.InternalKeyComparator::Compare(f->largest.Encode(), key) < 0) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
static bool AfterFile(const Comparator* ucmp, const Slice* user_key,
const FileMetaData* f) {
return (user_key != nullptr &&
ucmp->Compare(*user_key, f->largest.user_key()) > 0);
}
static bool BeforeFile(const Comparator* ucmp, const Slice* user_key,
const FileMetaData* f) {
return (user_key != nullptr &&
ucmp->Compare(*user_key, f->smallest.user_key()) < 0);
}
bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,
bool disjoint_sorted_files,
const std::vector<FileMetaData*>& files,
const Slice* smallest_user_key,
const Slice* largest_user_key) {
const Comparator* ucmp = icmp.user_comparator();
if (!disjoint_sorted_files) {
for (size_t i = 0; i < files.size(); i++) {
const FileMetaData* f = files[i];
if (AfterFile(ucmp, smallest_user_key, f) ||
BeforeFile(ucmp, largest_user_key, f)) {
} else {
return true;
}
}
return false;
}
uint32_t index = 0;
if (smallest_user_key != nullptr) {
InternalKey small_key(*smallest_user_key, kMaxSequenceNumber,
kValueTypeForSeek);
index = FindFile(icmp, files, small_key.Encode());
}
if (index >= files.size()) {
return false;
}
return !BeforeFile(ucmp, largest_user_key, files[index]);
}
class Version::LevelFileNumIterator : public Iterator {
public:
LevelFileNumIterator(const InternalKeyComparator& icmp,
const std::vector<FileMetaData*>* flist)
: icmp_(icmp), flist_(flist), index_(flist->size()) {
}
bool Valid() const override { return index_ < flist_->size(); }
void Seek(const Slice& target) override {
index_ = FindFile(icmp_, *flist_, target);
}
void SeekToFirst() override { index_ = 0; }
void SeekToLast() override {
index_ = flist_->empty() ? 0 : flist_->size() - 1;
}
void Next() override {
assert(Valid());
index_++;
}
void Prev() override {
assert(Valid());
if (index_ == 0) {
index_ = flist_->size();
} else {
index_--;
}
}
Slice key() const override {
assert(Valid());
return (*flist_)[index_]->largest.Encode();
}
Slice value() const override {
assert(Valid());
EncodeFixed64(value_buf_, (*flist_)[index_]->number);
EncodeFixed64(value_buf_ + 8, (*flist_)[index_]->file_size);
return Slice(value_buf_, sizeof(value_buf_));
}
Status status() const override { return Status::OK(); }
private:
const InternalKeyComparator icmp_;
const std::vector<FileMetaData*>* const flist_;
uint32_t index_;
mutable char value_buf_[16];
};
static Iterator* GetFileIterator(void* arg, const ReadOptions& options,
const Slice& file_value) {
TableCache* cache = reinterpret_cast<TableCache*>(arg);
if (file_value.size() != 16) {
return NewErrorIterator(
Status::Corruption("FileReader invoked with unexpected value"));
} else {
return cache->NewIterator(options, DecodeFixed64(file_value.data()),
DecodeFixed64(file_value.data() + 8));
}
}
Iterator* Version::NewConcatenatingIterator(const ReadOptions& options,
int level) const {
return NewTwoLevelIterator(
new LevelFileNumIterator(vset_->icmp_, &files_[level]), &GetFileIterator,
vset_->table_cache_, options);
}
void Version::AddIterators(const ReadOptions& options,
std::vector<Iterator*>* iters) {
for (size_t i = 0; i < files_[0].size(); i++) {
iters->push_back(vset_->table_cache_->NewIterator(
options, files_[0][i]->number, files_[0][i]->file_size));
}
for (int level = 1; level < config::kNumLevels; level++) {
if (!files_[level].empty()) {
iters->push_back(NewConcatenatingIterator(options, level));
}
}
}
namespace {
enum SaverState {
kNotFound,
kFound,
kDeleted,
kCorrupt,
};
struct Saver {
SaverState state;
const Comparator* ucmp;
Slice user_key;
std::string* value;
};
}
static void SaveValue(void* arg, const Slice& ikey, const Slice& v) {
Saver* s = reinterpret_cast<Saver*>(arg);
ParsedInternalKey parsed_key;
if (!ParseInternalKey(ikey, &parsed_key)) {
s->state = kCorrupt;
} else {
if (s->ucmp->Compare(parsed_key.user_key, s->user_key) == 0) {
s->state = (parsed_key.type == kTypeValue) ? kFound : kDeleted;
if (s->state == kFound) {
s->value->assign(v.data(), v.size());
}
}
}
}
static bool NewestFirst(FileMetaData* a, FileMetaData* b) {
return a->number > b->number;
}
void Version::ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,
bool (*func)(void*, int, FileMetaData*)) {
const Comparator* ucmp = vset_->icmp_.user_comparator();
std::vector<FileMetaData*> tmp;
tmp.reserve(files_[0].size());
for (uint32_t i = 0; i < files_[0].size(); i++) {
FileMetaData* f = files_[0][i];
if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
tmp.push_back(f);
}
}
if (!tmp.empty()) {
std::sort(tmp.begin(), tmp.end(), NewestFirst);
for (uint32_t i = 0; i < tmp.size(); i++) {
if (!(*func)(arg, 0, tmp[i])) {
return;
}
}
}
for (int level = 1; level < config::kNumLevels; level++) {
size_t num_files = files_[level].size();
if (num_files == 0) continue;
uint32_t index = FindFile(vset_->icmp_, files_[level], internal_key);
if (index < num_files) {
FileMetaData* f = files_[level][index];
if (ucmp->Compare(user_key, f->smallest.user_key()) < 0) {
} else {
if (!(*func)(arg, level, f)) {
return;
}
}
}
}
}
Status Version::Get(const ReadOptions& options, const LookupKey& k,
std::string* value, GetStats* stats) {
stats->seek_file = nullptr;
stats->seek_file_level = -1;
struct State {
Saver saver;
GetStats* stats;
const ReadOptions* options;
Slice ikey;
FileMetaData* last_file_read;
int last_file_read_level;
VersionSet* vset;
Status s;
bool found;
static bool Match(void* arg, int level, FileMetaData* f) {
State* state = reinterpret_cast<State*>(arg);
if (state->stats->seek_file == nullptr &&
state->last_file_read != nullptr) {
state->stats->seek_file = state->last_file_read;
state->stats->seek_file_level = state->last_file_read_level;
}
state->last_file_read = f;
state->last_file_read_level = level;
state->s = state->vset->table_cache_->Get(*state->options, f->number,
f->file_size, state->ikey,
&state->saver, SaveValue);
if (!state->s.ok()) {
state->found = true;
return false;
}
switch (state->saver.state) {
case kNotFound:
return true;
case kFound:
state->found = true;
return false;
case kDeleted:
return false;
case kCorrupt:
state->s =
Status::Corruption("corrupted key for ", state->saver.user_key);
state->found = true;
return false;
}
return false;
}
};
State state;
state.found = false;
state.stats = stats;
state.last_file_read = nullptr;
state.last_file_read_level = -1;
state.options = &options;
state.ikey = k.internal_key();
state.vset = vset_;
state.saver.state = kNotFound;
state.saver.ucmp = vset_->icmp_.user_comparator();
state.saver.user_key = k.user_key();
state.saver.value = value;
ForEachOverlapping(state.saver.user_key, state.ikey, &state, &State::Match);
return state.found ? state.s : Status::NotFound(Slice());
}
bool Version::UpdateStats(const GetStats& stats) {
FileMetaData* f = stats.seek_file;
if (f != nullptr) {
f->allowed_seeks--;
if (f->allowed_seeks <= 0 && file_to_compact_ == nullptr) {
file_to_compact_ = f;
file_to_compact_level_ = stats.seek_file_level;
return true;
}
}
return false;
}
bool Version::RecordReadSample(Slice internal_key) {
ParsedInternalKey ikey;
if (!ParseInternalKey(internal_key, &ikey)) {
return false;
}
struct State {
GetStats stats;
int matches;
static bool Match(void* arg, int level, FileMetaData* f) {
State* state = reinterpret_cast<State*>(arg);
state->matches++;
if (state->matches == 1) {
state->stats.seek_file = f;
state->stats.seek_file_level = level;
}
return state->matches < 2;
}
};
State state;
state.matches = 0;
ForEachOverlapping(ikey.user_key, internal_key, &state, &State::Match);
if (state.matches >= 2) {
return UpdateStats(state.stats);
}
return false;
}
void Version::Ref() { ++refs_; }
void Version::Unref() {
assert(this != &vset_->dummy_versions_);
assert(refs_ >= 1);
--refs_;
if (refs_ == 0) {
delete this;
}
}
bool Version::OverlapInLevel(int level, const Slice* smallest_user_key,
const Slice* largest_user_key) {
return SomeFileOverlapsRange(vset_->icmp_, (level > 0), files_[level],
smallest_user_key, largest_user_key);
}
int Version::PickLevelForMemTableOutput(const Slice& smallest_user_key,
const Slice& largest_user_key) {
int level = 0;
if (!OverlapInLevel(0, &smallest_user_key, &largest_user_key)) {
InternalKey start(smallest_user_key, kMaxSequenceNumber, kValueTypeForSeek);
InternalKey limit(largest_user_key, 0, static_cast<ValueType>(0));
std::vector<FileMetaData*> overlaps;
while (level < config::kMaxMemCompactLevel) {
if (OverlapInLevel(level + 1, &smallest_user_key, &largest_user_key)) {
break;
}
if (level + 2 < config::kNumLevels) {
GetOverlappingInputs(level + 2, &start, &limit, &overlaps);
const int64_t sum = TotalFileSize(overlaps);
if (sum > MaxGrandParentOverlapBytes(vset_->options_)) {
break;
}
}
level++;
}
}
return level;
}
void Version::GetOverlappingInputs(int level, const InternalKey* begin,
const InternalKey* end,
std::vector<FileMetaData*>* inputs) {
assert(level >= 0);
assert(level < config::kNumLevels);
inputs->clear();
Slice user_begin, user_end;
if (begin != nullptr) {
user_begin = begin->user_key();
}
if (end != nullptr) {
user_end = end->user_key();
}
const Comparator* user_cmp = vset_->icmp_.user_comparator();
for (size_t i = 0; i < files_[level].size();) {
FileMetaData* f = files_[level][i++];
const Slice file_start = f->smallest.user_key();
const Slice file_limit = f->largest.user_key();
if (begin != nullptr && user_cmp->Compare(file_limit, user_begin) < 0) {
} else if (end != nullptr && user_cmp->Compare(file_start, user_end) > 0) {
} else {
inputs->push_back(f);
if (level == 0) {
if (begin != nullptr && user_cmp->Compare(file_start, user_begin) < 0) {
user_begin = file_start;
inputs->clear();
i = 0;
} else if (end != nullptr &&
user_cmp->Compare(file_limit, user_end) > 0) {
user_end = file_limit;
inputs->clear();
i = 0;
}
}
}
}
}
std::string Version::DebugString() const {
std::string r;
for (int level = 0; level < config::kNumLevels; level++) {
r.append("--- level ");
AppendNumberTo(&r, level);
r.append(" ---\n");
const std::vector<FileMetaData*>& files = files_[level];
for (size_t i = 0; i < files.size(); i++) {
r.push_back(' ');
AppendNumberTo(&r, files[i]->number);
r.push_back(':');
AppendNumberTo(&r, files[i]->file_size);
r.append("[");
r.append(files[i]->smallest.DebugString());
r.append(" .. ");
r.append(files[i]->largest.DebugString());
r.append("]\n");
}
}
return r;
}
class VersionSet::Builder {
private:
struct BySmallestKey {
const InternalKeyComparator* internal_comparator;
bool operator()(FileMetaData* f1, FileMetaData* f2) const {
int r = internal_comparator->Compare(f1->smallest, f2->smallest);
if (r != 0) {
return (r < 0);
} else {
return (f1->number < f2->number);
}
}
};
typedef std::set<FileMetaData*, BySmallestKey> FileSet;
struct LevelState {
std::set<uint64_t> deleted_files;
FileSet* added_files;
};
VersionSet* vset_;
Version* base_;
LevelState lev | #include "db/version_set.h"
#include "gtest/gtest.h"
#include "util/logging.h"
#include "util/testutil.h"
namespace leveldb {
class FindFileTest : public testing::Test {
public:
FindFileTest() : disjoint_sorted_files_(true) {}
~FindFileTest() {
for (int i = 0; i < files_.size(); i++) {
delete files_[i];
}
}
void Add(const char* smallest, const char* largest,
SequenceNumber smallest_seq = 100,
SequenceNumber largest_seq = 100) {
FileMetaData* f = new FileMetaData;
f->number = files_.size() + 1;
f->smallest = InternalKey(smallest, smallest_seq, kTypeValue);
f->largest = InternalKey(largest, largest_seq, kTypeValue);
files_.push_back(f);
}
int Find(const char* key) {
InternalKey target(key, 100, kTypeValue);
InternalKeyComparator cmp(BytewiseComparator());
return FindFile(cmp, files_, target.Encode());
}
bool Overlaps(const char* smallest, const char* largest) {
InternalKeyComparator cmp(BytewiseComparator());
Slice s(smallest != nullptr ? smallest : "");
Slice l(largest != nullptr ? largest : "");
return SomeFileOverlapsRange(cmp, disjoint_sorted_files_, files_,
(smallest != nullptr ? &s : nullptr),
(largest != nullptr ? &l : nullptr));
}
bool disjoint_sorted_files_;
private:
std::vector<FileMetaData*> files_;
};
TEST_F(FindFileTest, Empty) {
ASSERT_EQ(0, Find("foo"));
ASSERT_TRUE(!Overlaps("a", "z"));
ASSERT_TRUE(!Overlaps(nullptr, "z"));
ASSERT_TRUE(!Overlaps("a", nullptr));
ASSERT_TRUE(!Overlaps(nullptr, nullptr));
}
TEST_F(FindFileTest, Single) {
Add("p", "q");
ASSERT_EQ(0, Find("a"));
ASSERT_EQ(0, Find("p"));
ASSERT_EQ(0, Find("p1"));
ASSERT_EQ(0, Find("q"));
ASSERT_EQ(1, Find("q1"));
ASSERT_EQ(1, Find("z"));
ASSERT_TRUE(!Overlaps("a", "b"));
ASSERT_TRUE(!Overlaps("z1", "z2"));
ASSERT_TRUE(Overlaps("a", "p"));
ASSERT_TRUE(Overlaps("a", "q"));
ASSERT_TRUE(Overlaps("a", "z"));
ASSERT_TRUE(Overlaps("p", "p1"));
ASSERT_TRUE(Overlaps("p", "q"));
ASSERT_TRUE(Overlaps("p", "z"));
ASSERT_TRUE(Overlaps("p1", "p2"));
ASSERT_TRUE(Overlaps("p1", "z"));
ASSERT_TRUE(Overlaps("q", "q"));
ASSERT_TRUE(Overlaps("q", "q1"));
ASSERT_TRUE(!Overlaps(nullptr, "j"));
ASSERT_TRUE(!Overlaps("r", nullptr));
ASSERT_TRUE(Overlaps(nullptr, "p"));
ASSERT_TRUE(Overlaps(nullptr, "p1"));
ASSERT_TRUE(Overlaps("q", nullptr));
ASSERT_TRUE(Overlaps(nullptr, nullptr));
}
TEST_F(FindFileTest, Multiple) {
Add("150", "200");
Add("200", "250");
Add("300", "350");
Add("400", "450");
ASSERT_EQ(0, Find("100"));
ASSERT_EQ(0, Find("150"));
ASSERT_EQ(0, Find("151"));
ASSERT_EQ(0, Find("199"));
ASSERT_EQ(0, Find("200"));
ASSERT_EQ(1, Find("201"));
ASSERT_EQ(1, Find("249"));
ASSERT_EQ(1, Find("250"));
ASSERT_EQ(2, Find("251"));
ASSERT_EQ(2, Find("299"));
ASSERT_EQ(2, Find("300"));
ASSERT_EQ(2, Find("349"));
ASSERT_EQ(2, Find("350"));
ASSERT_EQ(3, Find("351"));
ASSERT_EQ(3, Find("400"));
ASSERT_EQ(3, Find("450"));
ASSERT_EQ(4, Find("451"));
ASSERT_TRUE(!Overlaps("100", "149"));
ASSERT_TRUE(!Overlaps("251", "299"));
ASSERT_TRUE(!Overlaps("451", "500"));
ASSERT_TRUE(!Overlaps("351", "399"));
ASSERT_TRUE(Overlaps("100", "150"));
ASSERT_TRUE(Overlaps("100", "200"));
ASSERT_TRUE(Overlaps("100", "300"));
ASSERT_TRUE(Overlaps("100", "400"));
ASSERT_TRUE(Overlaps("100", "500"));
ASSERT_TRUE(Overlaps("375", "400"));
ASSERT_TRUE(Overlaps("450", "450"));
ASSERT_TRUE(Overlaps("450", "500"));
}
TEST_F(FindFileTest, MultipleNullBoundaries) {
Add("150", "200");
Add("200", "250");
Add("300", "350");
Add("400", "450");
ASSERT_TRUE(!Overlaps(nullptr, "149"));
ASSERT_TRUE(!Overlaps("451", nullptr));
ASSERT_TRUE(Overlaps(nullptr, nullptr));
ASSERT_TRUE(Overlaps(nullptr, "150"));
ASSERT_TRUE(Overlaps(nullptr, "199"));
ASSERT_TRUE(Overlaps(nullptr, "200"));
ASSERT_TRUE(Overlaps(nullptr, "201"));
ASSERT_TRUE(Overlaps(nullptr, "400"));
ASSERT_TRUE(Overlaps(nullptr, "800"));
ASSERT_TRUE(Overlaps("100", nullptr));
ASSERT_TRUE(Overlaps("200", nullptr));
ASSERT_TRUE(Overlaps("449", nullptr));
ASSERT_TRUE(Overlaps("450", nullptr));
}
TEST_F(FindFileTest, OverlapSequenceChecks) {
Add("200", "200", 5000, 3000);
ASSERT_TRUE(!Overlaps("199", "199"));
ASSERT_TRUE(!Overlaps("201", "300"));
ASSERT_TRUE(Overlaps("200", "200"));
ASSERT_TRUE(Overlaps("190", "200"));
ASSERT_TRUE(Overlaps("200", "210"));
}
TEST_F(FindFileTest, OverlappingFiles) {
Add("150", "600");
Add("400", "500");
disjoint_sorted_files_ = false;
ASSERT_TRUE(!Overlaps("100", "149"));
ASSERT_TRUE(!Overlaps("601", "700"));
ASSERT_TRUE(Overlaps("100", "150"));
ASSERT_TRUE(Overlaps("100", "200"));
ASSERT_TRUE(Overlaps("100", "300"));
ASSERT_TRUE(Overlaps("100", "400"));
ASSERT_TRUE(Overlaps("100", "500"));
ASSERT_TRUE(Overlaps("375", "400"));
ASSERT_TRUE(Overlaps("450", "450"));
ASSERT_TRUE(Overlaps("450", "500"));
ASSERT_TRUE(Overlaps("450", "700"));
ASSERT_TRUE(Overlaps("600", "700"));
}
void AddBoundaryInputs(const InternalKeyComparator& icmp,
const std::vector<FileMetaData*>& level_files,
std::vector<FileMetaData*>* compaction_files);
class AddBoundaryInputsTest : public testing::Test {
public:
std::vector<FileMetaData*> level_files_;
std::vector<FileMetaData*> compaction_files_;
std::vector<FileMetaData*> all_files_;
InternalKeyComparator icmp_;
AddBoundaryInputsTest() : icmp_(BytewiseComparator()) {}
~AddBoundaryInputsTest() {
for (size_t i = 0; i < all_files_.size(); ++i) {
delete all_files_[i];
}
all_files_.clear();
}
FileMetaData* CreateFileMetaData(uint64_t number, InternalKey smallest,
InternalKey largest) {
FileMetaData* f = new FileMetaData();
f->number = number;
f->smallest = smallest;
f->largest = largest;
all_files_.push_back(f);
return f;
}
};
TEST_F(AddBoundaryInputsTest, TestEmptyFileSets) {
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_TRUE(compaction_files_.empty());
ASSERT_TRUE(level_files_.empty());
}
TEST_F(AddBoundaryInputsTest, TestEmptyLevelFiles) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 2, kTypeValue),
InternalKey(InternalKey("100", 1, kTypeValue)));
compaction_files_.push_back(f1);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_EQ(1, compaction_files_.size());
ASSERT_EQ(f1, compaction_files_[0]);
ASSERT_TRUE(level_files_.empty());
}
TEST_F(AddBoundaryInputsTest, TestEmptyCompactionFiles) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 2, kTypeValue),
InternalKey(InternalKey("100", 1, kTypeValue)));
level_files_.push_back(f1);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_TRUE(compaction_files_.empty());
ASSERT_EQ(1, level_files_.size());
ASSERT_EQ(f1, level_files_[0]);
}
TEST_F(AddBoundaryInputsTest, TestNoBoundaryFiles) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 2, kTypeValue),
InternalKey(InternalKey("100", 1, kTypeValue)));
FileMetaData* f2 =
CreateFileMetaData(1, InternalKey("200", 2, kTypeValue),
InternalKey(InternalKey("200", 1, kTypeValue)));
FileMetaData* f3 =
CreateFileMetaData(1, InternalKey("300", 2, kTypeValue),
InternalKey(InternalKey("300", 1, kTypeValue)));
level_files_.push_back(f3);
level_files_.push_back(f2);
level_files_.push_back(f1);
compaction_files_.push_back(f2);
compaction_files_.push_back(f3);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_EQ(2, compaction_files_.size());
}
TEST_F(AddBoundaryInputsTest, TestOneBoundaryFiles) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 3, kTypeValue),
InternalKey(InternalKey("100", 2, kTypeValue)));
FileMetaData* f2 =
CreateFileMetaData(1, InternalKey("100", 1, kTypeValue),
InternalKey(InternalKey("200", 3, kTypeValue)));
FileMetaData* f3 =
CreateFileMetaData(1, InternalKey("300", 2, kTypeValue),
InternalKey(InternalKey("300", 1, kTypeValue)));
level_files_.push_back(f3);
level_files_.push_back(f2);
level_files_.push_back(f1);
compaction_files_.push_back(f1);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_EQ(2, compaction_files_.size());
ASSERT_EQ(f1, compaction_files_[0]);
ASSERT_EQ(f2, compaction_files_[1]);
}
TEST_F(AddBoundaryInputsTest, TestTwoBoundaryFiles) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 6, kTypeValue),
InternalKey(InternalKey("100", 5, kTypeValue)));
FileMetaData* f2 =
CreateFileMetaData(1, InternalKey("100", 2, kTypeValue),
InternalKey(InternalKey("300", 1, kTypeValue)));
FileMetaData* f3 =
CreateFileMetaData(1, InternalKey("100", 4, kTypeValue),
InternalKey(InternalKey("100", 3, kTypeValue)));
level_files_.push_back(f2);
level_files_.push_back(f3);
level_files_.push_back(f1);
compaction_files_.push_back(f1);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_EQ(3, compaction_files_.size());
ASSERT_EQ(f1, compaction_files_[0]);
ASSERT_EQ(f3, compaction_files_[1]);
ASSERT_EQ(f2, compaction_files_[2]);
}
TEST_F(AddBoundaryInputsTest, TestDisjoinFilePointers) {
FileMetaData* f1 =
CreateFileMetaData(1, InternalKey("100", 6, kTypeValue),
InternalKey(InternalKey("100", 5, kTypeValue)));
FileMetaData* f2 =
CreateFileMetaData(1, InternalKey("100", 6, kTypeValue),
InternalKey(InternalKey("100", 5, kTypeValue)));
FileMetaData* f3 =
CreateFileMetaData(1, InternalKey("100", 2, kTypeValue),
InternalKey(InternalKey("300", 1, kTypeValue)));
FileMetaData* f4 =
CreateFileMetaData(1, InternalKey("100", 4, kTypeValue),
InternalKey(InternalKey("100", 3, kTypeValue)));
level_files_.push_back(f2);
level_files_.push_back(f3);
level_files_.push_back(f4);
compaction_files_.push_back(f1);
AddBoundaryInputs(icmp_, level_files_, &compaction_files_);
ASSERT_EQ(3, compaction_files_.size());
ASSERT_EQ(f1, compaction_files_[0]);
ASSERT_EQ(f4, compaction_files_[1]);
ASSERT_EQ(f3, compaction_files_[2]);
}
} |
467 | cpp | google/leveldb | dbformat | db/dbformat.cc | db/dbformat_test.cc | #ifndef STORAGE_LEVELDB_DB_DBFORMAT_H_
#define STORAGE_LEVELDB_DB_DBFORMAT_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include "leveldb/comparator.h"
#include "leveldb/db.h"
#include "leveldb/filter_policy.h"
#include "leveldb/slice.h"
#include "leveldb/table_builder.h"
#include "util/coding.h"
#include "util/logging.h"
namespace leveldb {
namespace config {
static const int kNumLevels = 7;
static const int kL0_CompactionTrigger = 4;
static const int kL0_SlowdownWritesTrigger = 8;
static const int kL0_StopWritesTrigger = 12;
static const int kMaxMemCompactLevel = 2;
static const int kReadBytesPeriod = 1048576;
}
class InternalKey;
enum ValueType { kTypeDeletion = 0x0, kTypeValue = 0x1 };
static const ValueType kValueTypeForSeek = kTypeValue;
typedef uint64_t SequenceNumber;
static const SequenceNumber kMaxSequenceNumber = ((0x1ull << 56) - 1);
struct ParsedInternalKey {
Slice user_key;
SequenceNumber sequence;
ValueType type;
ParsedInternalKey() {}
ParsedInternalKey(const Slice& u, const SequenceNumber& seq, ValueType t)
: user_key(u), sequence(seq), type(t) {}
std::string DebugString() const;
};
inline size_t InternalKeyEncodingLength(const ParsedInternalKey& key) {
return key.user_key.size() + 8;
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key);
bool ParseInternalKey(const Slice& internal_key, ParsedInternalKey* result);
inline Slice ExtractUserKey(const Slice& internal_key) {
assert(internal_key.size() >= 8);
return Slice(internal_key.data(), internal_key.size() - 8);
}
class InternalKeyComparator : public Comparator {
private:
const Comparator* user_comparator_;
public:
explicit InternalKeyComparator(const Comparator* c) : user_comparator_(c) {}
const char* Name() const override;
int Compare(const Slice& a, const Slice& b) const override;
void FindShortestSeparator(std::string* start,
const Slice& limit) const override;
void FindShortSuccessor(std::string* key) const override;
const Comparator* user_comparator() const { return user_comparator_; }
int Compare(const InternalKey& a, const InternalKey& b) const;
};
class InternalFilterPolicy : public FilterPolicy {
private:
const FilterPolicy* const user_policy_;
public:
explicit InternalFilterPolicy(const FilterPolicy* p) : user_policy_(p) {}
const char* Name() const override;
void CreateFilter(const Slice* keys, int n, std::string* dst) const override;
bool KeyMayMatch(const Slice& key, const Slice& filter) const override;
};
class InternalKey {
private:
std::string rep_;
public:
InternalKey() {}
InternalKey(const Slice& user_key, SequenceNumber s, ValueType t) {
AppendInternalKey(&rep_, ParsedInternalKey(user_key, s, t));
}
bool DecodeFrom(const Slice& s) {
rep_.assign(s.data(), s.size());
return !rep_.empty();
}
Slice Encode() const {
assert(!rep_.empty());
return rep_;
}
Slice user_key() const { return ExtractUserKey(rep_); }
void SetFrom(const ParsedInternalKey& p) {
rep_.clear();
AppendInternalKey(&rep_, p);
}
void Clear() { rep_.clear(); }
std::string DebugString() const;
};
inline int InternalKeyComparator::Compare(const InternalKey& a,
const InternalKey& b) const {
return Compare(a.Encode(), b.Encode());
}
inline bool ParseInternalKey(const Slice& internal_key,
ParsedInternalKey* result) {
const size_t n = internal_key.size();
if (n < 8) return false;
uint64_t num = DecodeFixed64(internal_key.data() + n - 8);
uint8_t c = num & 0xff;
result->sequence = num >> 8;
result->type = static_cast<ValueType>(c);
result->user_key = Slice(internal_key.data(), n - 8);
return (c <= static_cast<uint8_t>(kTypeValue));
}
class LookupKey {
public:
LookupKey(const Slice& user_key, SequenceNumber sequence);
LookupKey(const LookupKey&) = delete;
LookupKey& operator=(const LookupKey&) = delete;
~LookupKey();
Slice memtable_key() const { return Slice(start_, end_ - start_); }
Slice internal_key() const { return Slice(kstart_, end_ - kstart_); }
Slice user_key() const { return Slice(kstart_, end_ - kstart_ - 8); }
private:
const char* start_;
const char* kstart_;
const char* end_;
char space_[200];
};
inline LookupKey::~LookupKey() {
if (start_ != space_) delete[] start_;
}
}
#endif
#include "db/dbformat.h"
#include <cstdio>
#include <sstream>
#include "port/port.h"
#include "util/coding.h"
namespace leveldb {
static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
assert(seq <= kMaxSequenceNumber);
assert(t <= kValueTypeForSeek);
return (seq << 8) | t;
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
result->append(key.user_key.data(), key.user_key.size());
PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}
std::string ParsedInternalKey::DebugString() const {
std::ostringstream ss;
ss << '\'' << EscapeString(user_key.ToString()) << "' @ " << sequence << " : "
<< static_cast<int>(type);
return ss.str();
}
std::string InternalKey::DebugString() const {
ParsedInternalKey parsed;
if (ParseInternalKey(rep_, &parsed)) {
return parsed.DebugString();
}
std::ostringstream ss;
ss << "(bad)" << EscapeString(rep_);
return ss.str();
}
const char* InternalKeyComparator::Name() const {
return "leveldb.InternalKeyComparator";
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
if (r == 0) {
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
void InternalKeyComparator::FindShortestSeparator(std::string* start,
const Slice& limit) const {
Slice user_start = ExtractUserKey(*start);
Slice user_limit = ExtractUserKey(limit);
std::string tmp(user_start.data(), user_start.size());
user_comparator_->FindShortestSeparator(&tmp, user_limit);
if (tmp.size() < user_start.size() &&
user_comparator_->Compare(user_start, tmp) < 0) {
PutFixed64(&tmp,
PackSequenceAndType(kMaxSequenceNumber, kValueTypeForSeek));
assert(this->Compare(*start, tmp) < 0);
assert(this->Compare(tmp, limit) < 0);
start->swap(tmp);
}
}
void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
Slice user_key = ExtractUserKey(*key);
std::string tmp(user_key.data(), user_key.size());
user_comparator_->FindShortSuccessor(&tmp);
if (tmp.size() < user_key.size() &&
user_comparator_->Compare(user_key, tmp) < 0) {
PutFixed64(&tmp,
PackSequenceAndType(kMaxSequenceNumber, kValueTypeForSeek));
assert(this->Compare(*key, tmp) < 0);
key->swap(tmp);
}
}
const char* InternalFilterPolicy::Name() const { return user_policy_->Name(); }
void InternalFilterPolicy::CreateFilter(const Slice* keys, int n,
std::string* dst) const {
Slice* mkey = const_cast<Slice*>(keys);
for (int i = 0; i < n; i++) {
mkey[i] = ExtractUserKey(keys[i]);
}
user_policy_->CreateFilter(keys, n, dst);
}
bool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const {
return user_policy_->KeyMayMatch(ExtractUserKey(key), f);
}
LookupKey::LookupKey(const Slice& user_key, SequenceNumber s) {
size_t usize = user_key.size();
size_t needed = usize + 13;
char* dst;
if (needed <= sizeof(space_)) {
dst = space_;
} else {
dst = new char[needed];
}
start_ = dst;
dst = EncodeVarint32(dst, usize + 8);
kstart_ = dst;
std::memcpy(dst, user_key.data(), usize);
dst += usize;
EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
dst += 8;
end_ = dst;
}
} | #include "db/dbformat.h"
#include "gtest/gtest.h"
#include "util/logging.h"
namespace leveldb {
static std::string IKey(const std::string& user_key, uint64_t seq,
ValueType vt) {
std::string encoded;
AppendInternalKey(&encoded, ParsedInternalKey(user_key, seq, vt));
return encoded;
}
static std::string Shorten(const std::string& s, const std::string& l) {
std::string result = s;
InternalKeyComparator(BytewiseComparator()).FindShortestSeparator(&result, l);
return result;
}
static std::string ShortSuccessor(const std::string& s) {
std::string result = s;
InternalKeyComparator(BytewiseComparator()).FindShortSuccessor(&result);
return result;
}
static void TestKey(const std::string& key, uint64_t seq, ValueType vt) {
std::string encoded = IKey(key, seq, vt);
Slice in(encoded);
ParsedInternalKey decoded("", 0, kTypeValue);
ASSERT_TRUE(ParseInternalKey(in, &decoded));
ASSERT_EQ(key, decoded.user_key.ToString());
ASSERT_EQ(seq, decoded.sequence);
ASSERT_EQ(vt, decoded.type);
ASSERT_TRUE(!ParseInternalKey(Slice("bar"), &decoded));
}
TEST(FormatTest, InternalKey_EncodeDecode) {
const char* keys[] = {"", "k", "hello", "longggggggggggggggggggggg"};
const uint64_t seq[] = {1,
2,
3,
(1ull << 8) - 1,
1ull << 8,
(1ull << 8) + 1,
(1ull << 16) - 1,
1ull << 16,
(1ull << 16) + 1,
(1ull << 32) - 1,
1ull << 32,
(1ull << 32) + 1};
for (int k = 0; k < sizeof(keys) / sizeof(keys[0]); k++) {
for (int s = 0; s < sizeof(seq) / sizeof(seq[0]); s++) {
TestKey(keys[k], seq[s], kTypeValue);
TestKey("hello", 1, kTypeDeletion);
}
}
}
TEST(FormatTest, InternalKey_DecodeFromEmpty) {
InternalKey internal_key;
ASSERT_TRUE(!internal_key.DecodeFrom(""));
}
TEST(FormatTest, InternalKeyShortSeparator) {
ASSERT_EQ(IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 99, kTypeValue)));
ASSERT_EQ(
IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 101, kTypeValue)));
ASSERT_EQ(
IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 100, kTypeValue)));
ASSERT_EQ(
IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("foo", 100, kTypeDeletion)));
ASSERT_EQ(IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("bar", 99, kTypeValue)));
ASSERT_EQ(
IKey("g", kMaxSequenceNumber, kValueTypeForSeek),
Shorten(IKey("foo", 100, kTypeValue), IKey("hello", 200, kTypeValue)));
ASSERT_EQ(
IKey("foo", 100, kTypeValue),
Shorten(IKey("foo", 100, kTypeValue), IKey("foobar", 200, kTypeValue)));
ASSERT_EQ(
IKey("foobar", 100, kTypeValue),
Shorten(IKey("foobar", 100, kTypeValue), IKey("foo", 200, kTypeValue)));
}
TEST(FormatTest, InternalKeyShortestSuccessor) {
ASSERT_EQ(IKey("g", kMaxSequenceNumber, kValueTypeForSeek),
ShortSuccessor(IKey("foo", 100, kTypeValue)));
ASSERT_EQ(IKey("\xff\xff", 100, kTypeValue),
ShortSuccessor(IKey("\xff\xff", 100, kTypeValue)));
}
TEST(FormatTest, ParsedInternalKeyDebugString) {
ParsedInternalKey key("The \"key\" in 'single quotes'", 42, kTypeValue);
ASSERT_EQ("'The \"key\" in 'single quotes'' @ 42 : 1", key.DebugString());
}
TEST(FormatTest, InternalKeyDebugString) {
InternalKey key("The \"key\" in 'single quotes'", 42, kTypeValue);
ASSERT_EQ("'The \"key\" in 'single quotes'' @ 42 : 1", key.DebugString());
InternalKey invalid_key;
ASSERT_EQ("(bad)", invalid_key.DebugString());
}
} |
468 | cpp | google/leveldb | version_edit | db/version_edit.cc | db/version_edit_test.cc | #ifndef STORAGE_LEVELDB_DB_VERSION_EDIT_H_
#define STORAGE_LEVELDB_DB_VERSION_EDIT_H_
#include <set>
#include <utility>
#include <vector>
#include "db/dbformat.h"
namespace leveldb {
class VersionSet;
struct FileMetaData {
FileMetaData() : refs(0), allowed_seeks(1 << 30), file_size(0) {}
int refs;
int allowed_seeks;
uint64_t number;
uint64_t file_size;
InternalKey smallest;
InternalKey largest;
};
class VersionEdit {
public:
VersionEdit() { Clear(); }
~VersionEdit() = default;
void Clear();
void SetComparatorName(const Slice& name) {
has_comparator_ = true;
comparator_ = name.ToString();
}
void SetLogNumber(uint64_t num) {
has_log_number_ = true;
log_number_ = num;
}
void SetPrevLogNumber(uint64_t num) {
has_prev_log_number_ = true;
prev_log_number_ = num;
}
void SetNextFile(uint64_t num) {
has_next_file_number_ = true;
next_file_number_ = num;
}
void SetLastSequence(SequenceNumber seq) {
has_last_sequence_ = true;
last_sequence_ = seq;
}
void SetCompactPointer(int level, const InternalKey& key) {
compact_pointers_.push_back(std::make_pair(level, key));
}
void AddFile(int level, uint64_t file, uint64_t file_size,
const InternalKey& smallest, const InternalKey& largest) {
FileMetaData f;
f.number = file;
f.file_size = file_size;
f.smallest = smallest;
f.largest = largest;
new_files_.push_back(std::make_pair(level, f));
}
void RemoveFile(int level, uint64_t file) {
deleted_files_.insert(std::make_pair(level, file));
}
void EncodeTo(std::string* dst) const;
Status DecodeFrom(const Slice& src);
std::string DebugString() const;
private:
friend class VersionSet;
typedef std::set<std::pair<int, uint64_t>> DeletedFileSet;
std::string comparator_;
uint64_t log_number_;
uint64_t prev_log_number_;
uint64_t next_file_number_;
SequenceNumber last_sequence_;
bool has_comparator_;
bool has_log_number_;
bool has_prev_log_number_;
bool has_next_file_number_;
bool has_last_sequence_;
std::vector<std::pair<int, InternalKey>> compact_pointers_;
DeletedFileSet deleted_files_;
std::vector<std::pair<int, FileMetaData>> new_files_;
};
}
#endif
#include "db/version_edit.h"
#include "db/version_set.h"
#include "util/coding.h"
namespace leveldb {
enum Tag {
kComparator = 1,
kLogNumber = 2,
kNextFileNumber = 3,
kLastSequence = 4,
kCompactPointer = 5,
kDeletedFile = 6,
kNewFile = 7,
kPrevLogNumber = 9
};
void VersionEdit::Clear() {
comparator_.clear();
log_number_ = 0;
prev_log_number_ = 0;
last_sequence_ = 0;
next_file_number_ = 0;
has_comparator_ = false;
has_log_number_ = false;
has_prev_log_number_ = false;
has_next_file_number_ = false;
has_last_sequence_ = false;
compact_pointers_.clear();
deleted_files_.clear();
new_files_.clear();
}
void VersionEdit::EncodeTo(std::string* dst) const {
if (has_comparator_) {
PutVarint32(dst, kComparator);
PutLengthPrefixedSlice(dst, comparator_);
}
if (has_log_number_) {
PutVarint32(dst, kLogNumber);
PutVarint64(dst, log_number_);
}
if (has_prev_log_number_) {
PutVarint32(dst, kPrevLogNumber);
PutVarint64(dst, prev_log_number_);
}
if (has_next_file_number_) {
PutVarint32(dst, kNextFileNumber);
PutVarint64(dst, next_file_number_);
}
if (has_last_sequence_) {
PutVarint32(dst, kLastSequence);
PutVarint64(dst, last_sequence_);
}
for (size_t i = 0; i < compact_pointers_.size(); i++) {
PutVarint32(dst, kCompactPointer);
PutVarint32(dst, compact_pointers_[i].first);
PutLengthPrefixedSlice(dst, compact_pointers_[i].second.Encode());
}
for (const auto& deleted_file_kvp : deleted_files_) {
PutVarint32(dst, kDeletedFile);
PutVarint32(dst, deleted_file_kvp.first);
PutVarint64(dst, deleted_file_kvp.second);
}
for (size_t i = 0; i < new_files_.size(); i++) {
const FileMetaData& f = new_files_[i].second;
PutVarint32(dst, kNewFile);
PutVarint32(dst, new_files_[i].first);
PutVarint64(dst, f.number);
PutVarint64(dst, f.file_size);
PutLengthPrefixedSlice(dst, f.smallest.Encode());
PutLengthPrefixedSlice(dst, f.largest.Encode());
}
}
static bool GetInternalKey(Slice* input, InternalKey* dst) {
Slice str;
if (GetLengthPrefixedSlice(input, &str)) {
return dst->DecodeFrom(str);
} else {
return false;
}
}
static bool GetLevel(Slice* input, int* level) {
uint32_t v;
if (GetVarint32(input, &v) && v < config::kNumLevels) {
*level = v;
return true;
} else {
return false;
}
}
Status VersionEdit::DecodeFrom(const Slice& src) {
Clear();
Slice input = src;
const char* msg = nullptr;
uint32_t tag;
int level;
uint64_t number;
FileMetaData f;
Slice str;
InternalKey key;
while (msg == nullptr && GetVarint32(&input, &tag)) {
switch (tag) {
case kComparator:
if (GetLengthPrefixedSlice(&input, &str)) {
comparator_ = str.ToString();
has_comparator_ = true;
} else {
msg = "comparator name";
}
break;
case kLogNumber:
if (GetVarint64(&input, &log_number_)) {
has_log_number_ = true;
} else {
msg = "log number";
}
break;
case kPrevLogNumber:
if (GetVarint64(&input, &prev_log_number_)) {
has_prev_log_number_ = true;
} else {
msg = "previous log number";
}
break;
case kNextFileNumber:
if (GetVarint64(&input, &next_file_number_)) {
has_next_file_number_ = true;
} else {
msg = "next file number";
}
break;
case kLastSequence:
if (GetVarint64(&input, &last_sequence_)) {
has_last_sequence_ = true;
} else {
msg = "last sequence number";
}
break;
case kCompactPointer:
if (GetLevel(&input, &level) && GetInternalKey(&input, &key)) {
compact_pointers_.push_back(std::make_pair(level, key));
} else {
msg = "compaction pointer";
}
break;
case kDeletedFile:
if (GetLevel(&input, &level) && GetVarint64(&input, &number)) {
deleted_files_.insert(std::make_pair(level, number));
} else {
msg = "deleted file";
}
break;
case kNewFile:
if (GetLevel(&input, &level) && GetVarint64(&input, &f.number) &&
GetVarint64(&input, &f.file_size) &&
GetInternalKey(&input, &f.smallest) &&
GetInternalKey(&input, &f.largest)) {
new_files_.push_back(std::make_pair(level, f));
} else {
msg = "new-file entry";
}
break;
default:
msg = "unknown tag";
break;
}
}
if (msg == nullptr && !input.empty()) {
msg = "invalid tag";
}
Status result;
if (msg != nullptr) {
result = Status::Corruption("VersionEdit", msg);
}
return result;
}
std::string VersionEdit::DebugString() const {
std::string r;
r.append("VersionEdit {");
if (has_comparator_) {
r.append("\n Comparator: ");
r.append(comparator_);
}
if (has_log_number_) {
r.append("\n LogNumber: ");
AppendNumberTo(&r, log_number_);
}
if (has_prev_log_number_) {
r.append("\n PrevLogNumber: ");
AppendNumberTo(&r, prev_log_number_);
}
if (has_next_file_number_) {
r.append("\n NextFile: ");
AppendNumberTo(&r, next_file_number_);
}
if (has_last_sequence_) {
r.append("\n LastSeq: ");
AppendNumberTo(&r, last_sequence_);
}
for (size_t i = 0; i < compact_pointers_.size(); i++) {
r.append("\n CompactPointer: ");
AppendNumberTo(&r, compact_pointers_[i].first);
r.append(" ");
r.append(compact_pointers_[i].second.DebugString());
}
for (const auto& deleted_files_kvp : deleted_files_) {
r.append("\n RemoveFile: ");
AppendNumberTo(&r, deleted_files_kvp.first);
r.append(" ");
AppendNumberTo(&r, deleted_files_kvp.second);
}
for (size_t i = 0; i < new_files_.size(); i++) {
const FileMetaData& f = new_files_[i].second;
r.append("\n AddFile: ");
AppendNumberTo(&r, new_files_[i].first);
r.append(" ");
AppendNumberTo(&r, f.number);
r.append(" ");
AppendNumberTo(&r, f.file_size);
r.append(" ");
r.append(f.smallest.DebugString());
r.append(" .. ");
r.append(f.largest.DebugString());
}
r.append("\n}\n");
return r;
}
} | #include "db/version_edit.h"
#include "gtest/gtest.h"
namespace leveldb {
static void TestEncodeDecode(const VersionEdit& edit) {
std::string encoded, encoded2;
edit.EncodeTo(&encoded);
VersionEdit parsed;
Status s = parsed.DecodeFrom(encoded);
ASSERT_TRUE(s.ok()) << s.ToString();
parsed.EncodeTo(&encoded2);
ASSERT_EQ(encoded, encoded2);
}
TEST(VersionEditTest, EncodeDecode) {
static const uint64_t kBig = 1ull << 50;
VersionEdit edit;
for (int i = 0; i < 4; i++) {
TestEncodeDecode(edit);
edit.AddFile(3, kBig + 300 + i, kBig + 400 + i,
InternalKey("foo", kBig + 500 + i, kTypeValue),
InternalKey("zoo", kBig + 600 + i, kTypeDeletion));
edit.RemoveFile(4, kBig + 700 + i);
edit.SetCompactPointer(i, InternalKey("x", kBig + 900 + i, kTypeValue));
}
edit.SetComparatorName("foo");
edit.SetLogNumber(kBig + 100);
edit.SetNextFile(kBig + 200);
edit.SetLastSequence(kBig + 1000);
TestEncodeDecode(edit);
}
} |
469 | cpp | google/leveldb | write_batch | db/write_batch.cc | db/write_batch_test.cc | #ifndef STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_
#define STORAGE_LEVELDB_INCLUDE_WRITE_BATCH_H_
#include <string>
#include "leveldb/export.h"
#include "leveldb/status.h"
namespace leveldb {
class Slice;
class LEVELDB_EXPORT WriteBatch {
public:
class LEVELDB_EXPORT Handler {
public:
virtual ~Handler();
virtual void Put(const Slice& key, const Slice& value) = 0;
virtual void Delete(const Slice& key) = 0;
};
WriteBatch();
WriteBatch(const WriteBatch&) = default;
WriteBatch& operator=(const WriteBatch&) = default;
~WriteBatch();
void Put(const Slice& key, const Slice& value);
void Delete(const Slice& key);
void Clear();
size_t ApproximateSize() const;
void Append(const WriteBatch& source);
Status Iterate(Handler* handler) const;
private:
friend class WriteBatchInternal;
std::string rep_;
};
}
#endif
#include "leveldb/write_batch.h"
#include "db/dbformat.h"
#include "db/memtable.h"
#include "db/write_batch_internal.h"
#include "leveldb/db.h"
#include "util/coding.h"
namespace leveldb {
static const size_t kHeader = 12;
WriteBatch::WriteBatch() { Clear(); }
WriteBatch::~WriteBatch() = default;
WriteBatch::Handler::~Handler() = default;
void WriteBatch::Clear() {
rep_.clear();
rep_.resize(kHeader);
}
size_t WriteBatch::ApproximateSize() const { return rep_.size(); }
Status WriteBatch::Iterate(Handler* handler) const {
Slice input(rep_);
if (input.size() < kHeader) {
return Status::Corruption("malformed WriteBatch (too small)");
}
input.remove_prefix(kHeader);
Slice key, value;
int found = 0;
while (!input.empty()) {
found++;
char tag = input[0];
input.remove_prefix(1);
switch (tag) {
case kTypeValue:
if (GetLengthPrefixedSlice(&input, &key) &&
GetLengthPrefixedSlice(&input, &value)) {
handler->Put(key, value);
} else {
return Status::Corruption("bad WriteBatch Put");
}
break;
case kTypeDeletion:
if (GetLengthPrefixedSlice(&input, &key)) {
handler->Delete(key);
} else {
return Status::Corruption("bad WriteBatch Delete");
}
break;
default:
return Status::Corruption("unknown WriteBatch tag");
}
}
if (found != WriteBatchInternal::Count(this)) {
return Status::Corruption("WriteBatch has wrong count");
} else {
return Status::OK();
}
}
int WriteBatchInternal::Count(const WriteBatch* b) {
return DecodeFixed32(b->rep_.data() + 8);
}
void WriteBatchInternal::SetCount(WriteBatch* b, int n) {
EncodeFixed32(&b->rep_[8], n);
}
SequenceNumber WriteBatchInternal::Sequence(const WriteBatch* b) {
return SequenceNumber(DecodeFixed64(b->rep_.data()));
}
void WriteBatchInternal::SetSequence(WriteBatch* b, SequenceNumber seq) {
EncodeFixed64(&b->rep_[0], seq);
}
void WriteBatch::Put(const Slice& key, const Slice& value) {
WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1);
rep_.push_back(static_cast<char>(kTypeValue));
PutLengthPrefixedSlice(&rep_, key);
PutLengthPrefixedSlice(&rep_, value);
}
void WriteBatch::Delete(const Slice& key) {
WriteBatchInternal::SetCount(this, WriteBatchInternal::Count(this) + 1);
rep_.push_back(static_cast<char>(kTypeDeletion));
PutLengthPrefixedSlice(&rep_, key);
}
void WriteBatch::Append(const WriteBatch& source) {
WriteBatchInternal::Append(this, &source);
}
namespace {
class MemTableInserter : public WriteBatch::Handler {
public:
SequenceNumber sequence_;
MemTable* mem_;
void Put(const Slice& key, const Slice& value) override {
mem_->Add(sequence_, kTypeValue, key, value);
sequence_++;
}
void Delete(const Slice& key) override {
mem_->Add(sequence_, kTypeDeletion, key, Slice());
sequence_++;
}
};
}
Status WriteBatchInternal::InsertInto(const WriteBatch* b, MemTable* memtable) {
MemTableInserter inserter;
inserter.sequence_ = WriteBatchInternal::Sequence(b);
inserter.mem_ = memtable;
return b->Iterate(&inserter);
}
void WriteBatchInternal::SetContents(WriteBatch* b, const Slice& contents) {
assert(contents.size() >= kHeader);
b->rep_.assign(contents.data(), contents.size());
}
void WriteBatchInternal::Append(WriteBatch* dst, const WriteBatch* src) {
SetCount(dst, Count(dst) + Count(src));
assert(src->rep_.size() >= kHeader);
dst->rep_.append(src->rep_.data() + kHeader, src->rep_.size() - kHeader);
}
} | #include "gtest/gtest.h"
#include "db/memtable.h"
#include "db/write_batch_internal.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "util/logging.h"
namespace leveldb {
static std::string PrintContents(WriteBatch* b) {
InternalKeyComparator cmp(BytewiseComparator());
MemTable* mem = new MemTable(cmp);
mem->Ref();
std::string state;
Status s = WriteBatchInternal::InsertInto(b, mem);
int count = 0;
Iterator* iter = mem->NewIterator();
for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
ParsedInternalKey ikey;
EXPECT_TRUE(ParseInternalKey(iter->key(), &ikey));
switch (ikey.type) {
case kTypeValue:
state.append("Put(");
state.append(ikey.user_key.ToString());
state.append(", ");
state.append(iter->value().ToString());
state.append(")");
count++;
break;
case kTypeDeletion:
state.append("Delete(");
state.append(ikey.user_key.ToString());
state.append(")");
count++;
break;
}
state.append("@");
state.append(NumberToString(ikey.sequence));
}
delete iter;
if (!s.ok()) {
state.append("ParseError()");
} else if (count != WriteBatchInternal::Count(b)) {
state.append("CountMismatch()");
}
mem->Unref();
return state;
}
TEST(WriteBatchTest, Empty) {
WriteBatch batch;
ASSERT_EQ("", PrintContents(&batch));
ASSERT_EQ(0, WriteBatchInternal::Count(&batch));
}
TEST(WriteBatchTest, Multiple) {
WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box"));
batch.Put(Slice("baz"), Slice("boo"));
WriteBatchInternal::SetSequence(&batch, 100);
ASSERT_EQ(100, WriteBatchInternal::Sequence(&batch));
ASSERT_EQ(3, WriteBatchInternal::Count(&batch));
ASSERT_EQ(
"Put(baz, boo)@102"
"Delete(box)@101"
"Put(foo, bar)@100",
PrintContents(&batch));
}
TEST(WriteBatchTest, Corruption) {
WriteBatch batch;
batch.Put(Slice("foo"), Slice("bar"));
batch.Delete(Slice("box"));
WriteBatchInternal::SetSequence(&batch, 200);
Slice contents = WriteBatchInternal::Contents(&batch);
WriteBatchInternal::SetContents(&batch,
Slice(contents.data(), contents.size() - 1));
ASSERT_EQ(
"Put(foo, bar)@200"
"ParseError()",
PrintContents(&batch));
}
TEST(WriteBatchTest, Append) {
WriteBatch b1, b2;
WriteBatchInternal::SetSequence(&b1, 200);
WriteBatchInternal::SetSequence(&b2, 300);
b1.Append(b2);
ASSERT_EQ("", PrintContents(&b1));
b2.Put("a", "va");
b1.Append(b2);
ASSERT_EQ("Put(a, va)@200", PrintContents(&b1));
b2.Clear();
b2.Put("b", "vb");
b1.Append(b2);
ASSERT_EQ(
"Put(a, va)@200"
"Put(b, vb)@201",
PrintContents(&b1));
b2.Delete("foo");
b1.Append(b2);
ASSERT_EQ(
"Put(a, va)@200"
"Put(b, vb)@202"
"Put(b, vb)@201"
"Delete(foo)@203",
PrintContents(&b1));
}
TEST(WriteBatchTest, ApproximateSize) {
WriteBatch batch;
size_t empty_size = batch.ApproximateSize();
batch.Put(Slice("foo"), Slice("bar"));
size_t one_key_size = batch.ApproximateSize();
ASSERT_LT(empty_size, one_key_size);
batch.Put(Slice("baz"), Slice("boo"));
size_t two_keys_size = batch.ApproximateSize();
ASSERT_LT(one_key_size, two_keys_size);
batch.Delete(Slice("box"));
size_t post_delete_size = batch.ApproximateSize();
ASSERT_LT(two_keys_size, post_delete_size);
}
} |
470 | cpp | google/leveldb | logging | util/logging.cc | util/logging_test.cc | #ifndef STORAGE_LEVELDB_UTIL_LOGGING_H_
#define STORAGE_LEVELDB_UTIL_LOGGING_H_
#include <cstdint>
#include <cstdio>
#include <string>
#include "port/port.h"
namespace leveldb {
class Slice;
class WritableFile;
void AppendNumberTo(std::string* str, uint64_t num);
void AppendEscapedStringTo(std::string* str, const Slice& value);
std::string NumberToString(uint64_t num);
std::string EscapeString(const Slice& value);
bool ConsumeDecimalNumber(Slice* in, uint64_t* val);
}
#endif
#include "util/logging.h"
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include "leveldb/env.h"
#include "leveldb/slice.h"
namespace leveldb {
void AppendNumberTo(std::string* str, uint64_t num) {
char buf[30];
std::snprintf(buf, sizeof(buf), "%llu", static_cast<unsigned long long>(num));
str->append(buf);
}
void AppendEscapedStringTo(std::string* str, const Slice& value) {
for (size_t i = 0; i < value.size(); i++) {
char c = value[i];
if (c >= ' ' && c <= '~') {
str->push_back(c);
} else {
char buf[10];
std::snprintf(buf, sizeof(buf), "\\x%02x",
static_cast<unsigned int>(c) & 0xff);
str->append(buf);
}
}
}
std::string NumberToString(uint64_t num) {
std::string r;
AppendNumberTo(&r, num);
return r;
}
std::string EscapeString(const Slice& value) {
std::string r;
AppendEscapedStringTo(&r, value);
return r;
}
bool ConsumeDecimalNumber(Slice* in, uint64_t* val) {
constexpr const uint64_t kMaxUint64 = std::numeric_limits<uint64_t>::max();
constexpr const char kLastDigitOfMaxUint64 =
'0' + static_cast<char>(kMaxUint64 % 10);
uint64_t value = 0;
const uint8_t* start = reinterpret_cast<const uint8_t*>(in->data());
const uint8_t* end = start + in->size();
const uint8_t* current = start;
for (; current != end; ++current) {
const uint8_t ch = *current;
if (ch < '0' || ch > '9') break;
if (value > kMaxUint64 / 10 ||
(value == kMaxUint64 / 10 && ch > kLastDigitOfMaxUint64)) {
return false;
}
value = (value * 10) + (ch - '0');
}
*val = value;
const size_t digits_consumed = current - start;
in->remove_prefix(digits_consumed);
return digits_consumed != 0;
}
} | #include "util/logging.h"
#include <limits>
#include <string>
#include "gtest/gtest.h"
#include "leveldb/slice.h"
namespace leveldb {
TEST(Logging, NumberToString) {
ASSERT_EQ("0", NumberToString(0));
ASSERT_EQ("1", NumberToString(1));
ASSERT_EQ("9", NumberToString(9));
ASSERT_EQ("10", NumberToString(10));
ASSERT_EQ("11", NumberToString(11));
ASSERT_EQ("19", NumberToString(19));
ASSERT_EQ("99", NumberToString(99));
ASSERT_EQ("100", NumberToString(100));
ASSERT_EQ("109", NumberToString(109));
ASSERT_EQ("190", NumberToString(190));
ASSERT_EQ("123", NumberToString(123));
ASSERT_EQ("12345678", NumberToString(12345678));
static_assert(std::numeric_limits<uint64_t>::max() == 18446744073709551615U,
"Test consistency check");
ASSERT_EQ("18446744073709551000", NumberToString(18446744073709551000U));
ASSERT_EQ("18446744073709551600", NumberToString(18446744073709551600U));
ASSERT_EQ("18446744073709551610", NumberToString(18446744073709551610U));
ASSERT_EQ("18446744073709551614", NumberToString(18446744073709551614U));
ASSERT_EQ("18446744073709551615", NumberToString(18446744073709551615U));
}
void ConsumeDecimalNumberRoundtripTest(uint64_t number,
const std::string& padding = "") {
std::string decimal_number = NumberToString(number);
std::string input_string = decimal_number + padding;
Slice input(input_string);
Slice output = input;
uint64_t result;
ASSERT_TRUE(ConsumeDecimalNumber(&output, &result));
ASSERT_EQ(number, result);
ASSERT_EQ(decimal_number.size(), output.data() - input.data());
ASSERT_EQ(padding.size(), output.size());
}
TEST(Logging, ConsumeDecimalNumberRoundtrip) {
ConsumeDecimalNumberRoundtripTest(0);
ConsumeDecimalNumberRoundtripTest(1);
ConsumeDecimalNumberRoundtripTest(9);
ConsumeDecimalNumberRoundtripTest(10);
ConsumeDecimalNumberRoundtripTest(11);
ConsumeDecimalNumberRoundtripTest(19);
ConsumeDecimalNumberRoundtripTest(99);
ConsumeDecimalNumberRoundtripTest(100);
ConsumeDecimalNumberRoundtripTest(109);
ConsumeDecimalNumberRoundtripTest(190);
ConsumeDecimalNumberRoundtripTest(123);
ASSERT_EQ("12345678", NumberToString(12345678));
for (uint64_t i = 0; i < 100; ++i) {
uint64_t large_number = std::numeric_limits<uint64_t>::max() - i;
ConsumeDecimalNumberRoundtripTest(large_number);
}
}
TEST(Logging, ConsumeDecimalNumberRoundtripWithPadding) {
ConsumeDecimalNumberRoundtripTest(0, " ");
ConsumeDecimalNumberRoundtripTest(1, "abc");
ConsumeDecimalNumberRoundtripTest(9, "x");
ConsumeDecimalNumberRoundtripTest(10, "_");
ConsumeDecimalNumberRoundtripTest(11, std::string("\0\0\0", 3));
ConsumeDecimalNumberRoundtripTest(19, "abc");
ConsumeDecimalNumberRoundtripTest(99, "padding");
ConsumeDecimalNumberRoundtripTest(100, " ");
for (uint64_t i = 0; i < 100; ++i) {
uint64_t large_number = std::numeric_limits<uint64_t>::max() - i;
ConsumeDecimalNumberRoundtripTest(large_number, "pad");
}
}
void ConsumeDecimalNumberOverflowTest(const std::string& input_string) {
Slice input(input_string);
Slice output = input;
uint64_t result;
ASSERT_EQ(false, ConsumeDecimalNumber(&output, &result));
}
TEST(Logging, ConsumeDecimalNumberOverflow) {
static_assert(std::numeric_limits<uint64_t>::max() == 18446744073709551615U,
"Test consistency check");
ConsumeDecimalNumberOverflowTest("18446744073709551616");
ConsumeDecimalNumberOverflowTest("18446744073709551617");
ConsumeDecimalNumberOverflowTest("18446744073709551618");
ConsumeDecimalNumberOverflowTest("18446744073709551619");
ConsumeDecimalNumberOverflowTest("18446744073709551620");
ConsumeDecimalNumberOverflowTest("18446744073709551621");
ConsumeDecimalNumberOverflowTest("18446744073709551622");
ConsumeDecimalNumberOverflowTest("18446744073709551623");
ConsumeDecimalNumberOverflowTest("18446744073709551624");
ConsumeDecimalNumberOverflowTest("18446744073709551625");
ConsumeDecimalNumberOverflowTest("18446744073709551626");
ConsumeDecimalNumberOverflowTest("18446744073709551700");
ConsumeDecimalNumberOverflowTest("99999999999999999999");
}
void ConsumeDecimalNumberNoDigitsTest(const std::string& input_string) {
Slice input(input_string);
Slice output = input;
uint64_t result;
ASSERT_EQ(false, ConsumeDecimalNumber(&output, &result));
ASSERT_EQ(input.data(), output.data());
ASSERT_EQ(input.size(), output.size());
}
TEST(Logging, ConsumeDecimalNumberNoDigits) {
ConsumeDecimalNumberNoDigitsTest("");
ConsumeDecimalNumberNoDigitsTest(" ");
ConsumeDecimalNumberNoDigitsTest("a");
ConsumeDecimalNumberNoDigitsTest(" 123");
ConsumeDecimalNumberNoDigitsTest("a123");
ConsumeDecimalNumberNoDigitsTest(std::string("\000123", 4));
ConsumeDecimalNumberNoDigitsTest(std::string("\177123", 4));
ConsumeDecimalNumberNoDigitsTest(std::string("\377123", 4));
}
} |
471 | cpp | google/leveldb | arena | util/arena.cc | util/arena_test.cc | #ifndef STORAGE_LEVELDB_UTIL_ARENA_H_
#define STORAGE_LEVELDB_UTIL_ARENA_H_
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <vector>
namespace leveldb {
class Arena {
public:
Arena();
Arena(const Arena&) = delete;
Arena& operator=(const Arena&) = delete;
~Arena();
char* Allocate(size_t bytes);
char* AllocateAligned(size_t bytes);
size_t MemoryUsage() const {
return memory_usage_.load(std::memory_order_relaxed);
}
private:
char* AllocateFallback(size_t bytes);
char* AllocateNewBlock(size_t block_bytes);
char* alloc_ptr_;
size_t alloc_bytes_remaining_;
std::vector<char*> blocks_;
std::atomic<size_t> memory_usage_;
};
inline char* Arena::Allocate(size_t bytes) {
assert(bytes > 0);
if (bytes <= alloc_bytes_remaining_) {
char* result = alloc_ptr_;
alloc_ptr_ += bytes;
alloc_bytes_remaining_ -= bytes;
return result;
}
return AllocateFallback(bytes);
}
}
#endif
#include "util/arena.h"
namespace leveldb {
static const int kBlockSize = 4096;
Arena::Arena()
: alloc_ptr_(nullptr), alloc_bytes_remaining_(0), memory_usage_(0) {}
Arena::~Arena() {
for (size_t i = 0; i < blocks_.size(); i++) {
delete[] blocks_[i];
}
}
char* Arena::AllocateFallback(size_t bytes) {
if (bytes > kBlockSize / 4) {
char* result = AllocateNewBlock(bytes);
return result;
}
alloc_ptr_ = AllocateNewBlock(kBlockSize);
alloc_bytes_remaining_ = kBlockSize;
char* result = alloc_ptr_;
alloc_ptr_ += bytes;
alloc_bytes_remaining_ -= bytes;
return result;
}
char* Arena::AllocateAligned(size_t bytes) {
const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8;
static_assert((align & (align - 1)) == 0,
"Pointer size should be a power of 2");
size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align - 1);
size_t slop = (current_mod == 0 ? 0 : align - current_mod);
size_t needed = bytes + slop;
char* result;
if (needed <= alloc_bytes_remaining_) {
result = alloc_ptr_ + slop;
alloc_ptr_ += needed;
alloc_bytes_remaining_ -= needed;
} else {
result = AllocateFallback(bytes);
}
assert((reinterpret_cast<uintptr_t>(result) & (align - 1)) == 0);
return result;
}
char* Arena::AllocateNewBlock(size_t block_bytes) {
char* result = new char[block_bytes];
blocks_.push_back(result);
memory_usage_.fetch_add(block_bytes + sizeof(char*),
std::memory_order_relaxed);
return result;
}
} | #include "util/arena.h"
#include "gtest/gtest.h"
#include "util/random.h"
namespace leveldb {
TEST(ArenaTest, Empty) { Arena arena; }
TEST(ArenaTest, Simple) {
std::vector<std::pair<size_t, char*>> allocated;
Arena arena;
const int N = 100000;
size_t bytes = 0;
Random rnd(301);
for (int i = 0; i < N; i++) {
size_t s;
if (i % (N / 10) == 0) {
s = i;
} else {
s = rnd.OneIn(4000)
? rnd.Uniform(6000)
: (rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20));
}
if (s == 0) {
s = 1;
}
char* r;
if (rnd.OneIn(10)) {
r = arena.AllocateAligned(s);
} else {
r = arena.Allocate(s);
}
for (size_t b = 0; b < s; b++) {
r[b] = i % 256;
}
bytes += s;
allocated.push_back(std::make_pair(s, r));
ASSERT_GE(arena.MemoryUsage(), bytes);
if (i > N / 10) {
ASSERT_LE(arena.MemoryUsage(), bytes * 1.10);
}
}
for (size_t i = 0; i < allocated.size(); i++) {
size_t num_bytes = allocated[i].first;
const char* p = allocated[i].second;
for (size_t b = 0; b < num_bytes; b++) {
ASSERT_EQ(int(p[b]) & 0xff, i % 256);
}
}
}
} |
472 | cpp | google/leveldb | coding | util/coding.cc | util/coding_test.cc | #ifndef STORAGE_LEVELDB_UTIL_CODING_H_
#define STORAGE_LEVELDB_UTIL_CODING_H_
#include <cstdint>
#include <cstring>
#include <string>
#include "leveldb/slice.h"
#include "port/port.h"
namespace leveldb {
void PutFixed32(std::string* dst, uint32_t value);
void PutFixed64(std::string* dst, uint64_t value);
void PutVarint32(std::string* dst, uint32_t value);
void PutVarint64(std::string* dst, uint64_t value);
void PutLengthPrefixedSlice(std::string* dst, const Slice& value);
bool GetVarint32(Slice* input, uint32_t* value);
bool GetVarint64(Slice* input, uint64_t* value);
bool GetLengthPrefixedSlice(Slice* input, Slice* result);
const char* GetVarint32Ptr(const char* p, const char* limit, uint32_t* v);
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* v);
int VarintLength(uint64_t v);
char* EncodeVarint32(char* dst, uint32_t value);
char* EncodeVarint64(char* dst, uint64_t value);
inline void EncodeFixed32(char* dst, uint32_t value) {
uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
buffer[0] = static_cast<uint8_t>(value);
buffer[1] = static_cast<uint8_t>(value >> 8);
buffer[2] = static_cast<uint8_t>(value >> 16);
buffer[3] = static_cast<uint8_t>(value >> 24);
}
inline void EncodeFixed64(char* dst, uint64_t value) {
uint8_t* const buffer = reinterpret_cast<uint8_t*>(dst);
buffer[0] = static_cast<uint8_t>(value);
buffer[1] = static_cast<uint8_t>(value >> 8);
buffer[2] = static_cast<uint8_t>(value >> 16);
buffer[3] = static_cast<uint8_t>(value >> 24);
buffer[4] = static_cast<uint8_t>(value >> 32);
buffer[5] = static_cast<uint8_t>(value >> 40);
buffer[6] = static_cast<uint8_t>(value >> 48);
buffer[7] = static_cast<uint8_t>(value >> 56);
}
inline uint32_t DecodeFixed32(const char* ptr) {
const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
return (static_cast<uint32_t>(buffer[0])) |
(static_cast<uint32_t>(buffer[1]) << 8) |
(static_cast<uint32_t>(buffer[2]) << 16) |
(static_cast<uint32_t>(buffer[3]) << 24);
}
inline uint64_t DecodeFixed64(const char* ptr) {
const uint8_t* const buffer = reinterpret_cast<const uint8_t*>(ptr);
return (static_cast<uint64_t>(buffer[0])) |
(static_cast<uint64_t>(buffer[1]) << 8) |
(static_cast<uint64_t>(buffer[2]) << 16) |
(static_cast<uint64_t>(buffer[3]) << 24) |
(static_cast<uint64_t>(buffer[4]) << 32) |
(static_cast<uint64_t>(buffer[5]) << 40) |
(static_cast<uint64_t>(buffer[6]) << 48) |
(static_cast<uint64_t>(buffer[7]) << 56);
}
const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32_t* value);
inline const char* GetVarint32Ptr(const char* p, const char* limit,
uint32_t* value) {
if (p < limit) {
uint32_t result = *(reinterpret_cast<const uint8_t*>(p));
if ((result & 128) == 0) {
*value = result;
return p + 1;
}
}
return GetVarint32PtrFallback(p, limit, value);
}
}
#endif
#include "util/coding.h"
namespace leveldb {
void PutFixed32(std::string* dst, uint32_t value) {
char buf[sizeof(value)];
EncodeFixed32(buf, value);
dst->append(buf, sizeof(buf));
}
void PutFixed64(std::string* dst, uint64_t value) {
char buf[sizeof(value)];
EncodeFixed64(buf, value);
dst->append(buf, sizeof(buf));
}
char* EncodeVarint32(char* dst, uint32_t v) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
static const int B = 128;
if (v < (1 << 7)) {
*(ptr++) = v;
} else if (v < (1 << 14)) {
*(ptr++) = v | B;
*(ptr++) = v >> 7;
} else if (v < (1 << 21)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = v >> 14;
} else if (v < (1 << 28)) {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = v >> 21;
} else {
*(ptr++) = v | B;
*(ptr++) = (v >> 7) | B;
*(ptr++) = (v >> 14) | B;
*(ptr++) = (v >> 21) | B;
*(ptr++) = v >> 28;
}
return reinterpret_cast<char*>(ptr);
}
void PutVarint32(std::string* dst, uint32_t v) {
char buf[5];
char* ptr = EncodeVarint32(buf, v);
dst->append(buf, ptr - buf);
}
char* EncodeVarint64(char* dst, uint64_t v) {
static const int B = 128;
uint8_t* ptr = reinterpret_cast<uint8_t*>(dst);
while (v >= B) {
*(ptr++) = v | B;
v >>= 7;
}
*(ptr++) = static_cast<uint8_t>(v);
return reinterpret_cast<char*>(ptr);
}
void PutVarint64(std::string* dst, uint64_t v) {
char buf[10];
char* ptr = EncodeVarint64(buf, v);
dst->append(buf, ptr - buf);
}
void PutLengthPrefixedSlice(std::string* dst, const Slice& value) {
PutVarint32(dst, value.size());
dst->append(value.data(), value.size());
}
int VarintLength(uint64_t v) {
int len = 1;
while (v >= 128) {
v >>= 7;
len++;
}
return len;
}
const char* GetVarint32PtrFallback(const char* p, const char* limit,
uint32_t* value) {
uint32_t result = 0;
for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) {
uint32_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
bool GetVarint32(Slice* input, uint32_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint32Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) {
uint64_t result = 0;
for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) {
uint64_t byte = *(reinterpret_cast<const uint8_t*>(p));
p++;
if (byte & 128) {
result |= ((byte & 127) << shift);
} else {
result |= (byte << shift);
*value = result;
return reinterpret_cast<const char*>(p);
}
}
return nullptr;
}
bool GetVarint64(Slice* input, uint64_t* value) {
const char* p = input->data();
const char* limit = p + input->size();
const char* q = GetVarint64Ptr(p, limit, value);
if (q == nullptr) {
return false;
} else {
*input = Slice(q, limit - q);
return true;
}
}
bool GetLengthPrefixedSlice(Slice* input, Slice* result) {
uint32_t len;
if (GetVarint32(input, &len) && input->size() >= len) {
*result = Slice(input->data(), len);
input->remove_prefix(len);
return true;
} else {
return false;
}
}
} | #include "util/coding.h"
#include <vector>
#include "gtest/gtest.h"
namespace leveldb {
TEST(Coding, Fixed32) {
std::string s;
for (uint32_t v = 0; v < 100000; v++) {
PutFixed32(&s, v);
}
const char* p = s.data();
for (uint32_t v = 0; v < 100000; v++) {
uint32_t actual = DecodeFixed32(p);
ASSERT_EQ(v, actual);
p += sizeof(uint32_t);
}
}
TEST(Coding, Fixed64) {
std::string s;
for (int power = 0; power <= 63; power++) {
uint64_t v = static_cast<uint64_t>(1) << power;
PutFixed64(&s, v - 1);
PutFixed64(&s, v + 0);
PutFixed64(&s, v + 1);
}
const char* p = s.data();
for (int power = 0; power <= 63; power++) {
uint64_t v = static_cast<uint64_t>(1) << power;
uint64_t actual;
actual = DecodeFixed64(p);
ASSERT_EQ(v - 1, actual);
p += sizeof(uint64_t);
actual = DecodeFixed64(p);
ASSERT_EQ(v + 0, actual);
p += sizeof(uint64_t);
actual = DecodeFixed64(p);
ASSERT_EQ(v + 1, actual);
p += sizeof(uint64_t);
}
}
TEST(Coding, EncodingOutput) {
std::string dst;
PutFixed32(&dst, 0x04030201);
ASSERT_EQ(4, dst.size());
ASSERT_EQ(0x01, static_cast<int>(dst[0]));
ASSERT_EQ(0x02, static_cast<int>(dst[1]));
ASSERT_EQ(0x03, static_cast<int>(dst[2]));
ASSERT_EQ(0x04, static_cast<int>(dst[3]));
dst.clear();
PutFixed64(&dst, 0x0807060504030201ull);
ASSERT_EQ(8, dst.size());
ASSERT_EQ(0x01, static_cast<int>(dst[0]));
ASSERT_EQ(0x02, static_cast<int>(dst[1]));
ASSERT_EQ(0x03, static_cast<int>(dst[2]));
ASSERT_EQ(0x04, static_cast<int>(dst[3]));
ASSERT_EQ(0x05, static_cast<int>(dst[4]));
ASSERT_EQ(0x06, static_cast<int>(dst[5]));
ASSERT_EQ(0x07, static_cast<int>(dst[6]));
ASSERT_EQ(0x08, static_cast<int>(dst[7]));
}
TEST(Coding, Varint32) {
std::string s;
for (uint32_t i = 0; i < (32 * 32); i++) {
uint32_t v = (i / 32) << (i % 32);
PutVarint32(&s, v);
}
const char* p = s.data();
const char* limit = p + s.size();
for (uint32_t i = 0; i < (32 * 32); i++) {
uint32_t expected = (i / 32) << (i % 32);
uint32_t actual;
const char* start = p;
p = GetVarint32Ptr(p, limit, &actual);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(expected, actual);
ASSERT_EQ(VarintLength(actual), p - start);
}
ASSERT_EQ(p, s.data() + s.size());
}
TEST(Coding, Varint64) {
std::vector<uint64_t> values;
values.push_back(0);
values.push_back(100);
values.push_back(~static_cast<uint64_t>(0));
values.push_back(~static_cast<uint64_t>(0) - 1);
for (uint32_t k = 0; k < 64; k++) {
const uint64_t power = 1ull << k;
values.push_back(power);
values.push_back(power - 1);
values.push_back(power + 1);
}
std::string s;
for (size_t i = 0; i < values.size(); i++) {
PutVarint64(&s, values[i]);
}
const char* p = s.data();
const char* limit = p + s.size();
for (size_t i = 0; i < values.size(); i++) {
ASSERT_TRUE(p < limit);
uint64_t actual;
const char* start = p;
p = GetVarint64Ptr(p, limit, &actual);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(values[i], actual);
ASSERT_EQ(VarintLength(actual), p - start);
}
ASSERT_EQ(p, limit);
}
TEST(Coding, Varint32Overflow) {
uint32_t result;
std::string input("\x81\x82\x83\x84\x85\x11");
ASSERT_TRUE(GetVarint32Ptr(input.data(), input.data() + input.size(),
&result) == nullptr);
}
TEST(Coding, Varint32Truncation) {
uint32_t large_value = (1u << 31) + 100;
std::string s;
PutVarint32(&s, large_value);
uint32_t result;
for (size_t len = 0; len < s.size() - 1; len++) {
ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + len, &result) == nullptr);
}
ASSERT_TRUE(GetVarint32Ptr(s.data(), s.data() + s.size(), &result) !=
nullptr);
ASSERT_EQ(large_value, result);
}
TEST(Coding, Varint64Overflow) {
uint64_t result;
std::string input("\x81\x82\x83\x84\x85\x81\x82\x83\x84\x85\x11");
ASSERT_TRUE(GetVarint64Ptr(input.data(), input.data() + input.size(),
&result) == nullptr);
}
TEST(Coding, Varint64Truncation) {
uint64_t large_value = (1ull << 63) + 100ull;
std::string s;
PutVarint64(&s, large_value);
uint64_t result;
for (size_t len = 0; len < s.size() - 1; len++) {
ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + len, &result) == nullptr);
}
ASSERT_TRUE(GetVarint64Ptr(s.data(), s.data() + s.size(), &result) !=
nullptr);
ASSERT_EQ(large_value, result);
}
TEST(Coding, Strings) {
std::string s;
PutLengthPrefixedSlice(&s, Slice(""));
PutLengthPrefixedSlice(&s, Slice("foo"));
PutLengthPrefixedSlice(&s, Slice("bar"));
PutLengthPrefixedSlice(&s, Slice(std::string(200, 'x')));
Slice input(s);
Slice v;
ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v));
ASSERT_EQ("", v.ToString());
ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v));
ASSERT_EQ("foo", v.ToString());
ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v));
ASSERT_EQ("bar", v.ToString());
ASSERT_TRUE(GetLengthPrefixedSlice(&input, &v));
ASSERT_EQ(std::string(200, 'x'), v.ToString());
ASSERT_EQ("", input.ToString());
}
} |
473 | cpp | google/leveldb | env | util/env.cc | util/env_test.cc | #ifndef STORAGE_LEVELDB_INCLUDE_ENV_H_
#define STORAGE_LEVELDB_INCLUDE_ENV_H_
#include <cstdarg>
#include <cstdint>
#include <string>
#include <vector>
#include "leveldb/export.h"
#include "leveldb/status.h"
#if defined(_WIN32)
#if defined(DeleteFile)
#undef DeleteFile
#define LEVELDB_DELETEFILE_UNDEFINED
#endif
#endif
namespace leveldb {
class FileLock;
class Logger;
class RandomAccessFile;
class SequentialFile;
class Slice;
class WritableFile;
class LEVELDB_EXPORT Env {
public:
Env();
Env(const Env&) = delete;
Env& operator=(const Env&) = delete;
virtual ~Env();
static Env* Default();
virtual Status NewSequentialFile(const std::string& fname,
SequentialFile** result) = 0;
virtual Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) = 0;
virtual Status NewWritableFile(const std::string& fname,
WritableFile** result) = 0;
virtual Status NewAppendableFile(const std::string& fname,
WritableFile** result);
virtual bool FileExists(const std::string& fname) = 0;
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result) = 0;
virtual Status RemoveFile(const std::string& fname);
virtual Status DeleteFile(const std::string& fname);
virtual Status CreateDir(const std::string& dirname) = 0;
virtual Status RemoveDir(const std::string& dirname);
virtual Status DeleteDir(const std::string& dirname);
virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) = 0;
virtual Status RenameFile(const std::string& src,
const std::string& target) = 0;
virtual Status LockFile(const std::string& fname, FileLock** lock) = 0;
virtual Status UnlockFile(FileLock* lock) = 0;
virtual void Schedule(void (*function)(void* arg), void* arg) = 0;
virtual void StartThread(void (*function)(void* arg), void* arg) = 0;
virtual Status GetTestDirectory(std::string* path) = 0;
virtual Status NewLogger(const std::string& fname, Logger** result) = 0;
virtual uint64_t NowMicros() = 0;
virtual void SleepForMicroseconds(int micros) = 0;
};
class LEVELDB_EXPORT SequentialFile {
public:
SequentialFile() = default;
SequentialFile(const SequentialFile&) = delete;
SequentialFile& operator=(const SequentialFile&) = delete;
virtual ~SequentialFile();
virtual Status Read(size_t n, Slice* result, char* scratch) = 0;
virtual Status Skip(uint64_t n) = 0;
};
class LEVELDB_EXPORT RandomAccessFile {
public:
RandomAccessFile() = default;
RandomAccessFile(const RandomAccessFile&) = delete;
RandomAccessFile& operator=(const RandomAccessFile&) = delete;
virtual ~RandomAccessFile();
virtual Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const = 0;
};
class LEVELDB_EXPORT WritableFile {
public:
WritableFile() = default;
WritableFile(const WritableFile&) = delete;
WritableFile& operator=(const WritableFile&) = delete;
virtual ~WritableFile();
virtual Status Append(const Slice& data) = 0;
virtual Status Close() = 0;
virtual Status Flush() = 0;
virtual Status Sync() = 0;
};
class LEVELDB_EXPORT Logger {
public:
Logger() = default;
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
virtual ~Logger();
virtual void Logv(const char* format, std::va_list ap) = 0;
};
class LEVELDB_EXPORT FileLock {
public:
FileLock() = default;
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
virtual ~FileLock();
};
void Log(Logger* info_log, const char* format, ...)
#if defined(__GNUC__) || defined(__clang__)
__attribute__((__format__(__printf__, 2, 3)))
#endif
;
LEVELDB_EXPORT Status WriteStringToFile(Env* env, const Slice& data,
const std::string& fname);
LEVELDB_EXPORT Status ReadFileToString(Env* env, const std::string& fname,
std::string* data);
class LEVELDB_EXPORT EnvWrapper : public Env {
public:
explicit EnvWrapper(Env* t) : target_(t) {}
virtual ~EnvWrapper();
Env* target() const { return target_; }
Status NewSequentialFile(const std::string& f, SequentialFile** r) override {
return target_->NewSequentialFile(f, r);
}
Status NewRandomAccessFile(const std::string& f,
RandomAccessFile** r) override {
return target_->NewRandomAccessFile(f, r);
}
Status NewWritableFile(const std::string& f, WritableFile** r) override {
return target_->NewWritableFile(f, r);
}
Status NewAppendableFile(const std::string& f, WritableFile** r) override {
return target_->NewAppendableFile(f, r);
}
bool FileExists(const std::string& f) override {
return target_->FileExists(f);
}
Status GetChildren(const std::string& dir,
std::vector<std::string>* r) override {
return target_->GetChildren(dir, r);
}
Status RemoveFile(const std::string& f) override {
return target_->RemoveFile(f);
}
Status CreateDir(const std::string& d) override {
return target_->CreateDir(d);
}
Status RemoveDir(const std::string& d) override {
return target_->RemoveDir(d);
}
Status GetFileSize(const std::string& f, uint64_t* s) override {
return target_->GetFileSize(f, s);
}
Status RenameFile(const std::string& s, const std::string& t) override {
return target_->RenameFile(s, t);
}
Status LockFile(const std::string& f, FileLock** l) override {
return target_->LockFile(f, l);
}
Status UnlockFile(FileLock* l) override { return target_->UnlockFile(l); }
void Schedule(void (*f)(void*), void* a) override {
return target_->Schedule(f, a);
}
void StartThread(void (*f)(void*), void* a) override {
return target_->StartThread(f, a);
}
Status GetTestDirectory(std::string* path) override {
return target_->GetTestDirectory(path);
}
Status NewLogger(const std::string& fname, Logger** result) override {
return target_->NewLogger(fname, result);
}
uint64_t NowMicros() override { return target_->NowMicros(); }
void SleepForMicroseconds(int micros) override {
target_->SleepForMicroseconds(micros);
}
private:
Env* target_;
};
}
#if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED)
#if defined(UNICODE)
#define DeleteFile DeleteFileW
#else
#define DeleteFile DeleteFileA
#endif
#endif
#endif
#include "leveldb/env.h"
#include <cstdarg>
#if defined(_WIN32) && defined(LEVELDB_DELETEFILE_UNDEFINED)
#undef DeleteFile
#endif
namespace leveldb {
Env::Env() = default;
Env::~Env() = default;
Status Env::NewAppendableFile(const std::string& fname, WritableFile** result) {
return Status::NotSupported("NewAppendableFile", fname);
}
Status Env::RemoveDir(const std::string& dirname) { return DeleteDir(dirname); }
Status Env::DeleteDir(const std::string& dirname) { return RemoveDir(dirname); }
Status Env::RemoveFile(const std::string& fname) { return DeleteFile(fname); }
Status Env::DeleteFile(const std::string& fname) { return RemoveFile(fname); }
SequentialFile::~SequentialFile() = default;
RandomAccessFile::~RandomAccessFile() = default;
WritableFile::~WritableFile() = default;
Logger::~Logger() = default;
FileLock::~FileLock() = default;
void Log(Logger* info_log, const char* format, ...) {
if (info_log != nullptr) {
std::va_list ap;
va_start(ap, format);
info_log->Logv(format, ap);
va_end(ap);
}
}
static Status DoWriteStringToFile(Env* env, const Slice& data,
const std::string& fname, bool should_sync) {
WritableFile* file;
Status s = env->NewWritableFile(fname, &file);
if (!s.ok()) {
return s;
}
s = file->Append(data);
if (s.ok() && should_sync) {
s = file->Sync();
}
if (s.ok()) {
s = file->Close();
}
delete file;
if (!s.ok()) {
env->RemoveFile(fname);
}
return s;
}
Status WriteStringToFile(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, false);
}
Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, true);
}
Status ReadFileToString(Env* env, const std::string& fname, std::string* data) {
data->clear();
SequentialFile* file;
Status s = env->NewSequentialFile(fname, &file);
if (!s.ok()) {
return s;
}
static const int kBufferSize = 8192;
char* space = new char[kBufferSize];
while (true) {
Slice fragment;
s = file->Read(kBufferSize, &fragment, space);
if (!s.ok()) {
break;
}
data->append(fragment.data(), fragment.size());
if (fragment.empty()) {
break;
}
}
delete[] space;
delete file;
return s;
}
EnvWrapper::~EnvWrapper() {}
} | #include "leveldb/env.h"
#include <algorithm>
#include "gtest/gtest.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/mutexlock.h"
#include "util/testutil.h"
namespace leveldb {
class EnvTest : public testing::Test {
public:
EnvTest() : env_(Env::Default()) {}
Env* env_;
};
TEST_F(EnvTest, ReadWrite) {
Random rnd(test::RandomSeed());
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/open_on_read.txt";
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
static const size_t kDataSize = 10 * 1048576;
std::string data;
while (data.size() < kDataSize) {
int len = rnd.Skewed(18);
std::string r;
test::RandomString(&rnd, len, &r);
ASSERT_LEVELDB_OK(writable_file->Append(r));
data += r;
if (rnd.OneIn(10)) {
ASSERT_LEVELDB_OK(writable_file->Flush());
}
}
ASSERT_LEVELDB_OK(writable_file->Sync());
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
SequentialFile* sequential_file;
ASSERT_LEVELDB_OK(env_->NewSequentialFile(test_file_name, &sequential_file));
std::string read_result;
std::string scratch;
while (read_result.size() < data.size()) {
int len = std::min<int>(rnd.Skewed(18), data.size() - read_result.size());
scratch.resize(std::max(len, 1));
Slice read;
ASSERT_LEVELDB_OK(sequential_file->Read(len, &read, &scratch[0]));
if (len > 0) {
ASSERT_GT(read.size(), 0);
}
ASSERT_LE(read.size(), len);
read_result.append(read.data(), read.size());
}
ASSERT_EQ(read_result, data);
delete sequential_file;
}
TEST_F(EnvTest, RunImmediately) {
struct RunState {
port::Mutex mu;
port::CondVar cvar{&mu};
bool called = false;
static void Run(void* arg) {
RunState* state = reinterpret_cast<RunState*>(arg);
MutexLock l(&state->mu);
ASSERT_EQ(state->called, false);
state->called = true;
state->cvar.Signal();
}
};
RunState state;
env_->Schedule(&RunState::Run, &state);
MutexLock l(&state.mu);
while (!state.called) {
state.cvar.Wait();
}
}
TEST_F(EnvTest, RunMany) {
struct RunState {
port::Mutex mu;
port::CondVar cvar{&mu};
int run_count = 0;
};
struct Callback {
RunState* const state_;
bool run = false;
Callback(RunState* s) : state_(s) {}
static void Run(void* arg) {
Callback* callback = reinterpret_cast<Callback*>(arg);
RunState* state = callback->state_;
MutexLock l(&state->mu);
state->run_count++;
callback->run = true;
state->cvar.Signal();
}
};
RunState state;
Callback callback1(&state);
Callback callback2(&state);
Callback callback3(&state);
Callback callback4(&state);
env_->Schedule(&Callback::Run, &callback1);
env_->Schedule(&Callback::Run, &callback2);
env_->Schedule(&Callback::Run, &callback3);
env_->Schedule(&Callback::Run, &callback4);
MutexLock l(&state.mu);
while (state.run_count != 4) {
state.cvar.Wait();
}
ASSERT_TRUE(callback1.run);
ASSERT_TRUE(callback2.run);
ASSERT_TRUE(callback3.run);
ASSERT_TRUE(callback4.run);
}
struct State {
port::Mutex mu;
port::CondVar cvar{&mu};
int val GUARDED_BY(mu);
int num_running GUARDED_BY(mu);
State(int val, int num_running) : val(val), num_running(num_running) {}
};
static void ThreadBody(void* arg) {
State* s = reinterpret_cast<State*>(arg);
s->mu.Lock();
s->val += 1;
s->num_running -= 1;
s->cvar.Signal();
s->mu.Unlock();
}
TEST_F(EnvTest, StartThread) {
State state(0, 3);
for (int i = 0; i < 3; i++) {
env_->StartThread(&ThreadBody, &state);
}
MutexLock l(&state.mu);
while (state.num_running != 0) {
state.cvar.Wait();
}
ASSERT_EQ(state.val, 3);
}
TEST_F(EnvTest, TestOpenNonExistentFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string non_existent_file = test_dir + "/non_existent_file";
ASSERT_TRUE(!env_->FileExists(non_existent_file));
RandomAccessFile* random_access_file;
Status status =
env_->NewRandomAccessFile(non_existent_file, &random_access_file);
#if defined(LEVELDB_PLATFORM_CHROMIUM)
ASSERT_TRUE(status.IsIOError());
#else
ASSERT_TRUE(status.IsNotFound());
#endif
SequentialFile* sequential_file;
status = env_->NewSequentialFile(non_existent_file, &sequential_file);
#if defined(LEVELDB_PLATFORM_CHROMIUM)
ASSERT_TRUE(status.IsIOError());
#else
ASSERT_TRUE(status.IsNotFound());
#endif
}
TEST_F(EnvTest, ReopenWritableFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/reopen_writable_file.txt";
env_->RemoveFile(test_file_name);
WritableFile* writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
std::string data("hello world!");
ASSERT_LEVELDB_OK(writable_file->Append(data));
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
ASSERT_LEVELDB_OK(env_->NewWritableFile(test_file_name, &writable_file));
data = "42";
ASSERT_LEVELDB_OK(writable_file->Append(data));
ASSERT_LEVELDB_OK(writable_file->Close());
delete writable_file;
ASSERT_LEVELDB_OK(ReadFileToString(env_, test_file_name, &data));
ASSERT_EQ(std::string("42"), data);
env_->RemoveFile(test_file_name);
}
TEST_F(EnvTest, ReopenAppendableFile) {
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file_name = test_dir + "/reopen_appendable_file.txt";
env_->RemoveFile(test_file_name);
WritableFile* appendable_file;
ASSERT_LEVELDB_OK(env_->NewAppendableFile(test_file_name, &appendable_file));
std::string data("hello world!");
ASSERT_LEVELDB_OK(appendable_file->Append(data));
ASSERT_LEVELDB_OK(appendable_file->Close());
delete appendable_file;
ASSERT_LEVELDB_OK(env_->NewAppendableFile(test_file_name, &appendable_file));
data = "42";
ASSERT_LEVELDB_OK(appendable_file->Append(data));
ASSERT_LEVELDB_OK(appendable_file->Close());
delete appendable_file;
ASSERT_LEVELDB_OK(ReadFileToString(env_, test_file_name, &data));
ASSERT_EQ(std::string("hello world!42"), data);
env_->RemoveFile(test_file_name);
}
} |
474 | cpp | google/leveldb | crc32c | util/crc32c.cc | util/crc32c_test.cc | #ifndef STORAGE_LEVELDB_UTIL_CRC32C_H_
#define STORAGE_LEVELDB_UTIL_CRC32C_H_
#include <cstddef>
#include <cstdint>
namespace leveldb {
namespace crc32c {
uint32_t Extend(uint32_t init_crc, const char* data, size_t n);
inline uint32_t Value(const char* data, size_t n) { return Extend(0, data, n); }
static const uint32_t kMaskDelta = 0xa282ead8ul;
inline uint32_t Mask(uint32_t crc) {
return ((crc >> 15) | (crc << 17)) + kMaskDelta;
}
inline uint32_t Unmask(uint32_t masked_crc) {
uint32_t rot = masked_crc - kMaskDelta;
return ((rot >> 17) | (rot << 15));
}
}
}
#endif
#include "util/crc32c.h"
#include <cstddef>
#include <cstdint>
#include "port/port.h"
#include "util/coding.h"
namespace leveldb {
namespace crc32c {
namespace {
const uint32_t kByteExtensionTable[256] = {
0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c,
0x26a1e7e8, 0xd4ca64eb, 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b,
0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, 0x105ec76f, 0xe235446c,
0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384,
0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc,
0xbc267848, 0x4e4dfb4b, 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a,
0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, 0xaa64d611, 0x580f5512,
0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa,
0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad,
0x1642ae59, 0xe4292d5a, 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a,
0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, 0x417b1dbc, 0xb3109ebf,
0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957,
0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f,
0xed03a29b, 0x1f682198, 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927,
0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, 0xdbfc821c, 0x2997011f,
0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7,
0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e,
0x4767748a, 0xb50cf789, 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859,
0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, 0x7198540d, 0x83f3d70e,
0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6,
0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de,
0xdde0eb2a, 0x2f8b6829, 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c,
0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, 0x082f63b7, 0xfa44e0b4,
0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c,
0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b,
0xb4091bff, 0x466298fc, 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c,
0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, 0xa24bb5a6, 0x502036a5,
0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d,
0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975,
0x0e330a81, 0xfc588982, 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d,
0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, 0x38cc2a06, 0xcaa7a905,
0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed,
0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8,
0xe52cc12c, 0x1747422f, 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff,
0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, 0xd3d3e1ab, 0x21b862a8,
0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540,
0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78,
0x7fab5e8c, 0x8dc0dd8f, 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee,
0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, 0x69e9f0d5, 0x9b8273d6,
0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e,
0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69,
0xd5cf889d, 0x27a40b9e, 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e,
0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351};
const uint32_t kStrideExtensionTable0[256] = {
0x00000000, 0x30d23865, 0x61a470ca, 0x517648af, 0xc348e194, 0xf39ad9f1,
0xa2ec915e, 0x923ea93b, 0x837db5d9, 0xb3af8dbc, 0xe2d9c513, 0xd20bfd76,
0x4035544d, 0x70e76c28, 0x21912487, 0x11431ce2, 0x03171d43, 0x33c52526,
0x62b36d89, 0x526155ec, 0xc05ffcd7, 0xf08dc4b2, 0xa1fb8c1d, 0x9129b478,
0x806aa89a, 0xb0b890ff, 0xe1ced850, 0xd11ce035, 0x4322490e, 0x73f0716b,
0x228639c4, 0x125401a1, 0x062e3a86, 0x36fc02e3, 0x678a4a4c, 0x57587229,
0xc566db12, 0xf5b4e377, 0xa4c2abd8, 0x941093bd, 0x85538f5f, 0xb581b73a,
0xe4f7ff95, 0xd425c7f0, 0x461b6ecb, 0x76c956ae, 0x27bf1e01, 0x176d2664,
0x053927c5, 0x35eb1fa0, 0x649d570f, 0x544f6f6a, 0xc671c651, 0xf6a3fe34,
0xa7d5b69b, 0x97078efe, 0x8644921c, 0xb696aa79, 0xe7e0e2d6, 0xd732dab3,
0x450c7388, 0x75de4bed, 0x24a80342, 0x147a3b27, 0x0c5c750c, 0x3c8e4d69,
0x6df805c6, 0x5d2a3da3, 0xcf149498, 0xffc6acfd, 0xaeb0e452, 0x9e62dc37,
0x8f21c0d5, 0xbff3f8b0, 0xee85b01f, 0xde57887a, 0x4c692141, 0x7cbb1924,
0x2dcd518b, 0x1d1f69ee, 0x0f4b684f, 0x3f99502a, 0x6eef1885, 0x5e3d20e0,
0xcc0389db, 0xfcd1b1be, 0xada7f911, 0x9d75c174, 0x8c36dd96, 0xbce4e5f3,
0xed92ad5c, 0xdd409539, 0x4f7e3c02, 0x7fac0467, 0x2eda4cc8, 0x1e0874ad,
0x0a724f8a, 0x3aa077ef, 0x6bd63f40, 0x5b040725, 0xc93aae1e, 0xf9e8967b,
0xa89eded4, 0x984ce6b1, 0x890ffa53, 0xb9ddc236, 0xe8ab8a99, 0xd879b2fc,
0x4a471bc7, 0x7a9523a2, 0x2be36b0d, 0x1b315368, 0x096552c9, 0x39b76aac,
0x68c12203, 0x58131a66, 0xca2db35d, 0xfaff8b38, 0xab89c397, 0x9b5bfbf2,
0x8a18e710, 0xbacadf75, 0xebbc97da, 0xdb6eafbf, 0x49500684, 0x79823ee1,
0x28f4764e, 0x18264e2b, 0x18b8ea18, 0x286ad27d, 0x791c9ad2, 0x49cea2b7,
0xdbf00b8c, 0xeb2233e9, 0xba547b46, 0x8a864323, 0x9bc55fc1, 0xab1767a4,
0xfa612f0b, 0xcab3176e, 0x588dbe55, 0x685f8630, 0x3929ce9f, 0x09fbf6fa,
0x1baff75b, 0x2b7dcf3e, 0x7a0b8791, 0x4ad9bff4, 0xd8e716cf, 0xe8352eaa,
0xb9436605, 0x89915e60, 0x98d24282, 0xa8007ae7, 0xf9763248, 0xc9a40a2d,
0x5b9aa316, 0x6b489b73, 0x3a3ed3dc, 0x0aecebb9, 0x1e96d09e, 0x2e44e8fb,
0x7f32a054, 0x4fe09831, 0xddde310a, 0xed0c096f, 0xbc7a41c0, 0x8ca879a5,
0x9deb6547, 0xad395d22, 0xfc4f158d, 0xcc9d2de8, 0x5ea384d3, 0x6e71bcb6,
0x3f07f419, 0x0fd5cc7c, 0x1d81cddd, 0x2d53f5b8, 0x7c25bd17, 0x4cf78572,
0xdec92c49, 0xee1b142c, 0xbf6d5c83, 0x8fbf64e6, 0x9efc7804, 0xae2e4061,
0xff5808ce, 0xcf8a30ab, 0x5db49990, 0x6d66a1f5, 0x3c10e95a, 0x0cc2d13f,
0x14e49f14, 0x2436a771, 0x7540efde, 0x4592d7bb, 0xd7ac7e80, 0xe77e46e5,
0xb6080e4a, 0x86da362f, 0x97992acd, 0xa74b12a8, 0xf63d5a07, 0xc6ef6262,
0x54d1cb59, 0x6403f33c, 0x3575bb93, 0x05a783f6, 0x17f38257, 0x2721ba32,
0x7657f29d, 0x4685caf8, 0xd4bb63c3, 0xe4695ba6, 0xb51f1309, 0x85cd2b6c,
0x948e378e, 0xa45c0feb, 0xf52a4744, 0xc5f87f21, 0x57c6d61a, 0x6714ee7f,
0x3662a6d0, 0x06b09eb5, 0x12caa592, 0x22189df7, 0x736ed558, 0x43bced3d,
0xd1824406, 0xe1507c63, 0xb02634cc, 0x80f40ca9, 0x91b7104b, 0xa165282e,
0xf0136081, 0xc0c158e4, 0x52fff1df, 0x622dc9ba, 0x335b8115, 0x0389b970,
0x11ddb8d1, 0x210f80b4, 0x7079c81b, 0x40abf07e, 0xd2955945, 0xe2476120,
0xb331298f, 0x83e311ea, 0x92a00d08, 0xa272356d, 0xf3047dc2, 0xc3d645a7,
0x51e8ec9c, 0x613ad4f9, 0x304c9c56, 0x009ea433};
const uint32_t kStrideExtensionTable1[256] = {
0x00000000, 0x54075546, 0xa80eaa8c, 0xfc09ffca, 0x55f123e9, 0x01f676af,
0xfdff8965, 0xa9f8dc23, 0xabe247d2, 0xffe51294, 0x03eced5e, 0x57ebb818,
0xfe13643b, 0xaa14317d, 0x561dceb7, 0x021a9bf1, 0x5228f955, 0x062fac13,
0xfa2653d9, 0xae21069f, 0x07d9dabc, 0x53de8ffa, 0xafd77030, 0xfbd02576,
0xf9cabe87, 0xadcdebc1, 0x51c4140b, 0x05c3414d, 0xac3b9d6e, 0xf83cc828,
0x043537e2, 0x503262a4, 0xa451f2aa, 0xf056a7ec, 0x0c5f5826, 0x58580d60,
0xf1a0d143, 0xa5a78405, 0x59ae7bcf, 0x0da92e89, 0x0fb3b578, 0x5bb4e03e,
0xa7bd1ff4, 0xf3ba4ab2, 0x5a429691, 0x0e45c3d7, 0xf24c3c1d, 0xa64b695b,
0xf6790bff, 0xa27e5eb9, 0x5e77a173, 0x0a70f435, 0xa3882816, 0xf78f7d50,
0x0b86829a, 0x5f81d7dc, 0x5d9b4c2d, 0x099c196b, 0xf595e6a1, 0xa192b3e7,
0x086a6fc4, 0x5c6d3a82, 0xa064c548, 0xf463900e, 0x4d4f93a5, 0x1948c6e3,
0xe5413929, 0xb1466c6f, 0x18beb04c, 0x4cb9e50a, 0xb0b01ac0, 0xe4b74f86,
0xe6add477, 0xb2aa8131, 0x4ea37efb, 0x1aa42bbd, 0xb35cf79e, 0xe75ba2d8,
0x1b525d12, 0x4f550854, 0x1f676af0, 0x4b603fb6, 0xb769c07c, 0xe36e953a,
0x4a964919, 0x1e911c5f, 0xe298e395, 0xb69fb6d3, 0xb4852d22, 0xe0827864,
0x1c8b87ae, 0x488cd2e8, 0xe1740ecb, 0xb5735b8d, 0x497aa447, 0x1d7df101,
0xe91e610f, 0xbd193449, 0x4110cb83, 0x15179ec5, 0xbcef42e6, 0xe8e817a0,
0x14e1e86a, 0x40e6bd2c, 0x42fc26dd, 0x16fb739b, 0xeaf28c51, 0xbef5d917,
0x170d0534, 0x430a5072, 0xbf03afb8, 0xeb04fafe, 0xbb36985a, 0xef31cd1c,
0x133832d6, 0x473f6790, 0xeec7bbb3, 0xbac0eef5, 0x46c9113f, 0x12ce4479,
0x10d4df88, 0x44d38ace, 0xb8da7504, 0xecdd2042, 0x4525fc61, 0x1122a927,
0xed2b56ed, 0xb92c03ab, 0x9a9f274a, 0xce98720c, 0x32918dc6, 0x6696d880,
0xcf6e04a3, 0x9b6951e5, 0x6760ae2f, 0x3367fb69, 0x317d6098, 0x657a35de,
0x9973ca14, 0xcd749f52, 0x648c4371, 0x308b1637, 0xcc82e9fd, 0x9885bcbb,
0xc8b7de1f, 0x9cb08b59, 0x60b97493, 0x34be21d5, 0x9d46fdf6, 0xc941a8b0,
0x3548577a, 0x614f023c, 0x635599cd, 0x3752cc8b, 0xcb5b3341, 0x9f5c6607,
0x36a4ba24, 0x62a3ef62, 0x9eaa10a8, 0xcaad45ee, 0x3eced5e0, 0x6ac980a6,
0x96c07f6c, 0xc2c72a2a, 0x6b3ff609, 0x3f38a34f, 0xc3315c85, 0x973609c3,
0x952c9232, 0xc12bc774, 0x3d2238be, 0x69256df8, 0xc0ddb1db, 0x94dae49d,
0x68d31b57, 0x3cd44e11, 0x6ce62cb5, 0x38e179f3, 0xc4e88639, 0x90efd37f,
0x39170f5c, 0x6d105a1a, 0x9119a5d0, 0xc51ef096, 0xc7046b67, 0x93033e21,
0x6f0ac1eb, 0x3b0d94ad, 0x92f5488e, 0xc6f21dc8, 0x3afbe202, 0x6efcb744,
0xd7d0b4ef, 0x83d7e1a9, 0x7fde1e63, 0x2bd94b25, 0x82219706, 0xd626c240,
0x2a2f3d8a, 0x7e2868cc, 0x7c32f33d, 0x2835a67b, 0xd43c59b1, 0x803b0cf7,
0x29c3d0d4, 0x7dc48592, 0x81cd7a58, 0xd5ca2f1e, 0x85f84dba, 0xd1ff18fc,
0x2df6e736, 0x79f1b270, 0xd0096e53, 0x840e3b15, 0x7807c4df, 0x2c009199,
0x2e1a0a68, 0x7a1d5f2e, 0x8614a0e4, 0xd213f5a2, 0x7beb2981, 0x2fec7cc7,
0xd3e5830d, 0x87e2d64b, 0x73814645, 0x27861303, 0xdb8fecc9, 0x8f88b98f,
0x267065ac, 0x727730ea, 0x8e7ecf20, 0xda799a66, 0xd8630197, 0x8c6454d1,
0x706dab1b, 0x246afe5d, 0x8d92227e, 0xd9957738, 0x259c88f2, 0x719bddb4,
0x21a9bf10, 0x75aeea56, 0x89a7159c, 0xdda040da, 0x74589cf9, 0x205fc9bf,
0xdc563675, 0x88516333, 0x8a4bf8c2, 0xde4cad84, 0x2245524e, 0x76420708,
0xdfbadb2b, 0x8bbd8e6d, 0x77b471a7, 0x23b324e1};
const uint32_t kStrideExtensionTable2[256] = {
0x00000000, 0x678efd01, 0xcf1dfa02, 0xa8930703, 0x9bd782f5, 0xfc597ff4,
0x54ca78f7, 0x334485f6, 0x3243731b, 0x55cd8e1a, 0xfd5e8919, 0x9ad07418,
0xa994f1ee, 0xce1a0cef, 0x66890bec, 0x0107f6ed, 0x6486e636, 0x03081b37,
0xab9b1c34, 0xcc15e135, 0xff5164c3, 0x98df99c2, 0x304c9ec1, 0x57c263c0,
0x56c5952d, 0x314b682c, 0x99d86f2f, 0xfe56922e, 0xcd1217d8, 0xaa9cead9,
0x020fedda, 0x658110db, 0xc90dcc6c, 0xae83316d, 0x0610366e, 0x619ecb6f,
0x52da4e99, 0x3554b398, 0x9dc7b49b, 0xfa49499a, 0xfb4ebf77, 0x9cc04276,
0x34534575, 0x53ddb874, 0x60993d82, 0x0717c083, 0xaf84c780, 0xc80a3a81,
0xad8b2a5a, 0xca05d75b, 0x6296d058, 0x05182d59, 0x365ca8af, 0x51d255ae,
0xf94152ad, 0x9ecfafac, 0x9fc85941, 0xf846a440, 0x50d5a343, 0x375b5e42,
0x041fdbb4, 0x639126b5, 0xcb0221b6, 0xac8cdcb7, 0x97f7ee29, 0xf0791328,
0x58ea142b, 0x3f64e92a, 0x0c206cdc, 0x6bae91dd, 0xc33d96de, 0xa4b36bdf,
0xa5b49d32, 0xc23a6033, 0x6aa96730, 0x0d279a31, 0x3e631fc7, 0x59ede2c6,
0xf17ee5c5, 0x96f018c4, 0xf371081f, 0x94fff51e, 0x3c6cf21d, 0x5be20f1c,
0x68a68aea, 0x0f2877eb, 0xa7bb70e8, 0xc0358de9, 0xc1327b04, 0xa6bc8605,
0x0e2f8106, 0x69a17c07, 0x5ae5f9f1, 0x3d6b04f0, 0x95f803f3, 0xf276fef2,
0x5efa2245, 0x3974df44, 0x91e7d847, 0xf6692546, 0xc52da0b0, 0xa2a35db1,
0x0a305ab2, 0x6dbea7b3, 0x6cb9515e, 0x0b37ac5f, 0xa3a4ab5c, 0xc42a565d,
0xf76ed3ab, 0x90e02eaa, 0x387329a9, 0x5ffdd4a8, 0x3a7cc473, 0x5df23972,
0xf5613e71, 0x92efc370, 0xa1ab4686, 0xc625bb87, 0x6eb6bc84, 0x09384185,
0x083fb768, 0x6fb14a69, 0xc7224d6a, 0xa0acb06b, 0x93e8359d, 0xf466c89c,
0x5cf5cf9f, 0x3b7b329e, 0x2a03aaa3, 0x4d8d57a2, 0xe51e50a1, 0x8290ada0,
0xb1d42856, 0xd65ad557, 0x7ec9d254, 0x19472f55, 0x1840d9b8, 0x7fce24b9,
0xd75d23ba, 0xb0d3debb, 0x83975b4d, 0xe419a64c, 0x4c8aa14f, 0x2b045c4e,
0x4e854c95, 0x290bb194, 0x8198b697, 0xe6164b96, 0xd552ce60, 0xb2dc3361,
0x1a4f3462, 0x7dc1c963, 0x7cc63f8e, 0x1b48c28f, 0xb3dbc58c, 0xd455388d,
0xe711bd7b, 0x809f407a, 0x280c4779, 0x4f82ba78, 0xe30e66cf, 0x84809bce,
0x2c139ccd, 0x4b9d61cc, 0x78d9e43a, 0x1f57193b, 0xb7c41e38, 0xd04ae339,
0xd14d15d4, 0xb6c3e8d5, 0x1e50efd6, 0x79de12d7, 0x4a9a9721, 0x2d146a20,
0x85876d23, 0xe2099022, 0x878880f9, 0xe0067df8, 0x48957afb, 0x2f1b87fa,
0x1c5f020c, 0x7bd1ff0d, 0xd342f80e, 0xb4cc050f, 0xb5cbf3e2, 0xd2450ee3,
0x7ad609e0, 0x1d58f4e1, 0x2e1c7117, 0x49928c16, 0xe1018b15, 0x868f7614,
0xbdf4448a, 0xda7ab98b, 0x72e9be88, 0x15674389, 0x2623c67f, 0x41ad3b7e,
0xe93e3c7d, 0x8eb0c17c, 0x8fb73791, 0xe839ca90, 0x40aacd93, 0x27243092,
0x1460b564, 0x73ee4865, 0xdb7d4f66, 0xbcf3b267, 0xd972a2bc, 0xbefc5fbd,
0x166f58be, 0x71e1a5bf, 0x42a52049, 0x252bdd48, 0x8db8da4b, 0xea36274a,
0xeb31d1a7, 0x8cbf2ca6, 0x242c2ba5, 0x43a2d6a4, 0x70e65352, 0x1768ae53,
0xbffba950, 0xd8755451, 0x74f988e6, 0x137775e7, 0xbbe472e4, 0xdc6a8fe5,
0xef2e0a13, 0x88a0f712, 0x2033f011, 0x47bd0d10, 0x46bafbfd, 0x213406fc,
0x89a701ff, 0xee29fcfe, 0xdd6d7908, 0xbae38409, 0x1270830a, 0x75fe7e0b,
0x107f6ed0, 0x77f193d1, 0xdf6294d2, 0xb8ec69d3, 0x8ba8ec25, 0xec261124,
0x44b51627, 0x233beb26, 0x223c1dcb, 0x45b2e0ca, 0xed21e7c9, 0x8aaf1ac8,
0xb9eb9f3e, 0xde65623f, 0x76f6653c, 0x1178983d};
const uint32_t kStrideExtensionTable3[256] = {
0x00000000, 0xf20c0dfe, 0xe1f46d0d, 0x13f860f3, 0xc604aceb, 0x3408a115,
0x27f0c1e6, 0xd5fccc18, 0x89e52f27, 0x7be922d9, 0x6811422a, 0x9a1d4fd4,
0x4fe183cc, 0xbded8e32, 0xae15eec1, 0x5c19e33f, 0x162628bf, 0xe42a2541,
0xf7d245b2, 0x05de484c, 0xd0228454, 0x222e89aa, 0x31d6e959, 0xc3dae4a7,
0x9fc30798, 0x6dcf0a66, 0x7e376a95, 0x8c3b676b, 0x59c7ab73, 0xabcba68d,
0xb833c67e, 0x4a3fcb80, 0x2c4c517e, 0xde405c80, 0xcdb83c73, 0x3fb4318d,
0xea48fd95, 0x1844f06b, 0x0bbc9098, 0xf9b09d66, 0xa5a97e59, 0x57a573a7,
0x445d1354, 0xb6511eaa, 0x63add2b2, 0x91a1df4c, 0x8259bfbf, 0x7055b241,
0x3a6a79c1, 0xc866743f, 0xdb9e14cc, 0x29921932, 0xfc6ed52a, 0x0e62d8d4,
0x1d9ab827, 0xef96b5d9, 0xb38f56e6, 0x41835b18, 0x527b3beb, 0xa0773615,
0x758bfa0d, 0x8787f7f3, 0x947f9700, 0x66739afe, 0x5898a2fc, 0xaa94af02,
0xb96ccff1, 0x4b60c20f, 0x9e9c0e17, 0x6c9003e9, 0x7f68631a, 0x8d646ee4,
0xd17d8ddb, 0x23718025, 0x3089e0d6, 0xc285ed28, 0x17792130, 0xe5752cce,
0xf68d4c3d, 0x048141c3, 0x4ebe8a43, 0xbcb287bd, 0xaf4ae74e, 0x5d46eab0,
0x88ba26a8, 0x7ab62b56, 0x694e4ba5, 0x9b42465b, 0xc75ba564, 0x3557a89a,
0x26afc869, 0xd4a3c597, 0x015f098f, 0xf3530471, 0xe0ab6482, 0x12a7697c,
0x74d4f382, 0x86d8fe7c, 0x95209e8f, 0x672c9371, 0xb2d05f69, 0x40dc5297,
0x53243264, 0xa1283f9a, 0xfd31dca5, 0x0f3dd15b, 0x1cc5b1a8, 0xeec9bc56,
0x3b35704e, 0xc9397db0, 0xdac11d43, 0x28cd10bd, 0x62f2db3d, 0x90fed6c3,
0x8306b630, 0x710abbce, 0xa4f677d6, 0x56fa7a28, 0x45021adb, 0xb70e1725,
0xeb17f41a, 0x191bf9e4, 0x0ae39917, 0xf8ef94e9, 0x2d1358f1, 0xdf1f550f,
0xcce735fc, 0x3eeb3802, 0xb13145f8, 0x433d4806, 0x50c528f5, 0xa2c9250b,
0x7735e913, 0x8539e4ed, 0x96c1841e, 0x64cd89e0, 0x38d46adf, 0xcad86721,
0xd92007d2, 0x2b2c0a2c, 0xfed0c634, 0x0cdccbca, 0x1f24ab39, 0xed28a6c7,
0xa7176d47, 0x551b60b9, 0x46e3004a, 0xb4ef0db4, 0x6113c1ac, 0x931fcc52,
0x80e7aca1, 0x72eba15f, 0x2ef24260, 0xdcfe4f9e, 0xcf062f6d, 0x3d0a2293,
0xe8f6ee8b, 0x1afae375, 0x09028386, 0xfb0e8e78, 0x9d7d1486, 0x6f711978,
0x7c89798b, 0x8e857475, 0x5b79b86d, 0xa975b593, 0xba8dd560, 0x4881d89e,
0x14983ba1, 0xe694365f, 0xf56c56ac, 0x07605b52, 0xd29c974a, 0x20909ab4,
0x3368fa47, 0xc164f7b9, 0x8b5b3c39, 0x795731c7, 0x6aaf5134, 0x98a35cca,
0x4d5f90d2, 0xbf539d2c, 0xacabfddf, 0x5ea7f021, 0x02be131e, 0xf0b21ee0,
0xe34a7e13, 0x114673ed, 0xc4babff5, 0x36b6b20b, 0x254ed2f8, 0xd742df06,
0xe9a9e704, 0x1ba5eafa, 0x085d8a09, 0xfa5187f7, 0x2fad4bef, 0xdda14611,
0xce5926e2, 0x3c552b1c, 0x604cc823, 0x9240c5dd, 0x81b8a52e, 0x73b4a8d0,
0xa64864c8, 0x54446936, 0x47bc09c5, 0xb5b0043b, 0xff8fcfbb, 0x0d83c245,
0x1e7ba2b6, 0xec77af48, 0x398b6350, 0xcb876eae, 0xd87f0e5d, 0x2a7303a3,
0x766ae09c, 0x8466ed62, 0x979e8d91, 0x6592806f, 0xb06e4c77, 0x42624189,
0x519a217a, 0xa3962c84, 0xc5e5b67a, 0x37e9bb84, 0x2411db77, 0xd61dd689,
0x03e11a91, 0xf1ed176f, 0xe215779c, 0x10197a62, 0x4c00995d, 0xbe0c94a3,
0xadf4f450, 0x5ff8f9ae, 0x8a0435b6, 0x78083848, 0x6bf058bb, 0x99fc5545,
0xd3c39ec5, 0x21cf933b, 0x3237f3c8, 0xc03bfe36, 0x15c7322e, 0xe7cb3fd0,
0xf4335f23, 0x063f52dd, 0x5a26b1e2, 0xa82abc1c, 0xbbd2dcef, 0x49ded111,
0x9c221d09, 0x6e2e10f7, 0x7dd67004, 0x8fda7dfa};
static constexpr const uint32_t kCRC32Xor = static_cast<uint32_t>(0xffffffffU);
inline uint32_t ReadUint32LE(const uint8_t* buffer) {
return DecodeFixed32(reinterpret_cast<const char*>(buffer));
}
template <int N>
constexpr inline const uint8_t* RoundUp(const uint8_t* pointer) {
return reinterpret_cast<uint8_t*>(
(reinterpret_cast<uintptr_t>(pointer) + (N - 1)) &
~static_cast<uintptr_t>(N - 1));
}
}
static bool CanAccelerateCRC32C() {
static const char kTestCRCBuffer[] = "TestCRCBuffer";
static const char kBufSize = sizeof(kTestCRCBuffer) - 1;
static const uint32_t kTestCRCValue = 0xdcbc59fa;
return port::AcceleratedCRC32C(0, kTestCRCBuffer, kBufSize) == kTestCRCValue;
}
uint32_t Extend(uint32_t crc, const char* data, size_t n) {
static bool accelerate = CanAccelerateCRC32C();
if (accelerate) {
return port::AcceleratedCRC32C(crc, data, n);
}
const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
const uint8_t* e = p + n;
uint32_t l = crc ^ kCRC32Xor;
#define STEP1 \
do { \
int c = (l & 0xff) ^ *p++; \
l = kByteExtensionTable[c] ^ (l >> 8); \
} while (0)
#define STEP4(s) \
do { \
crc##s = ReadUint32LE(p + s * 4) ^ kStrideExtensionTable3[crc##s & 0xff] ^ \
kStrideExtensionTable2[(crc##s >> 8) & 0xff] ^ \
kStrideExtensionTable1[(crc##s >> 16) & 0xff] ^ \
kStrideExtensionTable0[crc##s >> 24]; \
} while (0)
#define STEP16 \
do { \
STEP4(0); \
STEP4(1); \
STEP4(2); \
STEP4(3); \
p += 16; \
} while (0)
#define STEP4W(w) \
do { \
w ^= l; \
for (size_t i = 0; i < 4; ++i) { \
w = (w >> 8) ^ kByteExtensionTable[w & 0xff]; \
} \
l = w; \
} while (0)
const uint8_t* x = RoundUp<4>(p);
if (x <= e) {
while (p != x) {
STEP1;
}
}
if ((e - p) >= 16) {
uint32_t crc0 = ReadUint32LE(p + 0 * 4) ^ l;
uint32_t crc1 = ReadUint32LE(p + 1 * 4);
uint32_t crc2 = ReadUint32LE(p + 2 * 4);
uint32_t crc3 = ReadUint32LE(p + 3 * 4);
p += 16;
while ((e - p) >= 16) {
STEP16;
}
while ((e - p) >= 4) {
STEP4(0);
uint32_t tmp = crc0;
crc0 = crc1;
crc1 = crc2;
crc2 = crc3;
crc3 = tmp;
p += 4;
}
l = 0;
STEP4W(crc0);
STEP4W(crc1);
STEP4W(crc2);
STEP4W(crc3);
}
while (p != e) {
STEP1;
}
#undef STEP4W
#undef STEP16
#undef STEP4
#undef STEP1
return l ^ kCRC32Xor;
}
}
} | #include "util/crc32c.h"
#include "gtest/gtest.h"
namespace leveldb {
namespace crc32c {
TEST(CRC, StandardResults) {
char buf[32];
memset(buf, 0, sizeof(buf));
ASSERT_EQ(0x8a9136aa, Value(buf, sizeof(buf)));
memset(buf, 0xff, sizeof(buf));
ASSERT_EQ(0x62a8ab43, Value(buf, sizeof(buf)));
for (int i = 0; i < 32; i++) {
buf[i] = i;
}
ASSERT_EQ(0x46dd794e, Value(buf, sizeof(buf)));
for (int i = 0; i < 32; i++) {
buf[i] = 31 - i;
}
ASSERT_EQ(0x113fdb5c, Value(buf, sizeof(buf)));
uint8_t data[48] = {
0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
ASSERT_EQ(0xd9963a56, Value(reinterpret_cast<char*>(data), sizeof(data)));
}
TEST(CRC, Values) { ASSERT_NE(Value("a", 1), Value("foo", 3)); }
TEST(CRC, Extend) {
ASSERT_EQ(Value("hello world", 11), Extend(Value("hello ", 6), "world", 5));
}
TEST(CRC, Mask) {
uint32_t crc = Value("foo", 3);
ASSERT_NE(crc, Mask(crc));
ASSERT_NE(crc, Mask(Mask(crc)));
ASSERT_EQ(crc, Unmask(Mask(crc)));
ASSERT_EQ(crc, Unmask(Unmask(Mask(Mask(crc)))));
}
}
} |
475 | cpp | google/leveldb | hash | util/hash.cc | util/hash_test.cc | #ifndef STORAGE_LEVELDB_UTIL_HASH_H_
#define STORAGE_LEVELDB_UTIL_HASH_H_
#include <cstddef>
#include <cstdint>
namespace leveldb {
uint32_t Hash(const char* data, size_t n, uint32_t seed);
}
#endif
#include "util/hash.h"
#include <cstring>
#include "util/coding.h"
#ifndef FALLTHROUGH_INTENDED
#define FALLTHROUGH_INTENDED \
do { \
} while (0)
#endif
namespace leveldb {
uint32_t Hash(const char* data, size_t n, uint32_t seed) {
const uint32_t m = 0xc6a4a793;
const uint32_t r = 24;
const char* limit = data + n;
uint32_t h = seed ^ (n * m);
while (data + 4 <= limit) {
uint32_t w = DecodeFixed32(data);
data += 4;
h += w;
h *= m;
h ^= (h >> 16);
}
switch (limit - data) {
case 3:
h += static_cast<uint8_t>(data[2]) << 16;
FALLTHROUGH_INTENDED;
case 2:
h += static_cast<uint8_t>(data[1]) << 8;
FALLTHROUGH_INTENDED;
case 1:
h += static_cast<uint8_t>(data[0]);
h *= m;
h ^= (h >> r);
break;
}
return h;
}
} | #include "util/hash.h"
#include "gtest/gtest.h"
namespace leveldb {
TEST(HASH, SignedUnsignedIssue) {
const uint8_t data1[1] = {0x62};
const uint8_t data2[2] = {0xc3, 0x97};
const uint8_t data3[3] = {0xe2, 0x99, 0xa5};
const uint8_t data4[4] = {0xe1, 0x80, 0xb9, 0x32};
const uint8_t data5[48] = {
0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
ASSERT_EQ(Hash(0, 0, 0xbc9f1d34), 0xbc9f1d34);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data1), sizeof(data1), 0xbc9f1d34),
0xef1345c4);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data2), sizeof(data2), 0xbc9f1d34),
0x5b663814);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data3), sizeof(data3), 0xbc9f1d34),
0x323c078f);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data4), sizeof(data4), 0xbc9f1d34),
0xed21633a);
ASSERT_EQ(
Hash(reinterpret_cast<const char*>(data5), sizeof(data5), 0x12345678),
0xf333dabb);
}
} |
476 | cpp | google/leveldb | status | util/status.cc | util/status_test.cc | #ifndef STORAGE_LEVELDB_INCLUDE_STATUS_H_
#define STORAGE_LEVELDB_INCLUDE_STATUS_H_
#include <algorithm>
#include <string>
#include "leveldb/export.h"
#include "leveldb/slice.h"
namespace leveldb {
class LEVELDB_EXPORT Status {
public:
Status() noexcept : state_(nullptr) {}
~Status() { delete[] state_; }
Status(const Status& rhs);
Status& operator=(const Status& rhs);
Status(Status&& rhs) noexcept : state_(rhs.state_) { rhs.state_ = nullptr; }
Status& operator=(Status&& rhs) noexcept;
static Status OK() { return Status(); }
static Status NotFound(const Slice& msg, const Slice& msg2 = Slice()) {
return Status(kNotFound, msg, msg2);
}
static Status Corruption(const Slice& msg, const Slice& msg2 = Slice()) {
return Status(kCorruption, msg, msg2);
}
static Status NotSupported(const Slice& msg, const Slice& msg2 = Slice()) {
return Status(kNotSupported, msg, msg2);
}
static Status InvalidArgument(const Slice& msg, const Slice& msg2 = Slice()) {
return Status(kInvalidArgument, msg, msg2);
}
static Status IOError(const Slice& msg, const Slice& msg2 = Slice()) {
return Status(kIOError, msg, msg2);
}
bool ok() const { return (state_ == nullptr); }
bool IsNotFound() const { return code() == kNotFound; }
bool IsCorruption() const { return code() == kCorruption; }
bool IsIOError() const { return code() == kIOError; }
bool IsNotSupportedError() const { return code() == kNotSupported; }
bool IsInvalidArgument() const { return code() == kInvalidArgument; }
std::string ToString() const;
private:
enum Code {
kOk = 0,
kNotFound = 1,
kCorruption = 2,
kNotSupported = 3,
kInvalidArgument = 4,
kIOError = 5
};
Code code() const {
return (state_ == nullptr) ? kOk : static_cast<Code>(state_[4]);
}
Status(Code code, const Slice& msg, const Slice& msg2);
static const char* CopyState(const char* s);
const char* state_;
};
inline Status::Status(const Status& rhs) {
state_ = (rhs.state_ == nullptr) ? nullptr : CopyState(rhs.state_);
}
inline Status& Status::operator=(const Status& rhs) {
if (state_ != rhs.state_) {
delete[] state_;
state_ = (rhs.state_ == nullptr) ? nullptr : CopyState(rhs.state_);
}
return *this;
}
inline Status& Status::operator=(Status&& rhs) noexcept {
std::swap(state_, rhs.state_);
return *this;
}
}
#endif
#include "leveldb/status.h"
#include <cstdio>
#include "port/port.h"
namespace leveldb {
const char* Status::CopyState(const char* state) {
uint32_t size;
std::memcpy(&size, state, sizeof(size));
char* result = new char[size + 5];
std::memcpy(result, state, size + 5);
return result;
}
Status::Status(Code code, const Slice& msg, const Slice& msg2) {
assert(code != kOk);
const uint32_t len1 = static_cast<uint32_t>(msg.size());
const uint32_t len2 = static_cast<uint32_t>(msg2.size());
const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
char* result = new char[size + 5];
std::memcpy(result, &size, sizeof(size));
result[4] = static_cast<char>(code);
std::memcpy(result + 5, msg.data(), len1);
if (len2) {
result[5 + len1] = ':';
result[6 + len1] = ' ';
std::memcpy(result + 7 + len1, msg2.data(), len2);
}
state_ = result;
}
std::string Status::ToString() const {
if (state_ == nullptr) {
return "OK";
} else {
char tmp[30];
const char* type;
switch (code()) {
case kOk:
type = "OK";
break;
case kNotFound:
type = "NotFound: ";
break;
case kCorruption:
type = "Corruption: ";
break;
case kNotSupported:
type = "Not implemented: ";
break;
case kInvalidArgument:
type = "Invalid argument: ";
break;
case kIOError:
type = "IO error: ";
break;
default:
std::snprintf(tmp, sizeof(tmp),
"Unknown code(%d): ", static_cast<int>(code()));
type = tmp;
break;
}
std::string result(type);
uint32_t length;
std::memcpy(&length, state_, sizeof(length));
result.append(state_ + 5, length);
return result;
}
}
} | #include "leveldb/status.h"
#include <utility>
#include "gtest/gtest.h"
#include "leveldb/slice.h"
namespace leveldb {
TEST(Status, MoveConstructor) {
{
Status ok = Status::OK();
Status ok2 = std::move(ok);
ASSERT_TRUE(ok2.ok());
}
{
Status status = Status::NotFound("custom NotFound status message");
Status status2 = std::move(status);
ASSERT_TRUE(status2.IsNotFound());
ASSERT_EQ("NotFound: custom NotFound status message", status2.ToString());
}
{
Status self_moved = Status::IOError("custom IOError status message");
Status& self_moved_reference = self_moved;
self_moved_reference = std::move(self_moved);
}
}
} |
477 | cpp | google/leveldb | cache | util/cache.cc | util/cache_test.cc | #ifndef STORAGE_LEVELDB_INCLUDE_CACHE_H_
#define STORAGE_LEVELDB_INCLUDE_CACHE_H_
#include <cstdint>
#include "leveldb/export.h"
#include "leveldb/slice.h"
namespace leveldb {
class LEVELDB_EXPORT Cache;
LEVELDB_EXPORT Cache* NewLRUCache(size_t capacity);
class LEVELDB_EXPORT Cache {
public:
Cache() = default;
Cache(const Cache&) = delete;
Cache& operator=(const Cache&) = delete;
virtual ~Cache();
struct Handle {};
virtual Handle* Insert(const Slice& key, void* value, size_t charge,
void (*deleter)(const Slice& key, void* value)) = 0;
virtual Handle* Lookup(const Slice& key) = 0;
virtual void Release(Handle* handle) = 0;
virtual void* Value(Handle* handle) = 0;
virtual void Erase(const Slice& key) = 0;
virtual uint64_t NewId() = 0;
virtual void Prune() {}
virtual size_t TotalCharge() const = 0;
};
}
#endif
#include "leveldb/cache.h"
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/hash.h"
#include "util/mutexlock.h"
namespace leveldb {
Cache::~Cache() {}
namespace {
struct LRUHandle {
void* value;
void (*deleter)(const Slice&, void* value);
LRUHandle* next_hash;
LRUHandle* next;
LRUHandle* prev;
size_t charge;
size_t key_length;
bool in_cache;
uint32_t refs;
uint32_t hash;
char key_data[1];
Slice key() const {
assert(next != this);
return Slice(key_data, key_length);
}
};
class HandleTable {
public:
HandleTable() : length_(0), elems_(0), list_(nullptr) { Resize(); }
~HandleTable() { delete[] list_; }
LRUHandle* Lookup(const Slice& key, uint32_t hash) {
return *FindPointer(key, hash);
}
LRUHandle* Insert(LRUHandle* h) {
LRUHandle** ptr = FindPointer(h->key(), h->hash);
LRUHandle* old = *ptr;
h->next_hash = (old == nullptr ? nullptr : old->next_hash);
*ptr = h;
if (old == nullptr) {
++elems_;
if (elems_ > length_) {
Resize();
}
}
return old;
}
LRUHandle* Remove(const Slice& key, uint32_t hash) {
LRUHandle** ptr = FindPointer(key, hash);
LRUHandle* result = *ptr;
if (result != nullptr) {
*ptr = result->next_hash;
--elems_;
}
return result;
}
private:
uint32_t length_;
uint32_t elems_;
LRUHandle** list_;
LRUHandle** FindPointer(const Slice& key, uint32_t hash) {
LRUHandle** ptr = &list_[hash & (length_ - 1)];
while (*ptr != nullptr && ((*ptr)->hash != hash || key != (*ptr)->key())) {
ptr = &(*ptr)->next_hash;
}
return ptr;
}
void Resize() {
uint32_t new_length = 4;
while (new_length < elems_) {
new_length *= 2;
}
LRUHandle** new_list = new LRUHandle*[new_length];
memset(new_list, 0, sizeof(new_list[0]) * new_length);
uint32_t count = 0;
for (uint32_t i = 0; i < length_; i++) {
LRUHandle* h = list_[i];
while (h != nullptr) {
LRUHandle* next = h->next_hash;
uint32_t hash = h->hash;
LRUHandle** ptr = &new_list[hash & (new_length - 1)];
h->next_hash = *ptr;
*ptr = h;
h = next;
count++;
}
}
assert(elems_ == count);
delete[] list_;
list_ = new_list;
length_ = new_length;
}
};
class LRUCache {
public:
LRUCache();
~LRUCache();
void SetCapacity(size_t capacity) { capacity_ = capacity; }
Cache::Handle* Insert(const Slice& key, uint32_t hash, void* value,
size_t charge,
void (*deleter)(const Slice& key, void* value));
Cache::Handle* Lookup(const Slice& key, uint32_t hash);
void Release(Cache::Handle* handle);
void Erase(const Slice& key, uint32_t hash);
void Prune();
size_t TotalCharge() const {
MutexLock l(&mutex_);
return usage_;
}
private:
void LRU_Remove(LRUHandle* e);
void LRU_Append(LRUHandle* list, LRUHandle* e);
void Ref(LRUHandle* e);
void Unref(LRUHandle* e);
bool FinishErase(LRUHandle* e) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
size_t capacity_;
mutable port::Mutex mutex_;
size_t usage_ GUARDED_BY(mutex_);
LRUHandle lru_ GUARDED_BY(mutex_);
LRUHandle in_use_ GUARDED_BY(mutex_);
HandleTable table_ GUARDED_BY(mutex_);
};
LRUCache::LRUCache() : capacity_(0), usage_(0) {
lru_.next = &lru_;
lru_.prev = &lru_;
in_use_.next = &in_use_;
in_use_.prev = &in_use_;
}
LRUCache::~LRUCache() {
assert(in_use_.next == &in_use_);
for (LRUHandle* e = lru_.next; e != &lru_;) {
LRUHandle* next = e->next;
assert(e->in_cache);
e->in_cache = false;
assert(e->refs == 1);
Unref(e);
e = next;
}
}
void LRUCache::Ref(LRUHandle* e) {
if (e->refs == 1 && e->in_cache) {
LRU_Remove(e);
LRU_Append(&in_use_, e);
}
e->refs++;
}
void LRUCache::Unref(LRUHandle* e) {
assert(e->refs > 0);
e->refs--;
if (e->refs == 0) {
assert(!e->in_cache);
(*e->deleter)(e->key(), e->value);
free(e);
} else if (e->in_cache && e->refs == 1) {
LRU_Remove(e);
LRU_Append(&lru_, e);
}
}
void LRUCache::LRU_Remove(LRUHandle* e) {
e->next->prev = e->prev;
e->prev->next = e->next;
}
void LRUCache::LRU_Append(LRUHandle* list, LRUHandle* e) {
e->next = list;
e->prev = list->prev;
e->prev->next = e;
e->next->prev = e;
}
Cache::Handle* LRUCache::Lookup(const Slice& key, uint32_t hash) {
MutexLock l(&mutex_);
LRUHandle* e = table_.Lookup(key, hash);
if (e != nullptr) {
Ref(e);
}
return reinterpret_cast<Cache::Handle*>(e);
}
void LRUCache::Release(Cache::Handle* handle) {
MutexLock l(&mutex_);
Unref(reinterpret_cast<LRUHandle*>(handle));
}
Cache::Handle* LRUCache::Insert(const Slice& key, uint32_t hash, void* value,
size_t charge,
void (*deleter)(const Slice& key,
void* value)) {
MutexLock l(&mutex_);
LRUHandle* e =
reinterpret_cast<LRUHandle*>(malloc(sizeof(LRUHandle) - 1 + key.size()));
e->value = value;
e->deleter = deleter;
e->charge = charge;
e->key_length = key.size();
e->hash = hash;
e->in_cache = false;
e->refs = 1;
std::memcpy(e->key_data, key.data(), key.size());
if (capacity_ > 0) {
e->refs++;
e->in_cache = true;
LRU_Append(&in_use_, e);
usage_ += charge;
FinishErase(table_.Insert(e));
} else {
e->next = nullptr;
}
while (usage_ > capacity_ && lru_.next != &lru_) {
LRUHandle* old = lru_.next;
assert(old->refs == 1);
bool erased = FinishErase(table_.Remove(old->key(), old->hash));
if (!erased) {
assert(erased);
}
}
return reinterpret_cast<Cache::Handle*>(e);
}
bool LRUCache::FinishErase(LRUHandle* e) {
if (e != nullptr) {
assert(e->in_cache);
LRU_Remove(e);
e->in_cache = false;
usage_ -= e->charge;
Unref(e);
}
return e != nullptr;
}
void LRUCache::Erase(const Slice& key, uint32_t hash) {
MutexLock l(&mutex_);
FinishErase(table_.Remove(key, hash));
}
void LRUCache::Prune() {
MutexLock l(&mutex_);
while (lru_.next != &lru_) {
LRUHandle* e = lru_.next;
assert(e->refs == 1);
bool erased = FinishErase(table_.Remove(e->key(), e->hash));
if (!erased) {
assert(erased);
}
}
}
static const int kNumShardBits = 4;
static const int kNumShards = 1 << kNumShardBits;
class ShardedLRUCache : public Cache {
private:
LRUCache shard_[kNumShards];
port::Mutex id_mutex_;
uint64_t last_id_;
static inline uint32_t HashSlice(const Slice& s) {
return Hash(s.data(), s.size(), 0);
}
static uint32_t Shard(uint32_t hash) { return hash >> (32 - kNumShardBits); }
public:
explicit ShardedLRUCache(size_t capacity) : last_id_(0) {
const size_t per_shard = (capacity + (kNumShards - 1)) / kNumShards;
for (int s = 0; s < kNumShards; s++) {
shard_[s].SetCapacity(per_shard);
}
}
~ShardedLRUCache() override {}
Handle* Insert(const Slice& key, void* value, size_t charge,
void (*deleter)(const Slice& key, void* value)) override {
const uint32_t hash = HashSlice(key);
return shard_[Shard(hash)].Insert(key, hash, value, charge, deleter);
}
Handle* Lookup(const Slice& key) override {
const uint32_t hash = HashSlice(key);
return shard_[Shard(hash)].Lookup(key, hash);
}
void Release(Handle* handle) override {
LRUHandle* h = reinterpret_cast<LRUHandle*>(handle);
shard_[Shard(h->hash)].Release(handle);
}
void Erase(const Slice& key) override {
const uint32_t hash = HashSlice(key);
shard_[Shard(hash)].Erase(key, hash);
}
void* Value(Handle* handle) override {
return reinterpret_cast<LRUHandle*>(handle)->value;
}
uint64_t NewId() override {
MutexLock l(&id_mutex_);
return ++(last_id_);
}
void Prune() override {
for (int s = 0; s < kNumShards; s++) {
shard_[s].Prune();
}
}
size_t TotalCharge() const override {
size_t total = 0;
for (int s = 0; s < kNumShards; s++) {
total += shard_[s].TotalCharge();
}
return total;
}
};
}
Cache* NewLRUCache(size_t capacity) { return new ShardedLRUCache(capacity); }
} | #include "leveldb/cache.h"
#include <vector>
#include "gtest/gtest.h"
#include "util/coding.h"
namespace leveldb {
static std::string EncodeKey(int k) {
std::string result;
PutFixed32(&result, k);
return result;
}
static int DecodeKey(const Slice& k) {
assert(k.size() == 4);
return DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }
class CacheTest : public testing::Test {
public:
static void Deleter(const Slice& key, void* v) {
current_->deleted_keys_.push_back(DecodeKey(key));
current_->deleted_values_.push_back(DecodeValue(v));
}
static constexpr int kCacheSize = 1000;
std::vector<int> deleted_keys_;
std::vector<int> deleted_values_;
Cache* cache_;
CacheTest() : cache_(NewLRUCache(kCacheSize)) { current_ = this; }
~CacheTest() { delete cache_; }
int Lookup(int key) {
Cache::Handle* handle = cache_->Lookup(EncodeKey(key));
const int r = (handle == nullptr) ? -1 : DecodeValue(cache_->Value(handle));
if (handle != nullptr) {
cache_->Release(handle);
}
return r;
}
void Insert(int key, int value, int charge = 1) {
cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter));
}
Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) {
return cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter);
}
void Erase(int key) { cache_->Erase(EncodeKey(key)); }
static CacheTest* current_;
};
CacheTest* CacheTest::current_;
TEST_F(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100));
Insert(100, 101);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(200, 201);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(100, 102);
ASSERT_EQ(102, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
}
TEST_F(CacheTest, Erase) {
Erase(200);
ASSERT_EQ(0, deleted_keys_.size());
Insert(100, 101);
Insert(200, 201);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
}
TEST_F(CacheTest, EntriesArePinned) {
Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
Insert(100, 102);
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));
ASSERT_EQ(0, deleted_keys_.size());
cache_->Release(h1);
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(1, deleted_keys_.size());
cache_->Release(h2);
ASSERT_EQ(2, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[1]);
ASSERT_EQ(102, deleted_values_[1]);
}
TEST_F(CacheTest, EvictionPolicy) {
Insert(100, 101);
Insert(200, 201);
Insert(300, 301);
Cache::Handle* h = cache_->Lookup(EncodeKey(300));
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000 + i, 2000 + i);
ASSERT_EQ(2000 + i, Lookup(1000 + i));
ASSERT_EQ(101, Lookup(100));
}
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(301, Lookup(300));
cache_->Release(h);
}
TEST_F(CacheTest, UseExceedsCacheSize) {
std::vector<Cache::Handle*> h;
for (int i = 0; i < kCacheSize + 100; i++) {
h.push_back(InsertAndReturnHandle(1000 + i, 2000 + i));
}
for (int i = 0; i < h.size(); i++) {
ASSERT_EQ(2000 + i, Lookup(1000 + i));
}
for (int i = 0; i < h.size(); i++) {
cache_->Release(h[i]);
}
}
TEST_F(CacheTest, HeavyEntries) {
const int kLight = 1;
const int kHeavy = 10;
int added = 0;
int index = 0;
while (added < 2 * kCacheSize) {
const int weight = (index & 1) ? kLight : kHeavy;
Insert(index, 1000 + index, weight);
added += weight;
index++;
}
int cached_weight = 0;
for (int i = 0; i < index; i++) {
const int weight = (i & 1 ? kLight : kHeavy);
int r = Lookup(i);
if (r >= 0) {
cached_weight += weight;
ASSERT_EQ(1000 + i, r);
}
}
ASSERT_LE(cached_weight, kCacheSize + kCacheSize / 10);
}
TEST_F(CacheTest, NewId) {
uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId();
ASSERT_NE(a, b);
}
TEST_F(CacheTest, Prune) {
Insert(1, 100);
Insert(2, 200);
Cache::Handle* handle = cache_->Lookup(EncodeKey(1));
ASSERT_TRUE(handle);
cache_->Prune();
cache_->Release(handle);
ASSERT_EQ(100, Lookup(1));
ASSERT_EQ(-1, Lookup(2));
}
TEST_F(CacheTest, ZeroSizeCache) {
delete cache_;
cache_ = NewLRUCache(0);
Insert(1, 100);
ASSERT_EQ(-1, Lookup(1));
}
} |
478 | cpp | google/libaddressinput | testdata_source | cpp/test/testdata_source.cc | cpp/test/testdata_source_test.cc | #ifndef I18N_ADDRESSINPUT_TEST_TESTDATA_SOURCE_H_
#define I18N_ADDRESSINPUT_TEST_TESTDATA_SOURCE_H_
#include <libaddressinput/source.h>
#include <string>
namespace i18n {
namespace addressinput {
extern const char kDataFileName[];
class TestdataSource : public Source {
public:
TestdataSource(const TestdataSource&) = delete;
TestdataSource& operator=(const TestdataSource&) = delete;
explicit TestdataSource(bool aggregate);
TestdataSource(bool aggregate, const std::string& src_path);
~TestdataSource() override;
void Get(const std::string& key, const Callback& data_ready) const override;
private:
const bool aggregate_;
const std::string src_path_;
};
}
}
#endif
#include "testdata_source.h"
#include <cassert>
#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
namespace i18n {
namespace addressinput {
const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt";
namespace {
const char kNormalPrefix = '-';
const char kAggregatePrefix = '+';
const char kDataKeyPrefix[] = "data/";
const size_t kDataKeyPrefixLength = sizeof kDataKeyPrefix - 1;
const size_t kCldrRegionCodeLength = 2;
const size_t kAggregateDataKeyLength =
kDataKeyPrefixLength + kCldrRegionCodeLength;
std::map<std::string, std::string> InitData(const std::string& src_path) {
std::map<std::string, std::string> data;
std::ifstream file(src_path);
if (!file.is_open()) {
std::cerr << "Error opening \"" << src_path << "\"." << '\n';
std::exit(EXIT_FAILURE);
}
const std::string normal_prefix(1, kNormalPrefix);
const std::string aggregate_prefix(1, kAggregatePrefix);
std::string key;
std::string value;
auto last_data_it = data.end();
auto aggregate_data_it = data.end();
while (file.good()) {
std::getline(file, key, '=');
if (!key.empty()) {
std::getline(file, value, '\n');
last_data_it =
data.emplace_hint(last_data_it, normal_prefix + key, value);
if (key.compare(0,
kDataKeyPrefixLength,
kDataKeyPrefix,
kDataKeyPrefixLength) == 0) {
if (aggregate_data_it != data.end() &&
key.compare(0,
kAggregateDataKeyLength,
aggregate_data_it->first,
sizeof kAggregatePrefix,
kAggregateDataKeyLength) == 0) {
aggregate_data_it->second.append(", \"" + key + "\": " + value);
} else {
assert(key.size() == kAggregateDataKeyLength);
if (aggregate_data_it != data.end()) {
aggregate_data_it->second.push_back('}');
}
const std::string& aggregate_key =
aggregate_prefix + key.substr(0, kAggregateDataKeyLength);
aggregate_data_it = data.emplace_hint(
aggregate_data_it, aggregate_key, "{\"" + key + "\": " + value);
}
}
}
}
file.close();
return data;
}
const std::map<std::string, std::string>& GetData(const std::string& src_path) {
static const std::map<std::string, std::string> kData(InitData(src_path));
return kData;
}
}
TestdataSource::TestdataSource(bool aggregate, const std::string& src_path)
: aggregate_(aggregate), src_path_(src_path) {}
TestdataSource::TestdataSource(bool aggregate)
: aggregate_(aggregate), src_path_(kDataFileName) {}
TestdataSource::~TestdataSource() = default;
void TestdataSource::Get(const std::string& key,
const Callback& data_ready) const {
std::string prefixed_key(1, aggregate_ ? kAggregatePrefix : kNormalPrefix);
prefixed_key += key;
auto data_it = GetData(src_path_).find(prefixed_key);
bool success = data_it != GetData(src_path_).end();
std::string* data = nullptr;
if (success) {
data = new std::string(data_it->second);
} else {
success = true;
data = new std::string("{}");
}
data_ready(success, key, data);
}
}
} | #include "testdata_source.h"
#include <libaddressinput/callback.h>
#include <libaddressinput/source.h>
#include <cstddef>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "region_data_constants.h"
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::kDataFileName;
using i18n::addressinput::RegionDataConstants;
using i18n::addressinput::Source;
using i18n::addressinput::TestdataSource;
class TestdataSourceTest : public testing::TestWithParam<std::string> {
public:
TestdataSourceTest(const TestdataSourceTest&) = delete;
TestdataSourceTest& operator=(const TestdataSourceTest&) = delete;
protected:
TestdataSourceTest()
: source_(false),
source_with_path_(false, kDataFileName),
aggregate_source_(true),
aggregate_source_with_path_(true, kDataFileName),
success_(false),
key_(),
data_(),
data_ready_(BuildCallback(this, &TestdataSourceTest::OnDataReady)) {}
TestdataSource source_;
TestdataSource source_with_path_;
TestdataSource aggregate_source_;
TestdataSource aggregate_source_with_path_;
bool success_;
std::string key_;
std::string data_;
const std::unique_ptr<const Source::Callback> data_ready_;
private:
void OnDataReady(bool success, const std::string& key, std::string* data) {
ASSERT_FALSE(success && data == nullptr);
success_ = success;
key_ = key;
if (data != nullptr) {
data_ = *data;
delete data;
}
}
};
testing::AssertionResult DataIsValid(const std::string& data,
const std::string& key) {
if (data.empty()) {
return testing::AssertionFailure() << "empty data";
}
std::string expected_data_begin = R"({"id":")" + key + R"(")";
if (data.compare(0, expected_data_begin.length(), expected_data_begin) != 0) {
return testing::AssertionFailure()
<< data << " does not begin with " << expected_data_begin;
}
static const char kDataEnd[] = "\"}";
static const size_t kDataEndLength = sizeof kDataEnd - 1;
if (data.compare(data.length() - kDataEndLength,
kDataEndLength,
kDataEnd,
kDataEndLength) != 0) {
return testing::AssertionFailure()
<< data << " does not end with " << kDataEnd;
}
return testing::AssertionSuccess();
}
TEST_P(TestdataSourceTest, TestdataSourceHasValidDataForRegion) {
std::string key = "data/" + GetParam();
source_.Get(key, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(key, key_);
EXPECT_TRUE(DataIsValid(data_, key));
};
TEST_P(TestdataSourceTest, TestdataSourceWithPathHasValidDataForRegion) {
std::string key = "data/" + GetParam();
source_with_path_.Get(key, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(key, key_);
EXPECT_TRUE(DataIsValid(data_, key));
};
testing::AssertionResult AggregateDataIsValid(const std::string& data,
const std::string& key) {
if (data.empty()) {
return testing::AssertionFailure() << "empty data";
}
std::string expected_data_begin = "{\"" + key;
if (data.compare(0, expected_data_begin.length(), expected_data_begin) != 0) {
return testing::AssertionFailure()
<< data << " does not begin with " << expected_data_begin;
}
static const char kDataEnd[] = "\"}}";
static const size_t kDataEndLength = sizeof kDataEnd - 1;
if (data.compare(data.length() - kDataEndLength,
kDataEndLength,
kDataEnd,
kDataEndLength) != 0) {
return testing::AssertionFailure()
<< data << " does not end with " << kDataEnd;
}
return testing::AssertionSuccess();
}
TEST_P(TestdataSourceTest, TestdataSourceHasValidAggregatedDataForRegion) {
std::string key = "data/" + GetParam();
aggregate_source_.Get(key, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(key, key_);
EXPECT_TRUE(AggregateDataIsValid(data_, key));
};
TEST_P(TestdataSourceTest,
TestdataSourceWithPathHasValidAggregatedDataForRegion) {
std::string key = "data/" + GetParam();
aggregate_source_with_path_.Get(key, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(key, key_);
EXPECT_TRUE(AggregateDataIsValid(data_, key));
};
INSTANTIATE_TEST_SUITE_P(
AllRegions, TestdataSourceTest,
testing::ValuesIn(RegionDataConstants::GetRegionCodes()));
TEST_F(TestdataSourceTest, GetExistingData) {
static const std::string kKey = "data";
source_.Get(kKey, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kKey, key_);
EXPECT_TRUE(DataIsValid(data_, kKey));
}
TEST_F(TestdataSourceTest, GetMissingKeyReturnsEmptyDictionary) {
static const std::string kJunkKey = "junk";
source_.Get(kJunkKey, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kJunkKey, key_);
EXPECT_EQ("{}", data_);
}
TEST_F(TestdataSourceTest, AggregateGetMissingKeyReturnsEmptyDictionary) {
static const std::string kJunkKey = "junk";
aggregate_source_.Get(kJunkKey, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kJunkKey, key_);
EXPECT_EQ("{}", data_);
}
TEST_F(TestdataSourceTest, GetEmptyKeyReturnsEmptyDictionary) {
static const std::string kEmptyKey;
source_.Get(kEmptyKey, *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kEmptyKey, key_);
EXPECT_EQ("{}", data_);
}
} |
479 | cpp | google/libaddressinput | fake_storage | cpp/test/fake_storage.cc | cpp/test/fake_storage_test.cc | #ifndef I18N_ADDRESSINPUT_FAKE_STORAGE_H_
#define I18N_ADDRESSINPUT_FAKE_STORAGE_H_
#include <libaddressinput/storage.h>
#include <map>
#include <string>
namespace i18n {
namespace addressinput {
class FakeStorage : public Storage {
public:
FakeStorage(const FakeStorage&) = delete;
FakeStorage& operator=(const FakeStorage&) = delete;
FakeStorage();
~FakeStorage() override;
void Put(const std::string& key, std::string* data) override;
void Get(const std::string& key, const Callback& data_ready) const override;
private:
std::map<std::string, std::string*> data_;
};
}
}
#endif
#include "fake_storage.h"
#include <cassert>
#include <cstddef>
#include <string>
namespace i18n {
namespace addressinput {
FakeStorage::FakeStorage() = default;
FakeStorage::~FakeStorage() {
for (const auto& pair : data_) {
delete pair.second;
}
}
void FakeStorage::Put(const std::string& key, std::string* data) {
assert(data != nullptr);
auto result = data_.emplace(key, data);
if (!result.second) {
delete result.first->second;
result.first->second = data;
}
}
void FakeStorage::Get(const std::string& key,
const Callback& data_ready) const {
auto data_it = data_.find(key);
bool success = data_it != data_.end();
data_ready(success, key,
success ? new std::string(*data_it->second) : nullptr);
}
}
} | #include "fake_storage.h"
#include <libaddressinput/callback.h>
#include <libaddressinput/storage.h>
#include <cstddef>
#include <memory>
#include <string>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::FakeStorage;
using i18n::addressinput::Storage;
class FakeStorageTest : public testing::Test {
public:
FakeStorageTest(const FakeStorageTest&) = delete;
FakeStorageTest& operator=(const FakeStorageTest&) = delete;
protected:
FakeStorageTest()
: storage_(),
success_(false),
key_(),
data_(),
data_ready_(BuildCallback(this, &FakeStorageTest::OnDataReady)) {}
FakeStorage storage_;
bool success_;
std::string key_;
std::string data_;
const std::unique_ptr<const Storage::Callback> data_ready_;
private:
void OnDataReady(bool success, const std::string& key, std::string* data) {
ASSERT_FALSE(success && data == nullptr);
success_ = success;
key_ = key;
if (data != nullptr) {
data_ = *data;
delete data;
}
}
};
TEST_F(FakeStorageTest, GetWithoutPutReturnsEmptyData) {
storage_.Get("key", *data_ready_);
EXPECT_FALSE(success_);
EXPECT_EQ("key", key_);
EXPECT_TRUE(data_.empty());
}
TEST_F(FakeStorageTest, GetReturnsWhatWasPut) {
storage_.Put("key", new std::string("value"));
storage_.Get("key", *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ("key", key_);
EXPECT_EQ("value", data_);
}
TEST_F(FakeStorageTest, SecondPutOverwritesData) {
storage_.Put("key", new std::string("bad-value"));
storage_.Put("key", new std::string("good-value"));
storage_.Get("key", *data_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ("key", key_);
EXPECT_EQ("good-value", data_);
}
} |
480 | cpp | google/libaddressinput | region_data_constants | cpp/src/region_data_constants.cc | cpp/test/region_data_constants_test.cc | #ifndef I18N_ADDRESSINPUT_REGION_DATA_CONSTANTS_H_
#define I18N_ADDRESSINPUT_REGION_DATA_CONSTANTS_H_
#include <cstddef>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
class RegionDataConstants {
public:
static bool IsSupported(const std::string& region_code);
static const std::vector<std::string>& GetRegionCodes();
static std::string GetRegionData(const std::string& region_code);
static const std::string& GetDefaultRegionData();
static size_t GetMaxLookupKeyDepth(const std::string& region_code);
RegionDataConstants(const RegionDataConstants&) = delete;
RegionDataConstants& operator=(const RegionDataConstants&) = delete;
};
}
}
#endif
#include "region_data_constants.h"
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <map>
#include <string>
#include <vector>
#include "address_field_util.h"
#include "format_element.h"
#include "lookup_key.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
struct RegionData {
const char* const region_code;
const char* const data;
};
const RegionData kRegionData[] = {
{"AC", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"ASCN 1ZZ",)"
R"("languages":"en")"
"}"},
{"AD", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"AD100,AD501,AD700",)"
R"("posturl":"http:
R"("languages":"ca")"
"}"},
{"AE", "{"
R"("fmt":"%N%n%O%n%A%n%S",)"
R"("lfmt":"%N%n%O%n%A%n%S",)"
R"("require":"AS",)"
R"("state_name_type":"emirate",)"
R"("languages":"ar")"
"}"},
{"AF", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"1001,2601,3801",)"
R"("languages":"fa~ps~uz-Arab~tk")"
"}"},
{"AG", "{"
R"("require":"A",)"
R"("languages":"en")"
"}"},
{"AI", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"2640",)"
R"("languages":"en")"
"}"},
{"AL", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C",)"
R"("zipex":"1001,1017,3501",)"
R"("languages":"sq")"
"}"},
{"AM", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C%n%S",)"
R"("lfmt":"%N%n%O%n%A%n%Z%n%C%n%S",)"
R"("zipex":"375010,0002,0010",)"
R"("languages":"hy")"
"}"},
{"AO", "{"
R"("languages":"pt")"
"}"},
{"AQ", "{"
"}"},
{"AR", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)"
R"("zipex":"C1070AAM,C1000WAM,B1000TBU,X5187XAB",)"
R"("posturl":"http:
R"("languages":"es")"
"}"},
{"AS", "{"
R"("fmt":"%N%n%O%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("zip_name_type":"zip",)"
R"("state_name_type":"state",)"
R"("zipex":"96799",)"
R"("posturl":"http:
R"("languages":"sm~en")"
"}"},
{"AT", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"1010,3741",)"
R"("posturl":"http:
R"("languages":"de~hr~sl~hu")"
"}"},
{"AU", "{"
R"("fmt":"%O%n%N%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("state_name_type":"state",)"
R"("locality_name_type":"suburb",)"
R"("zipex":"2060,3171,6430,4000,4006,3001",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"AW", "{"
R"("languages":"nl~pap")"
"}"},
{"AX", "{"
R"("fmt":"%O%n%N%n%A%nAX-%Z %C%nÅLAND",)"
R"("require":"ACZ",)"
R"("zipex":"22150,22550,22240,22710,22270,22730,22430",)"
R"("posturl":"https:
R"("languages":"sv")"
"}"},
{"AZ", "{"
R"("fmt":"%N%n%O%n%A%nAZ %Z %C",)"
R"("zipex":"1000",)"
R"("languages":"az~az-Cyrl")"
"}"},
{"BA", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"71000",)"
R"("languages":"bs~bs-Cyrl~hr~sr~sr-Latn")"
"}"},
{"BB", "{"
R"("fmt":"%N%n%O%n%A%n%C, %S %Z",)"
R"("state_name_type":"parish",)"
R"("zipex":"BB23026,BB22025",)"
R"("languages":"en")"
"}"},
{"BD", "{"
R"("fmt":"%N%n%O%n%A%n%C - %Z",)"
R"("zipex":"1340,1000",)"
R"("posturl":"https:
R"("languages":"bn")"
"}"},
{"BE", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"4000,1000",)"
R"("posturl":"https:
R"("languages":"nl~fr~de")"
"}"},
{"BF", "{"
R"("fmt":"%N%n%O%n%A%n%C %X",)"
R"("languages":"fr")"
"}"},
{"BG", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"1000,1700",)"
R"("posturl":"http:
R"("languages":"bg")"
"}"},
{"BH", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"317",)"
R"("languages":"ar")"
"}"},
{"BI", "{"
R"("languages":"rn~fr~en")"
"}"},
{"BJ", "{"
R"("languages":"fr")"
"}"},
{"BL", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97100",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"BM", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"FL 07,HM GX,HM 12",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"BN", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"BT2328,KA1131,BA1511",)"
R"("posturl":"http:
R"("languages":"ms~ms-Arab")"
"}"},
{"BO", "{"
R"("languages":"es~qu~ay")"
"}"},
{"BQ", "{"
R"("languages":"nl")"
"}"},
{"BR", "{"
R"("fmt":"%O%n%N%n%A%n%D%n%C-%S%n%Z",)"
R"("require":"ASCZ",)"
R"("state_name_type":"state",)"
R"("sublocality_name_type":"neighborhood",)"
R"("zipex":"40301-110,70002-900",)"
R"("posturl":"http:
R"("languages":"pt")"
"}"},
{"BS", "{"
R"("fmt":"%N%n%O%n%A%n%C, %S",)"
R"("state_name_type":"island",)"
R"("languages":"en")"
"}"},
{"BT", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"11001,31101,35003",)"
R"("posturl":"https:
R"("languages":"dz")"
"}"},
{"BV", "{"
"}"},
{"BW", "{"
R"("languages":"en~tn")"
"}"},
{"BY", "{"
R"("fmt":"%O%n%N%n%A%n%Z, %C%n%S",)"
R"("zipex":"223016,225860,220050",)"
R"("posturl":"http:
R"("languages":"be~ru")"
"}"},
{"BZ", "{"
R"("languages":"en")"
"}"},
{"CA", "{"
R"("fmt":"%N%n%O%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("zipex":"H3Z 2Y7,V8X 3X4,T0L 1K0,T0H 1A0,K1A 0B1",)"
R"("posturl":"https:
R"("languages":"en~fr")"
"}"},
{"CC", "{"
R"("fmt":"%O%n%N%n%A%n%C %S %Z",)"
R"("zipex":"6799",)"
R"("languages":"en")"
"}"},
{"CD", "{"
R"("languages":"sw~lua~fr~ln~kg")"
"}"},
{"CF", "{"
R"("languages":"fr~sg")"
"}"},
{"CG", "{"
R"("languages":"fr")"
"}"},
{"CH", "{"
R"("fmt":"%O%n%N%n%A%nCH-%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"2544,1211,1556,3030",)"
R"("posturl":"http:
R"("languages":"de~gsw~fr~it~rm")"
"}"},
{"CI", "{"
R"("fmt":"%N%n%O%n%X %A %C %X",)"
R"("languages":"fr")"
"}"},
{"CK", "{"
R"("languages":"en")"
"}"},
{"CL", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)"
R"("zipex":"8340457,8720019,1230000,8329100",)"
R"("languages":"es")"
"}"},
{"CM", "{"
R"("languages":"fr~en")"
"}"},
{"CN", "{"
R"("fmt":"%Z%n%S%C%D%n%A%n%O%n%N",)"
R"("lfmt":"%N%n%O%n%A%n%D%n%C%n%S, %Z",)"
R"("require":"ACSZ",)"
R"("sublocality_name_type":"district",)"
R"("zipex":"266033,317204,100096,100808",)"
R"("posturl":"http:
R"("languages":"zh")"
"}"},
{"CO", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%C, %S, %Z",)"
R"("require":"AS",)"
R"("state_name_type":"department",)"
R"("zipex":"111221,130001,760011",)"
R"("posturl":"http:
R"("languages":"es")"
"}"},
{"CR", "{"
R"("fmt":"%N%n%O%n%A%n%S, %C%n%Z",)"
R"("require":"ACS",)"
R"("zipex":"1000,2010,1001",)"
R"("posturl":"https:
R"("languages":"es")"
"}"},
{"CU", "{"
R"("fmt":"%N%n%O%n%A%n%C %S%n%Z",)"
R"("zipex":"10700",)"
R"("languages":"es")"
"}"},
{"CV", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C%n%S",)"
R"("state_name_type":"island",)"
R"("zipex":"7600",)"
R"("languages":"pt")"
"}"},
{"CW", "{"
R"("languages":"pap~nl")"
"}"},
{"CX", "{"
R"("fmt":"%O%n%N%n%A%n%C %S %Z",)"
R"("zipex":"6798",)"
R"("languages":"en")"
"}"},
{"CY", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"2008,3304,1900",)"
R"("languages":"el~tr")"
"}"},
{"CZ", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"100 00,251 66,530 87,110 00,225 99",)"
R"("posturl":"http:
R"("languages":"cs")"
"}"},
{"DE", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"26133,53225",)"
R"("posturl":"http:
R"("languages":"de~frr")"
"}"},
{"DJ", "{"
R"("languages":"ar~fr")"
"}"},
{"DK", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"8660,1566",)"
R"("posturl":"http:
R"("languages":"da~de~kl")"
"}"},
{"DM", "{"
R"("languages":"en")"
"}"},
{"DO", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"11903,10101",)"
R"("posturl":"http:
R"("languages":"es")"
"}"},
{"DZ", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"40304,16027",)"
R"("languages":"ar~fr")"
"}"},
{"EC", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C",)"
R"("zipex":"090105,092301",)"
R"("posturl":"http:
R"("languages":"es~qu")"
"}"},
{"EE", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C %S",)"
R"("require":"ACZ",)"
R"("zipex":"69501,11212",)"
R"("posturl":"https:
R"("languages":"et")"
"}"},
{"EG", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%S%n%Z",)"
R"("lfmt":"%N%n%O%n%A%n%C%n%S%n%Z",)"
R"("zipex":"4460232,5734356",)"
R"("languages":"ar")"
"}"},
{"EH", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"70000,72000",)"
R"("languages":"ar")"
"}"},
{"ER", "{"
R"("languages":"ti~en~ar")"
"}"},
{"ES", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C %S",)"
R"("require":"ACSZ",)"
R"("zipex":"28039,28300,28070",)"
R"("posturl":"http:
R"("languages":"es~ca~gl~eu")"
"}"},
{"ET", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"1000",)"
R"("languages":"am")"
"}"},
{"FI", "{"
R"("fmt":"%O%n%N%n%A%nFI-%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"00550,00011",)"
R"("posturl":"https:
R"("languages":"fi~sv~sms")"
"}"},
{"FJ", "{"
R"("languages":"en~hif~fj")"
"}"},
{"FK", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"FIQQ 1ZZ",)"
R"("languages":"en")"
"}"},
{"FM", "{"
R"("fmt":"%N%n%O%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("zip_name_type":"zip",)"
R"("state_name_type":"state",)"
R"("zipex":"96941,96944",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"FO", "{"
R"("fmt":"%N%n%O%n%A%nFO%Z %C",)"
R"("zipex":"100",)"
R"("posturl":"https:
R"("languages":"fo")"
"}"},
{"FR", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"33380,34092,33506",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"GA", "{"
R"("languages":"fr")"
"}"},
{"GB", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("require":"ACZ",)"
R"("locality_name_type":"post_town",)"
R"("zipex":"EC1Y 8SY,GIR 0AA,M2 5BQ,M34 4AB,CR0 2YR,DN16 9AA,W1A 4ZZ,EC1A 1HQ,OX14 4PG,BS18 8HF,NR25 7HG,RH6 0NP,BH23 6AA,B6 5BA,SO23 9AP,PO1 3AX,BFPO 61",)"
R"("posturl":"http:
R"("languages":"en~cy~ga~gd")"
"}"},
{"GD", "{"
R"("languages":"en")"
"}"},
{"GE", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"0101",)"
R"("posturl":"http:
R"("languages":"ka~ab~os")"
"}"},
{"GF", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97300",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"GG", "{"
R"("fmt":"%N%n%O%n%A%n%C%nGUERNSEY%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"GY1 1AA,GY2 2BT",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"GH", "{"
R"("languages":"ak~en~ee~gaa")"
"}"},
{"GI", "{"
R"("fmt":"%N%n%O%n%A%nGIBRALTAR%n%Z",)"
R"("require":"A",)"
R"("zipex":"GX11 1AA",)"
R"("languages":"en")"
"}"},
{"GL", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"3900,3950,3911",)"
R"("languages":"kl")"
"}"},
{"GM", "{"
R"("languages":"en")"
"}"},
{"GN", "{"
R"("fmt":"%N%n%O%n%Z %A %C",)"
R"("zipex":"001,200,100",)"
R"("languages":"fr")"
"}"},
{"GP", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97100",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"GQ", "{"
R"("languages":"es~fr~pt")"
"}"},
{"GR", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"151 24,151 10,101 88",)"
R"("posturl":"https:
R"("languages":"el")"
"}"},
{"GS", "{"
R"("fmt":"%N%n%O%n%A%n%n%C%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"SIQQ 1ZZ")"
"}"},
{"GT", "{"
R"("fmt":"%N%n%O%n%A%n%Z- %C",)"
R"("zipex":"09001,01501",)"
R"("languages":"es~quc")"
"}"},
{"GU", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("require":"ACZ",)"
R"("zip_name_type":"zip",)"
R"("zipex":"96910,96931",)"
R"("posturl":"http:
R"("languages":"en~ch")"
"}"},
{"GW", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"1000,1011",)"
R"("languages":"pt")"
"}"},
{"GY", "{"
R"("languages":"en")"
"}"},
{"HK", "{"
R"("fmt":"%S%n%C%n%A%n%O%n%N",)"
R"("lfmt":"%N%n%O%n%A%n%C%n%S",)"
R"("require":"AS",)"
R"("state_name_type":"area",)"
R"("locality_name_type":"district",)"
R"("languages":"zh-Hant~en")"
"}"},
{"HM", "{"
R"("fmt":"%O%n%N%n%A%n%C %S %Z",)"
R"("zipex":"7050")"
"}"},
{"HN", "{"
R"("fmt":"%N%n%O%n%A%n%C, %S%n%Z",)"
R"("require":"ACS",)"
R"("state_name_type":"department",)"
R"("zipex":"31301",)"
R"("languages":"es")"
"}"},
{"HR", "{"
R"("fmt":"%N%n%O%n%A%nHR-%Z %C",)"
R"("zipex":"10000,21001,10002",)"
R"("posturl":"http:
R"("languages":"hr~it~vec")"
"}"},
{"HT", "{"
R"("fmt":"%N%n%O%n%A%nHT%Z %C",)"
R"("zipex":"6120,5310,6110,8510",)"
R"("languages":"ht~fr")"
"}"},
{"HU", "{"
R"("fmt":"%N%n%O%n%C%n%A%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"1037,2380,1540",)"
R"("posturl":"http:
R"("languages":"hu")"
"}"},
{"ID", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%S %Z",)"
R"("require":"AS",)"
R"("zipex":"40115",)"
R"("languages":"id")"
"}"},
{"IE", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%C%n%S%n%Z",)"
R"("zip_name_type":"eircode",)"
R"("state_name_type":"county",)"
R"("sublocality_name_type":"townland",)"
R"("zipex":"A65 F4E2",)"
R"("posturl":"https:
R"("languages":"en")"
"}"},
{"IL", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"9614303",)"
R"("posturl":"http:
R"("languages":"iw~ar")"
"}"},
{"IM", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"IM2 1AA,IM99 1PS",)"
R"("posturl":"https:
R"("languages":"en~gv")"
"}"},
{"IN", "{"
R"("fmt":"%N%n%O%n%A%n%T%n%F%n%L%n%C %Z%n%S",)"
R"("require":"ACSZ",)"
R"("zip_name_type":"pin",)"
R"("state_name_type":"state",)"
R"("zipex":"110034,110001",)"
R"("posturl":"https:
R"("languages":"en~hi")"
"}"},
{"IO", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"BBND 1ZZ",)"
R"("languages":"en")"
"}"},
{"IQ", "{"
R"("fmt":"%O%n%N%n%A%n%C, %S%n%Z",)"
R"("require":"ACS",)"
R"("zipex":"31001",)"
R"("languages":"ar")"
"}"},
{"IR", "{"
R"("fmt":"%O%n%N%n%S%n%C, %D%n%A%n%Z",)"
R"("sublocality_name_type":"neighborhood",)"
R"("zipex":"11936-12345",)"
R"("languages":"fa")"
"}"},
{"IS", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"320,121,220,110",)"
R"("posturl":"https:
R"("languages":"is")"
"}"},
{"IT", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C %S",)"
R"("require":"ACSZ",)"
R"("zipex":"00144,47037,39049",)"
R"("posturl":"http:
R"("languages":"it")"
"}"},
{"JE", "{"
R"("fmt":"%N%n%O%n%A%n%C%nJERSEY%n%Z",)"
R"("require":"ACZ",)"
R"("zipex":"JE1 1AA,JE2 2BT",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"JM", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%S %X",)"
R"("require":"ACS",)"
R"("state_name_type":"parish",)"
R"("languages":"en")"
"}"},
{"JO", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"11937,11190",)"
R"("languages":"ar")"
"}"},
{"JP", "{"
R"("fmt":"〒%Z%n%S%n%A%n%O%n%N",)"
R"("lfmt":"%N%n%O%n%A, %S%n%Z",)"
R"("require":"ASZ",)"
R"("state_name_type":"prefecture",)"
R"("zipex":"154-0023,350-1106,951-8073,112-0001,208-0032,231-0012",)"
R"("posturl":"http:
R"("languages":"ja")"
"}"},
{"KE", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"20100,00100",)"
R"("languages":"sw~en")"
"}"},
{"KG", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"720001",)"
R"("languages":"ky~ru")"
"}"},
{"KH", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"120101,120108",)"
R"("posturl":"https:
R"("languages":"km")"
"}"},
{"KI", "{"
R"("fmt":"%N%n%O%n%A%n%S%n%C",)"
R"("state_name_type":"island",)"
R"("languages":"en~gil")"
"}"},
{"KM", "{"
R"("languages":"ar~fr~zdj~wni")"
"}"},
{"KN", "{"
R"("fmt":"%N%n%O%n%A%n%C, %S",)"
R"("require":"ACS",)"
R"("state_name_type":"island",)"
R"("languages":"en")"
"}"},
{"KP", "{"
R"("fmt":"%Z%n%S%n%C%n%A%n%O%n%N",)"
R"("lfmt":"%N%n%O%n%A%n%C%n%S, %Z",)"
R"("languages":"ko")"
"}"},
{"KR", "{"
R"("fmt":"%S %C%D%n%A%n%O%n%N%n%Z",)"
R"("lfmt":"%N%n%O%n%A%n%D%n%C%n%S%n%Z",)"
R"("require":"ACSZ",)"
R"("state_name_type":"do_si",)"
R"("sublocality_name_type":"district",)"
R"("zipex":"03051",)"
R"("posturl":"http:
R"("languages":"ko")"
"}"},
{"KW", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"54541,54551,54404,13009",)"
R"("languages":"ar")"
"}"},
{"KY", "{"
R"("fmt":"%N%n%O%n%A%n%S %Z",)"
R"("require":"AS",)"
R"("state_name_type":"island",)"
R"("zipex":"KY1-1100,KY1-1702,KY2-2101",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"KZ", "{"
R"("fmt":"%Z%n%S%n%C%n%A%n%O%n%N",)"
R"("zipex":"040900,050012",)"
R"("languages":"kk~ru")"
"}"},
{"LA", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"01160,01000",)"
R"("languages":"lo")"
"}"},
{"LB", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"2038 3054,1107 2810,1000",)"
R"("languages":"ar")"
"}"},
{"LC", "{"
R"("languages":"en")"
"}"},
{"LI", "{"
R"("fmt":"%O%n%N%n%A%nFL-%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"9496,9491,9490,9485",)"
R"("posturl":"http:
R"("languages":"de~gsw")"
"}"},
{"LK", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"20000,00100",)"
R"("posturl":"http:
R"("languages":"si~ta")"
"}"},
{"LR", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"1000",)"
R"("languages":"en")"
"}"},
{"LS", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"100",)"
R"("languages":"st~en")"
"}"},
{"LT", "{"
R"("fmt":"%O%n%N%n%A%nLT-%Z %C %S",)"
R"("require":"ACZ",)"
R"("zipex":"04340,03500",)"
R"("posturl":"http:
R"("languages":"lt")"
"}"},
{"LU", "{"
R"("fmt":"%O%n%N%n%A%nL-%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"4750,2998",)"
R"("posturl":"https:
R"("languages":"fr~lb~de")"
"}"},
{"LV", "{"
R"("fmt":"%N%n%O%n%A%n%S%n%C, %Z",)"
R"("require":"ACZ",)"
R"("zipex":"LV-1073,LV-1000",)"
R"("posturl":"https:
R"("languages":"lv")"
"}"},
{"LY", "{"
R"("languages":"ar")"
"}"},
{"MA", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"53000,10000,20050,16052",)"
R"("languages":"ar~fr~tzm")"
"}"},
{"MC", "{"
R"("fmt":"%N%n%O%n%A%nMC-%Z %C %X",)"
R"("zipex":"98000,98020,98011,98001",)"
R"("languages":"fr")"
"}"},
{"MD", "{"
R"("fmt":"%N%n%O%n%A%nMD-%Z %C",)"
R"("zipex":"2012,2019",)"
R"("languages":"ro")"
"}"},
{"ME", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"81257,81258,81217,84314,85366",)"
R"("languages":"sr-Latn")"
"}"},
{"MF", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97100",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"MG", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"501,101",)"
R"("languages":"mg~fr~en")"
"}"},
{"MH", "{"
R"("fmt":"%N%n%O%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("zip_name_type":"zip",)"
R"("state_name_type":"state",)"
R"("zipex":"96960,96970",)"
R"("posturl":"http:
R"("languages":"en~mh")"
"}"},
{"MK", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"1314,1321,1443,1062",)"
R"("languages":"mk~sq")"
"}"},
{"ML", "{"
R"("languages":"fr")"
"}"},
{"MM", "{"
R"("fmt":"%N%n%O%n%A%n%C, %Z",)"
R"("zipex":"11181",)"
R"("languages":"my")"
"}"},
{"MN", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%S %Z",)"
R"("zipex":"65030,65270",)"
R"("posturl":"http:
R"("languages":"mn")"
"}"},
{"MO", "{"
R"("fmt":"%A%n%O%n%N",)"
R"("lfmt":"%N%n%O%n%A",)"
R"("require":"A",)"
R"("languages":"zh-Hant~pt")"
"}"},
{"MP", "{"
R"("fmt":"%N%n%O%n%A%n%C %S %Z",)"
R"("require":"ACSZ",)"
R"("zip_name_type":"zip",)"
R"("state_name_type":"state",)"
R"("zipex":"96950,96951,96952",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"MQ", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97220",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"MR", "{"
R"("languages":"ar")"
"}"},
{"MS", "{"
R"("languages":"en")"
"}"},
{"MT", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"NXR 01,ZTN 05,GPO 01,BZN 1130,SPB 6031,VCT 1753",)"
R"("posturl":"https:
R"("languages":"mt~en")"
"}"},
{"MU", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C",)"
R"("zipex":"42602",)"
R"("languages":"en~fr")"
"}"},
{"MV", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"20026",)"
R"("posturl":"http:
R"("languages":"dv")"
"}"},
{"MW", "{"
R"("fmt":"%N%n%O%n%A%n%C %X",)"
R"("languages":"en~ny")"
"}"},
{"MX", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%Z %C, %S",)"
R"("require":"ACSZ",)"
R"("state_name_type":"state",)"
R"("sublocality_name_type":"neighborhood",)"
R"("zipex":"02860,77520,06082",)"
R"("posturl":"https:
R"("languages":"es")"
"}"},
{"MY", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%Z %C%n%S",)"
R"("require":"ACZ",)"
R"("state_name_type":"state",)"
R"("sublocality_name_type":"village_township",)"
R"("zipex":"43000,50754,88990,50670",)"
R"("posturl":"http:
R"("languages":"ms")"
"}"},
{"MZ", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C%S",)"
R"("zipex":"1102,1119,3212",)"
R"("languages":"pt")"
"}"},
{"NA", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R"("zipex":"10001,10017",)"
R"("languages":"en")"
"}"},
{"NC", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"98814,98800,98810",)"
R"("posturl":"https:
R"("languages":"fr")"
"}"},
{"NE", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("zipex":"8001",)"
R"("languages":"fr")"
"}"},
{"NF", "{"
R"("fmt":"%O%n%N%n%A%n%C %S %Z",)"
R"("zipex":"2899",)"
R"("languages":"en")"
"}"},
{"NG", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%C %Z%n%S",)"
R"("state_name_type":"state",)"
R"("zipex":"930283,300001,931104",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"NI", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C, %S",)"
R"("state_name_type":"department",)"
R"("zipex":"52000",)"
R"("posturl":"http:
R"("languages":"es")"
"}"},
{"NL", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"1234 AB,2490 AA",)"
R"("posturl":"http:
R"("languages":"nl~fy")"
"}"},
{"NO", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("locality_name_type":"post_town",)"
R"("zipex":"0025,0107,6631",)"
R"("posturl":"http:
R"("languages":"no~nn~se")"
"}"},
{"NP", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z",)"
R"("zipex":"44601",)"
R"("posturl":"http:
R"("languages":"ne")"
"}"},
{"NR", "{"
R"("fmt":"%N%n%O%n%A%n%S",)"
R"("require":"AS",)"
R"("state_name_type":"district",)"
R"("languages":"en")"
"}"},
{"NU", "{"
R"("languages":"en~niu")"
"}"},
{"NZ", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%C %Z",)"
R"("require":"ACZ",)"
R"("zipex":"6001,6015,6332,8252,1030",)"
R"("posturl":"https:
R"("languages":"en~mi")"
"}"},
{"OM", "{"
R"("fmt":"%N%n%O%n%A%n%Z%n%C",)"
R"("zipex":"133,112,111",)"
R"("languages":"ar")"
"}"},
{"PA", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%S",)"
R"("languages":"es")"
"}"},
{"PE", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z%n%S",)"
R"("locality_name_type":"district",)"
R"("zipex":"LIMA 23,LIMA 42,CALLAO 2,02001",)"
R"("posturl":"http:
R"("languages":"es")"
"}"},
{"PF", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C %S",)"
R"("require":"ACSZ",)"
R"("state_name_type":"island",)"
R"("zipex":"98709",)"
R"("languages":"fr~ty")"
"}"},
{"PG", "{"
R"("fmt":"%N%n%O%n%A%n%C %Z %S",)"
R"("require":"ACS",)"
R"("zipex":"111",)"
R"("languages":"tpi~en~ho")"
"}"},
{"PH", "{"
R"("fmt":"%N%n%O%n%A%n%D, %C%n%Z %S",)"
R"("zipex":"1008,1050,1135,1207,2000,1000",)"
R"("posturl":"http:
R"("languages":"en")"
"}"},
{"PK", "{"
R"("fmt":"%N%n%O%n%A%n%D%n%C-%Z",)"
R"("zipex":"44000",)"
R"("posturl":"http:
R"("languages":"ur~en")"
"}"},
{"PL", "{"
R"("fmt":"%N%n%O%n%A%n%Z %C",)"
R"("require":"ACZ",)"
R"("zipex":"00-950,05-470,48-300,32-015,00-940",)"
R"("posturl":"http:
R"("languages":"pl~de~csb~lt")"
"}"},
{"PM", "{"
R"("fmt":"%O%n%N%n%A%n%Z %C %X",)"
R"("require":"ACZ",)"
R"("zipex":"97500",)"
R"("languages":"fr")"
"}"},
{"PN", "{"
R"("fmt":"%N%n%O%n%A%n%C%n%Z",)"
R | #include "region_data_constants.h"
#include <algorithm>
#include <string>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::RegionDataConstants;
class RegionCodeTest : public testing::TestWithParam<std::string> {
public:
RegionCodeTest(const RegionCodeTest&) = delete;
RegionCodeTest& operator=(const RegionCodeTest&) = delete;
protected:
RegionCodeTest() = default;
};
TEST_P(RegionCodeTest, RegionCodeHasTwoCharacters) {
EXPECT_EQ(2, GetParam().length());
}
INSTANTIATE_TEST_SUITE_P(
AllRegionCodes, RegionCodeTest,
testing::ValuesIn(RegionDataConstants::GetRegionCodes()));
testing::AssertionResult HasCurlyBraces(const std::string& data) {
if (data.empty()) {
return testing::AssertionFailure() << "data is empty";
}
if (data[0] != '{') {
return testing::AssertionFailure() << data << " does not start with '{'";
}
if (data[data.length() - 1] != '}') {
return testing::AssertionFailure() << data << " does not end with '}'";
}
return testing::AssertionSuccess();
}
TEST(DefaultRegionDataTest, DefaultRegionHasCurlyBraces) {
EXPECT_TRUE(HasCurlyBraces(RegionDataConstants::GetDefaultRegionData()));
}
class RegionDataTest : public testing::TestWithParam<std::string> {
public:
RegionDataTest(const RegionDataTest&) = delete;
RegionDataTest& operator=(const RegionDataTest&) = delete;
protected:
RegionDataTest() = default;
std::string GetData() const {
return RegionDataConstants::GetRegionData(GetParam());
}
};
TEST_P(RegionDataTest, RegionDataHasCurlyBraces) {
EXPECT_TRUE(HasCurlyBraces(GetData()));
}
INSTANTIATE_TEST_SUITE_P(
AllRegionData, RegionDataTest,
testing::ValuesIn(RegionDataConstants::GetRegionCodes()));
TEST(RegionDataConstantsTest, GetMaxLookupKeyDepth) {
EXPECT_EQ(0, RegionDataConstants::GetMaxLookupKeyDepth("NZ"));
EXPECT_EQ(1, RegionDataConstants::GetMaxLookupKeyDepth("KY"));
EXPECT_EQ(2, RegionDataConstants::GetMaxLookupKeyDepth("US"));
EXPECT_EQ(3, RegionDataConstants::GetMaxLookupKeyDepth("CN"));
}
TEST(RegionDataConstantsTest, RegionCodesSorted) {
EXPECT_TRUE(std::is_sorted(RegionDataConstants::GetRegionCodes().begin(),
RegionDataConstants::GetRegionCodes().end()));
}
} |
481 | cpp | google/libaddressinput | localization | cpp/src/localization.cc | cpp/test/localization_test.cc | #ifndef I18N_ADDRESSINPUT_LOCALIZATION_H_
#define I18N_ADDRESSINPUT_LOCALIZATION_H_
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <string>
namespace i18n {
namespace addressinput {
struct AddressData;
class Localization {
public:
Localization(const Localization&) = delete;
Localization& operator=(const Localization&) = delete;
Localization();
~Localization() = default;
std::string GetString(int message_id) const;
std::string GetErrorMessage(const AddressData& address,
AddressField field,
AddressProblem problem,
bool enable_examples,
bool enable_links) const;
void SetGetter(std::string (*getter)(int));
private:
std::string GetErrorMessageForPostalCode(
AddressProblem problem,
bool uses_postal_code_as_label,
const std::string& postal_code_example,
const std::string& post_service_url) const;
std::string (*get_string_)(int);
};
}
}
#endif
#include <libaddressinput/localization.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <cassert>
#include <cstddef>
#include <string>
#include <vector>
#include "messages.h"
#include "region_data_constants.h"
#include "rule.h"
#include "util/string_split.h"
#include "util/string_util.h"
namespace {
void PushBackUrl(const std::string& url, std::vector<std::string>* parameters) {
assert(parameters != nullptr);
parameters->push_back("<a href=\"" + url + "\">");
parameters->emplace_back("</a>");
}
}
namespace i18n {
namespace addressinput {
namespace {
#include "en_messages.cc"
std::string GetEnglishString(int message_id) {
const char* str = GetString(message_id);
return str != nullptr ? std::string(str) : std::string();
}
}
Localization::Localization() : get_string_(&GetEnglishString) {}
std::string Localization::GetString(int message_id) const {
return get_string_(message_id);
}
std::string Localization::GetErrorMessage(const AddressData& address,
AddressField field,
AddressProblem problem,
bool enable_examples,
bool enable_links) const {
if (field == POSTAL_CODE) {
Rule rule;
rule.CopyFrom(Rule::GetDefault());
std::string postal_code_example, post_service_url;
if (rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(address.region_code))) {
if (enable_examples) {
std::vector<std::string> examples_list;
SplitString(rule.GetPostalCodeExample(), ',', &examples_list);
if (!examples_list.empty()) {
postal_code_example = examples_list.front();
}
}
if (enable_links) {
post_service_url = rule.GetPostServiceUrl();
}
} else {
assert(false);
}
bool uses_postal_code_as_label =
rule.GetPostalCodeNameMessageId() ==
IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL;
return GetErrorMessageForPostalCode(problem, uses_postal_code_as_label,
postal_code_example, post_service_url);
} else {
if (problem == MISSING_REQUIRED_FIELD) {
return get_string_(IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD);
} else if (problem == UNKNOWN_VALUE) {
std::vector<std::string> parameters;
if (AddressData::IsRepeatedFieldValue(field)) {
const auto& values = address.GetRepeatedFieldValue(field);
assert(!values.empty());
parameters.push_back(values.front());
} else {
parameters.push_back(address.GetFieldValue(field));
}
return DoReplaceStringPlaceholders(
get_string_(IDS_LIBADDRESSINPUT_UNKNOWN_VALUE), parameters);
} else if (problem == USES_P_O_BOX) {
return get_string_(IDS_LIBADDRESSINPUT_PO_BOX_FORBIDDEN_VALUE);
} else {
assert(false);
return "";
}
}
}
void Localization::SetGetter(std::string (*getter)(int)) {
assert(getter != nullptr);
get_string_ = getter;
}
std::string Localization::GetErrorMessageForPostalCode(
AddressProblem problem,
bool uses_postal_code_as_label,
const std::string& postal_code_example,
const std::string& post_service_url) const {
int message_id;
std::vector<std::string> parameters;
if (problem == MISSING_REQUIRED_FIELD) {
if (!postal_code_example.empty() && !post_service_url.empty()) {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE_AND_URL :
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE_AND_URL;
parameters.push_back(postal_code_example);
PushBackUrl(post_service_url, ¶meters);
} else if (!postal_code_example.empty()) {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE :
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE;
parameters.push_back(postal_code_example);
} else {
message_id = IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD;
}
return DoReplaceStringPlaceholders(get_string_(message_id), parameters);
} else if (problem == INVALID_FORMAT) {
if (!postal_code_example.empty() && !post_service_url.empty()) {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE_AND_URL :
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE_AND_URL;
parameters.push_back(postal_code_example);
PushBackUrl(post_service_url, ¶meters);
} else if (!postal_code_example.empty()) {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE :
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE;
parameters.push_back(postal_code_example);
} else {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE :
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP;
}
return DoReplaceStringPlaceholders(get_string_(message_id), parameters);
} else if (problem == MISMATCHING_VALUE) {
if (!post_service_url.empty()) {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE_URL :
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP_URL;
PushBackUrl(post_service_url, ¶meters);
} else {
message_id = uses_postal_code_as_label ?
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE :
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP;
}
return DoReplaceStringPlaceholders(get_string_(message_id), parameters);
} else {
assert(false);
return "";
}
}
}
} | #include <libaddressinput/localization.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "grit.h"
#include "messages.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressField;
using i18n::addressinput::INVALID_MESSAGE_ID;
using i18n::addressinput::Localization;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::ADMIN_AREA;
using i18n::addressinput::LOCALITY;
using i18n::addressinput::DEPENDENT_LOCALITY;
using i18n::addressinput::SORTING_CODE;
using i18n::addressinput::POSTAL_CODE;
using i18n::addressinput::STREET_ADDRESS;
using i18n::addressinput::ORGANIZATION;
using i18n::addressinput::RECIPIENT;
using i18n::addressinput::MISSING_REQUIRED_FIELD;
using i18n::addressinput::UNKNOWN_VALUE;
using i18n::addressinput::INVALID_FORMAT;
using i18n::addressinput::MISMATCHING_VALUE;
using i18n::addressinput::USES_P_O_BOX;
class LocalizationTest : public testing::TestWithParam<int> {
public:
LocalizationTest(const LocalizationTest&) = delete;
LocalizationTest& operator=(const LocalizationTest&) = delete;
protected:
LocalizationTest() = default;
Localization localization_;
};
const char kValidMessage[] = "Data";
std::string GetValidMessage(int message_id) { return kValidMessage; }
TEST_P(LocalizationTest, ValidStringGetterCanBeUsed) {
localization_.SetGetter(&GetValidMessage);
EXPECT_EQ(kValidMessage, localization_.GetString(GetParam()));
}
TEST_P(LocalizationTest, DefaultStringIsNotEmpty) {
EXPECT_FALSE(localization_.GetString(GetParam()).empty());
}
TEST_P(LocalizationTest, NoNewline) {
EXPECT_EQ(std::string::npos, localization_.GetString(GetParam()).find('\n'));
}
TEST_P(LocalizationTest, NoDoubleSpace) {
EXPECT_EQ(std::string::npos,
localization_.GetString(GetParam()).find(std::string(2U, ' ')));
}
INSTANTIATE_TEST_SUITE_P(
AllMessages, LocalizationTest,
testing::Values(
IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL,
IDS_LIBADDRESSINPUT_LOCALITY_LABEL,
IDS_LIBADDRESSINPUT_ADDRESS_LINE_1_LABEL,
IDS_LIBADDRESSINPUT_PIN_CODE_LABEL,
IDS_LIBADDRESSINPUT_POSTAL_CODE_LABEL,
IDS_LIBADDRESSINPUT_ZIP_CODE_LABEL, IDS_LIBADDRESSINPUT_AREA,
IDS_LIBADDRESSINPUT_COUNTY, IDS_LIBADDRESSINPUT_DEPARTMENT,
IDS_LIBADDRESSINPUT_DISTRICT, IDS_LIBADDRESSINPUT_DO_SI,
IDS_LIBADDRESSINPUT_EMIRATE, IDS_LIBADDRESSINPUT_ISLAND,
IDS_LIBADDRESSINPUT_PARISH, IDS_LIBADDRESSINPUT_PREFECTURE,
IDS_LIBADDRESSINPUT_PROVINCE, IDS_LIBADDRESSINPUT_STATE,
IDS_LIBADDRESSINPUT_ORGANIZATION_LABEL,
IDS_LIBADDRESSINPUT_RECIPIENT_LABEL,
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD,
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE_AND_URL,
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_POSTAL_CODE_EXAMPLE,
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE_AND_URL,
IDS_LIBADDRESSINPUT_MISSING_REQUIRED_ZIP_CODE_EXAMPLE,
IDS_LIBADDRESSINPUT_UNKNOWN_VALUE,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE_AND_URL,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE_EXAMPLE,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_POSTAL_CODE,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE_AND_URL,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP_CODE_EXAMPLE,
IDS_LIBADDRESSINPUT_UNRECOGNIZED_FORMAT_ZIP,
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE_URL,
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_POSTAL_CODE,
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP_URL,
IDS_LIBADDRESSINPUT_MISMATCHING_VALUE_ZIP,
IDS_LIBADDRESSINPUT_PO_BOX_FORBIDDEN_VALUE));
TEST_F(LocalizationTest, InvalidMessageIsEmptyString) {
EXPECT_TRUE(localization_.GetString(INVALID_MESSAGE_ID).empty());
}
TEST(LocalizationGetErrorMessageTest, MissingRequiredPostalCode) {
Localization localization;
const AddressData address{.region_code = "CH"};
EXPECT_EQ("You must provide a postal code, for example 2544."
" Don't know your postal code? Find it out"
" <a href=\"http:
"here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, true, true));
EXPECT_EQ("You must provide a postal code, for example 2544.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, true, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, false, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, false, true));
}
TEST(LocalizationGetErrorMessageTest, MissingRequiredZipCode) {
Localization localization;
const AddressData address{.region_code = "US"};
EXPECT_EQ("You must provide a ZIP code, for example 95014."
" Don't know your ZIP code? Find it out"
" <a href=\"https:
"input.action\">here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, true, true));
EXPECT_EQ("You must provide a ZIP code, for example 95014.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, true, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, false, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISSING_REQUIRED_FIELD, false, true));
}
TEST(LocalizationGetErrorMessageTest, MissingRequiredOtherFields) {
Localization localization;
const AddressData address{.region_code = "US"};
const std::vector<AddressField> other_fields{
COUNTRY,
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
STREET_ADDRESS,
ORGANIZATION,
RECIPIENT,
};
for (AddressField field : other_fields) {
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(
address, field, MISSING_REQUIRED_FIELD, true, true));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(
address, field, MISSING_REQUIRED_FIELD, true, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(
address, field, MISSING_REQUIRED_FIELD, false, false));
EXPECT_EQ("You can't leave this empty.",
localization.GetErrorMessage(
address, field, MISSING_REQUIRED_FIELD, false, true));
}
}
TEST(LocalizationGetErrorMessageTest, UnknownValueOtherFields) {
Localization localization;
const AddressData address{
.region_code = "US",
.address_line{
"bad address line 1",
"bad address line 2",
},
.administrative_area = "bad admin area",
.locality = "bad locality",
.dependent_locality = "bad dependent locality",
.sorting_code = "bad sorting code",
.organization = "bad organization",
.recipient = "bad recipient",
};
EXPECT_EQ("US "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, COUNTRY, UNKNOWN_VALUE, true, true));
EXPECT_EQ("US "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, COUNTRY, UNKNOWN_VALUE, true, false));
EXPECT_EQ("US "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, COUNTRY, UNKNOWN_VALUE, false, false));
EXPECT_EQ("US "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, COUNTRY, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad admin area "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ADMIN_AREA, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad admin area "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ADMIN_AREA, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad admin area "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ADMIN_AREA, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad admin area "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ADMIN_AREA, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, LOCALITY, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, LOCALITY, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, LOCALITY, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, LOCALITY, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad dependent locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad dependent locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad dependent locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad dependent locality "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, DEPENDENT_LOCALITY, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad sorting code "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, SORTING_CODE, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad sorting code "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, SORTING_CODE, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad sorting code "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, SORTING_CODE, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad sorting code "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, SORTING_CODE, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad address line 1 "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, STREET_ADDRESS, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad address line 1 "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, STREET_ADDRESS, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad address line 1 "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, STREET_ADDRESS, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad address line 1 "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, STREET_ADDRESS, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad organization "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ORGANIZATION, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad organization "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ORGANIZATION, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad organization "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ORGANIZATION, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad organization "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, ORGANIZATION, UNKNOWN_VALUE, false, true));
EXPECT_EQ("bad recipient "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, RECIPIENT, UNKNOWN_VALUE, true, true));
EXPECT_EQ("bad recipient "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, RECIPIENT, UNKNOWN_VALUE, true, false));
EXPECT_EQ("bad recipient "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, RECIPIENT, UNKNOWN_VALUE, false, false));
EXPECT_EQ("bad recipient "
"is not recognized as a known value for this field.",
localization.GetErrorMessage(
address, RECIPIENT, UNKNOWN_VALUE, false, true));
}
TEST(LocalizationGetErrorMessageTest, InvalidFormatPostalCode) {
Localization localization;
const AddressData address{.region_code = "CH"};
EXPECT_EQ("This postal code format is not recognized. Example "
"of a valid postal code: 2544."
" Don't know your postal code? Find it out"
" <a href=\"http:
"here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, true, true));
EXPECT_EQ("This postal code format is not recognized. Example "
"of a valid postal code: 2544.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, true, false));
EXPECT_EQ("This postal code format is not recognized.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, false, false));
EXPECT_EQ("This postal code format is not recognized.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, false, true));
}
TEST(LocalizationGetErrorMessageTest, InvalidFormatZipCode) {
Localization localization;
const AddressData address{.region_code = "US"};
EXPECT_EQ("This ZIP code format is not recognized. Example of "
"a valid ZIP code: 95014."
" Don't know your ZIP code? Find it out"
" <a href=\"https:
"input.action\">here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, true, true));
EXPECT_EQ("This ZIP code format is not recognized. Example of "
"a valid ZIP code: 95014.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, true, false));
EXPECT_EQ("This ZIP code format is not recognized.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, false, false));
EXPECT_EQ("This ZIP code format is not recognized.",
localization.GetErrorMessage(address, POSTAL_CODE,
INVALID_FORMAT, false, true));
}
TEST(LocalizationGetErrorMessageTest, MismatchingValuePostalCode) {
Localization localization;
const AddressData address{.region_code = "CH"};
EXPECT_EQ("This postal code does not appear to match the rest "
"of this address."
" Don't know your postal code? Find it out"
" <a href=\"http:
"here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, true, true));
EXPECT_EQ("This postal code does not appear to match the rest "
"of this address.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, true, false));
EXPECT_EQ("This postal code does not appear to match the rest "
"of this address.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, false, false));
EXPECT_EQ("This postal code does not appear to match the rest "
"of this address."
" Don't know your postal code? Find it out"
" <a href=\"http:
"here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, false, true));
}
TEST(LocalizationGetErrorMessageTest, MismatchingValueZipCode) {
Localization localization;
const AddressData address{.region_code = "US"};
EXPECT_EQ("This ZIP code does not appear to match the rest of "
"this address."
" Don't know your ZIP code? Find it out"
" <a href=\"https:
"input.action\">here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, true, true));
EXPECT_EQ("This ZIP code does not appear to match the rest of "
"this address.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, true, false));
EXPECT_EQ("This ZIP code does not appear to match the rest of "
"this address.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, false, false));
EXPECT_EQ("This ZIP code does not appear to match the rest of "
"this address."
" Don't know your ZIP code? Find it out"
" <a href=\"https:
"input.action\">here</a>.",
localization.GetErrorMessage(address, POSTAL_CODE,
MISMATCHING_VALUE, false, true));
}
TEST(LocalizationGetErrorMessageTest, UsesPOBoxOtherFields) {
Localization localization;
const AddressData address{.region_code = "US"};
const std::vector<AddressField> other_fields{
COUNTRY,
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
STREET_ADDRESS,
ORGANIZATION,
RECIPIENT,
};
for (AddressField field : other_fields) {
EXPECT_EQ("This address line appears to contain a post "
"office box. Please use a street"
" or building address.",
localization.GetErrorMessage(
address, field, USES_P_O_BOX, true, true));
EXPECT_EQ("This address line appears to contain a post "
"office box. Please use a street"
" or building address.",
localization.GetErrorMessage(
address, field, USES_P_O_BOX, true, false));
EXPECT_EQ("This address line appears to contain a post "
"office box. Please use a street"
" or building address.",
localization.GetErrorMessage(
address, field, USES_P_O_BOX, false, false));
EXPECT_EQ("This address line appears to contain a post "
"office box. Please use a street"
" or building address.",
localization.GetErrorMessage(
address, field, USES_P_O_BOX, false, true));
}
}
} |
482 | cpp | google/libaddressinput | region_data | cpp/src/region_data.cc | cpp/test/region_data_test.cc | #ifndef I18N_ADDRESSINPUT_REGION_DATA_H_
#define I18N_ADDRESSINPUT_REGION_DATA_H_
#include <cassert>
#include <cstddef>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
class RegionData {
public:
RegionData(const RegionData&) = delete;
RegionData& operator=(const RegionData&) = delete;
explicit RegionData(const std::string& region_code);
~RegionData();
RegionData* AddSubRegion(const std::string& key, const std::string& name);
const std::string& key() const { return key_; }
const std::string& name() const { return name_; }
bool has_parent() const { return parent_ != nullptr; }
const RegionData& parent() const {
assert(parent_ != nullptr);
return *parent_;
}
const std::vector<const RegionData*>& sub_regions() const {
return sub_regions_;
}
private:
RegionData(const std::string& key,
const std::string& name,
RegionData* parent);
const std::string& key_;
const std::string& name_;
const RegionData* const parent_;
std::vector<const RegionData*> sub_regions_;
};
}
}
#endif
#include <libaddressinput/region_data.h>
#include <cstddef>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
RegionData::RegionData(const std::string& region_code)
: key_(region_code),
name_(region_code),
parent_(nullptr),
sub_regions_() {}
RegionData::~RegionData() {
for (auto ptr : sub_regions_) {
delete ptr;
}
}
RegionData* RegionData::AddSubRegion(const std::string& key,
const std::string& name) {
auto* sub_region = new RegionData(key, name, this);
sub_regions_.push_back(sub_region);
return sub_region;
}
RegionData::RegionData(const std::string& key,
const std::string& name,
RegionData* parent)
: key_(key), name_(name), parent_(parent), sub_regions_() {}
}
} | #include <libaddressinput/region_data.h>
#include <cstddef>
#include <string>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::RegionData;
TEST(RegionDataTest, NoParentByDefault) {
static const std::string kEmpty;
RegionData region(kEmpty);
EXPECT_FALSE(region.has_parent());
}
TEST(RegionDataTest, NoSubRegionsByDefault) {
static const std::string kEmpty;
RegionData region(kEmpty);
EXPECT_TRUE(region.sub_regions().empty());
}
TEST(RegionDataTest, SubRegionGetsParent) {
static const std::string kEmpty;
RegionData region(kEmpty);
region.AddSubRegion(kEmpty, kEmpty);
ASSERT_EQ(1U, region.sub_regions().size());
ASSERT_TRUE(region.sub_regions()[0] != nullptr);
EXPECT_EQ(®ion, ®ion.sub_regions()[0]->parent());
}
} |
483 | cpp | google/libaddressinput | rule_retriever | cpp/src/rule_retriever.cc | cpp/test/rule_retriever_test.cc | #ifndef I18N_ADDRESSINPUT_RULE_RETRIEVER_H_
#define I18N_ADDRESSINPUT_RULE_RETRIEVER_H_
#include <libaddressinput/callback.h>
#include <memory>
#include <string>
namespace i18n {
namespace addressinput {
class Retriever;
class Rule;
class RuleRetriever {
public:
using Callback =
i18n::addressinput::Callback<const std::string&, const Rule&>;
RuleRetriever(const RuleRetriever&) = delete;
RuleRetriever& operator=(const RuleRetriever&) = delete;
explicit RuleRetriever(const Retriever* retriever);
~RuleRetriever();
void RetrieveRule(const std::string& key, const Callback& rule_ready) const;
private:
std::unique_ptr<const Retriever> data_retriever_;
};
}
}
#endif
#include "rule_retriever.h"
#include <libaddressinput/callback.h>
#include <cassert>
#include <cstddef>
#include <memory>
#include <string>
#include "retriever.h"
#include "rule.h"
namespace i18n {
namespace addressinput {
namespace {
class Helper {
public:
Helper(const Helper&) = delete;
Helper& operator=(const Helper&) = delete;
Helper(const std::string& key,
const RuleRetriever::Callback& rule_ready,
const Retriever& data_retriever)
: rule_ready_(rule_ready),
data_retrieved_(BuildCallback(this, &Helper::OnDataRetrieved)) {
data_retriever.Retrieve(key, *data_retrieved_);
}
private:
~Helper() = default;
void OnDataRetrieved(bool success,
const std::string& key,
const std::string& data) {
Rule rule;
if (!success) {
rule_ready_(false, key, rule);
} else {
success = rule.ParseSerializedRule(data);
rule_ready_(success, key, rule);
}
delete this;
}
const RuleRetriever::Callback& rule_ready_;
const std::unique_ptr<const Retriever::Callback> data_retrieved_;
};
}
RuleRetriever::RuleRetriever(const Retriever* retriever)
: data_retriever_(retriever) {
assert(data_retriever_ != nullptr);
}
RuleRetriever::~RuleRetriever() = default;
void RuleRetriever::RetrieveRule(const std::string& key,
const Callback& rule_ready) const {
new Helper(key, rule_ready, *data_retriever_);
}
}
} | #include "rule_retriever.h"
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "retriever.h"
#include "rule.h"
#include "testdata_source.h"
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::Retriever;
using i18n::addressinput::Rule;
using i18n::addressinput::RuleRetriever;
using i18n::addressinput::TestdataSource;
class RuleRetrieverTest : public testing::Test {
public:
RuleRetrieverTest(const RuleRetrieverTest&) = delete;
RuleRetrieverTest& operator=(const RuleRetrieverTest&) = delete;
protected:
RuleRetrieverTest()
: rule_retriever_(
new Retriever(new TestdataSource(false), new NullStorage)),
success_(false),
key_(),
rule_(),
rule_ready_(BuildCallback(this, &RuleRetrieverTest::OnRuleReady)) {}
RuleRetriever rule_retriever_;
bool success_;
std::string key_;
Rule rule_;
const std::unique_ptr<const RuleRetriever::Callback> rule_ready_;
private:
void OnRuleReady(bool success,
const std::string& key,
const Rule& rule) {
success_ = success;
key_ = key;
rule_.CopyFrom(rule);
}
};
TEST_F(RuleRetrieverTest, ExistingRule) {
static const char kExistingKey[] = "data/CA";
rule_retriever_.RetrieveRule(kExistingKey, *rule_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kExistingKey, key_);
EXPECT_FALSE(rule_.GetFormat().empty());
}
TEST_F(RuleRetrieverTest, MissingRule) {
static const char kMissingKey[] = "junk";
rule_retriever_.RetrieveRule(kMissingKey, *rule_ready_);
EXPECT_TRUE(success_);
EXPECT_EQ(kMissingKey, key_);
EXPECT_TRUE(rule_.GetFormat().empty());
}
} |
484 | cpp | google/libaddressinput | post_box_matchers | cpp/src/post_box_matchers.cc | cpp/test/post_box_matchers_test.cc | #ifndef I18N_ADDRESSINPUT_POST_BOX_MATCHERS_H_
#define I18N_ADDRESSINPUT_POST_BOX_MATCHERS_H_
#include <vector>
namespace i18n {
namespace addressinput {
class Rule;
struct RE2PlainPtr;
class PostBoxMatchers {
public:
static std::vector<const RE2PlainPtr*> GetMatchers(const Rule& country_rule);
PostBoxMatchers(const PostBoxMatchers&) = delete;
PostBoxMatchers& operator=(const PostBoxMatchers&) = delete;
};
}
}
#endif
#include "post_box_matchers.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <string>
#include <vector>
#include <re2/re2.h>
#include "language.h"
#include "rule.h"
#include "util/re2ptr.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
struct LanguageInfo {
const char* language;
const char* regexp;
static bool less(const LanguageInfo& a, const LanguageInfo& b) {
return strcmp(a.language, b.language) < 0;
}
};
constexpr const LanguageInfo kLanguageInfoMap[] = {
{"ar", R"(صندوق بريد|ص[-. ]ب)"},
{"cs", R"((?i)p\.? ?p\.? \d)"},
{"da", R"((?i)Postboks)"},
{"de", R"((?i)Postfach)"},
{"el", R"((?i)T\.? ?Θ\.? \d{2})"},
{"en", R"(Private Bag|Post(?:al)? Box)"},
{"es", R"((?i)(?:Apartado|Casillas) de correos?)"},
{"fi", R"((?i)Postilokero|P\.?L\.? \d)"},
{"fr", R"((?i)Bo(?:[iî]|î)te Postale|BP \d|CEDEX \d)"},
{"hr", R"((?i)p\.? ?p\.? \d)"},
{"hu", R"((?i)Postafi(?:[oó]|ó)k|Pf\.? \d)"},
{"ja", R"(私書箱\d{1,5}号)"},
{"nl", R"((?i)Postbus)"},
{"no", R"((?i)Postboks)"},
{"pl", R"((?i)Skr(?:\.?|ytka) poczt(?:\.?|owa))"},
{"pt", R"((?i)Apartado)"},
{"ru", R"((?i)абонентский ящик|[аa]"я (?:(?:№|#|N) ?)?\d)"},
{"sv", R"((?i)Box \d)"},
{"und", R"(P\.? ?O\.? Box)"},
{"zh", R"(郵政信箱.{1,5}號|郵局第.{1,10}號信箱)"},
};
constexpr size_t kLanguageInfoMapSize = size(kLanguageInfoMap);
constexpr bool StrLessOrEqualConstexpr(const char* a, const char* b) {
return (*a == '\0') ? true : (
(*a == *b) ? StrLessOrEqualConstexpr(a + 1, b + 1) : (*a < *b));
}
static_assert(StrLessOrEqualConstexpr("", ""), "");
static_assert(StrLessOrEqualConstexpr("", "foo"), "");
static_assert(!StrLessOrEqualConstexpr("foo", ""), "");
static_assert(StrLessOrEqualConstexpr("foo", "foo"), "");
static_assert(!StrLessOrEqualConstexpr("foo", "bar"), "");
static_assert(StrLessOrEqualConstexpr("bar", "foo"), "");
static_assert(StrLessOrEqualConstexpr("foo", "foobar"), "");
static_assert(!StrLessOrEqualConstexpr("foobar", "foo"), "");
constexpr bool CheckLanguageInfoMapOrderConstexpr(size_t n = 0) {
return !StrLessOrEqualConstexpr(kLanguageInfoMap[n].language,
kLanguageInfoMap[n + 1].language) ? false : (
(n + 2 < kLanguageInfoMapSize) ?
CheckLanguageInfoMapOrderConstexpr(n + 1) : true);
}
static_assert(CheckLanguageInfoMapOrderConstexpr(),
"kLanguageInfoMap is not correctly sorted!");
const LanguageInfo* FindLanguageInfoFor(const std::string& language) {
const LanguageInfo* begin = kLanguageInfoMap;
const LanguageInfo* end = begin + kLanguageInfoMapSize;
LanguageInfo key = { language.c_str(), };
const LanguageInfo* probe =
std::lower_bound(begin, end, key, LanguageInfo::less);
if (probe != end && language == probe->language) {
return probe;
}
return nullptr;
}
class StaticRE2Array {
public:
StaticRE2Array() {
for (size_t n = 0; n < kLanguageInfoMapSize; ++n) {
re2s_[n].ptr = new RE2(kLanguageInfoMap[n].regexp);
}
}
~StaticRE2Array() {
for (auto& entry : re2s_) {
delete entry.ptr;
}
}
const RE2PlainPtr* FindMatcherFor(const std::string& language) const {
const LanguageInfo* info = FindLanguageInfoFor(language);
if (!info) {
return nullptr;
}
size_t idx = info - kLanguageInfoMap;
assert(idx < kLanguageInfoMapSize);
return &re2s_[idx];
}
private:
RE2PlainPtr re2s_[kLanguageInfoMapSize];
};
}
std::vector<const RE2PlainPtr*> PostBoxMatchers::GetMatchers(
const Rule& country_rule) {
static const StaticRE2Array kMatchers;
std::vector<std::string> languages{"und"};
for (const auto& language_tag : country_rule.GetLanguages()) {
Language language(language_tag);
languages.push_back(language.base);
}
std::vector<const RE2PlainPtr*> result;
for (const auto& language_tag : languages) {
const RE2PlainPtr* matcher = kMatchers.FindMatcherFor(language_tag);
if (matcher != nullptr) {
result.push_back(matcher);
}
}
return result;
}
}
} | #include "post_box_matchers.h"
#include <gtest/gtest.h>
#include "rule.h"
namespace {
using i18n::addressinput::PostBoxMatchers;
using i18n::addressinput::Rule;
TEST(PostBoxMatchersTest, AlwaysGetMatcherForLanguageUnd) {
Rule rule;
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(1, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
}
TEST(PostBoxMatchersTest, NoMatcherForInvalidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(1, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
}
TEST(PostBoxMatchersTest, HasMatcherForValidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, MixValidAndInvalidLanguage) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"xx~sv\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, UseBaseLanguageForMatching) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"sv-SE\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
TEST(PostBoxMatchersTest, LenientLanguageTagParsing) {
Rule rule;
ASSERT_TRUE(rule.ParseSerializedRule("{\"languages\":\"SV_SE\"}"));
const auto& matchers = PostBoxMatchers::GetMatchers(rule);
EXPECT_EQ(2, matchers.size());
EXPECT_TRUE(matchers[0] != nullptr);
EXPECT_TRUE(matchers[1] != nullptr);
}
} |
485 | cpp | google/libaddressinput | address_field | cpp/src/address_field.cc | cpp/test/address_field_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_FIELD_H_
#define I18N_ADDRESSINPUT_ADDRESS_FIELD_H_
#include <iosfwd>
namespace i18n {
namespace addressinput {
enum AddressField {
COUNTRY,
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
POSTAL_CODE,
STREET_ADDRESS,
ORGANIZATION,
RECIPIENT
};
}
}
std::ostream& operator<<(std::ostream& o,
i18n::addressinput::AddressField field);
#endif
#include <libaddressinput/address_field.h>
#include <cstddef>
#include <ostream>
#include "util/size.h"
using i18n::addressinput::AddressField;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::RECIPIENT;
using i18n::addressinput::size;
std::ostream& operator<<(std::ostream& o, AddressField field) {
static const char* const kFieldNames[] = {
"COUNTRY",
"ADMIN_AREA",
"LOCALITY",
"DEPENDENT_LOCALITY",
"SORTING_CODE",
"POSTAL_CODE",
"STREET_ADDRESS",
"ORGANIZATION",
"RECIPIENT",
};
static_assert(COUNTRY == 0, "bad_base");
static_assert(RECIPIENT == size(kFieldNames) - 1, "bad_length");
if (field < 0 || static_cast<size_t>(field) >= size(kFieldNames)) {
o << "[INVALID ENUM VALUE " << static_cast<int>(field) << "]";
} else {
o << kFieldNames[field];
}
return o;
} | #include <libaddressinput/address_field.h>
#include <sstream>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::SORTING_CODE;
TEST(AddressFieldTest, ValidEnumValue) {
std::ostringstream oss;
oss << SORTING_CODE;
EXPECT_EQ("SORTING_CODE", oss.str());
}
} |
486 | cpp | google/libaddressinput | region_data_builder | cpp/src/region_data_builder.cc | cpp/test/region_data_builder_test.cc | #ifndef I18N_ADDRESSINPUT_REGION_DATA_BUILDER_H_
#define I18N_ADDRESSINPUT_REGION_DATA_BUILDER_H_
#include <map>
#include <string>
namespace i18n {
namespace addressinput {
class PreloadSupplier;
class RegionData;
class RegionDataBuilder {
public:
RegionDataBuilder(const RegionDataBuilder&) = delete;
RegionDataBuilder& operator=(const RegionDataBuilder&) = delete;
explicit RegionDataBuilder(PreloadSupplier* supplier);
~RegionDataBuilder();
const RegionData& Build(const std::string& region_code,
const std::string& ui_language_tag,
std::string* best_region_tree_language_tag);
private:
using LanguageRegionMap = std::map<std::string, const RegionData*>;
using RegionCodeDataMap = std::map<std::string, LanguageRegionMap*>;
PreloadSupplier* const supplier_;
RegionCodeDataMap cache_;
};
}
}
#endif
#include <libaddressinput/region_data_builder.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/preload_supplier.h>
#include <libaddressinput/region_data.h>
#include <cassert>
#include <cstddef>
#include <string>
#include <vector>
#include "language.h"
#include "lookup_key.h"
#include "region_data_constants.h"
#include "rule.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
const size_t kLookupKeysMaxDepth = size(LookupKey::kHierarchy) - 1;
void BuildRegionTreeRecursively(
const std::map<std::string, const Rule*>& rules,
std::map<std::string, const Rule*>::const_iterator hint,
const LookupKey& parent_key,
RegionData* parent_region,
const std::vector<std::string>& keys,
bool prefer_latin_name,
size_t region_max_depth) {
assert(parent_region != nullptr);
LookupKey lookup_key;
for (const auto& key : keys) {
lookup_key.FromLookupKey(parent_key, key);
const std::string lookup_key_string =
lookup_key.ToKeyString(kLookupKeysMaxDepth);
++hint;
if (hint == rules.end() || hint->first != lookup_key_string) {
hint = rules.find(lookup_key_string);
if (hint == rules.end()) {
return;
}
}
const Rule* rule = hint->second;
assert(rule != nullptr);
const std::string& local_name = rule->GetName().empty()
? key : rule->GetName();
const std::string& name =
prefer_latin_name && !rule->GetLatinName().empty()
? rule->GetLatinName() : local_name;
RegionData* region = parent_region->AddSubRegion(key, name);
if (!rule->GetSubKeys().empty() &&
region_max_depth > parent_key.GetDepth()) {
BuildRegionTreeRecursively(rules,
hint,
lookup_key,
region,
rule->GetSubKeys(),
prefer_latin_name,
region_max_depth);
}
}
}
RegionData* BuildRegion(const std::map<std::string, const Rule*>& rules,
const std::string& region_code,
const Language& language) {
AddressData address;
address.region_code = region_code;
LookupKey lookup_key;
lookup_key.FromAddress(address);
auto hint = rules.find(lookup_key.ToKeyString(kLookupKeysMaxDepth));
assert(hint != rules.end());
const Rule* rule = hint->second;
assert(rule != nullptr);
auto* region = new RegionData(region_code);
size_t region_max_depth =
RegionDataConstants::GetMaxLookupKeyDepth(region_code);
if (region_max_depth > 0) {
BuildRegionTreeRecursively(rules,
hint,
lookup_key,
region,
rule->GetSubKeys(),
language.has_latin_script,
region_max_depth);
}
return region;
}
}
RegionDataBuilder::RegionDataBuilder(PreloadSupplier* supplier)
: supplier_(supplier),
cache_() {
assert(supplier_ != nullptr);
}
RegionDataBuilder::~RegionDataBuilder() {
for (const auto& outer : cache_) {
assert(outer.second != nullptr);
for (const auto& inner : *outer.second) {
delete inner.second;
}
delete outer.second;
}
}
const RegionData& RegionDataBuilder::Build(
const std::string& region_code,
const std::string& ui_language_tag,
std::string* best_region_tree_language_tag) {
assert(supplier_->IsLoaded(region_code));
assert(best_region_tree_language_tag != nullptr);
auto region_it = cache_.find(region_code);
if (region_it == cache_.end()) {
region_it = cache_.emplace(region_code, new LanguageRegionMap).first;
}
Rule rule;
rule.ParseSerializedRule(RegionDataConstants::GetRegionData(region_code));
static const Language kUndefinedLanguage("und");
const Language best_language =
rule.GetLanguages().empty()
? kUndefinedLanguage
: ChooseBestAddressLanguage(rule, Language(ui_language_tag));
*best_region_tree_language_tag = best_language.tag;
auto language_it = region_it->second->find(best_language.tag);
if (language_it == region_it->second->end()) {
const auto& rules = supplier_->GetRulesForRegion(region_code);
language_it = region_it->second
->emplace(best_language.tag,
BuildRegion(rules, region_code, best_language))
.first;
}
return *language_it->second;
}
}
} | #include <libaddressinput/region_data_builder.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <libaddressinput/preload_supplier.h>
#include <libaddressinput/region_data.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "testdata_source.h"
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::PreloadSupplier;
using i18n::addressinput::RegionData;
using i18n::addressinput::RegionDataBuilder;
using i18n::addressinput::TestdataSource;
class RegionDataBuilderTest : public testing::Test {
public:
RegionDataBuilderTest(const RegionDataBuilderTest&) = delete;
RegionDataBuilderTest& operator=(const RegionDataBuilderTest&) = delete;
protected:
RegionDataBuilderTest()
: supplier_(new TestdataSource(true),
new NullStorage),
builder_(&supplier_),
loaded_callback_(BuildCallback(this, &RegionDataBuilderTest::OnLoaded)),
best_language_() {}
PreloadSupplier supplier_;
RegionDataBuilder builder_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_callback_;
std::string best_language_;
private:
void OnLoaded(bool success, const std::string& region_code, int num_rules) {
ASSERT_TRUE(success);
ASSERT_FALSE(region_code.empty());
ASSERT_LT(0, num_rules);
ASSERT_TRUE(supplier_.IsLoaded(region_code));
}
};
TEST_F(RegionDataBuilderTest, BuildUsRegionTree) {
supplier_.LoadRules("US", *loaded_callback_);
const RegionData& tree = builder_.Build("US", "en-US", &best_language_);
EXPECT_FALSE(tree.sub_regions().empty());
}
TEST_F(RegionDataBuilderTest, BuildCnRegionTree) {
supplier_.LoadRules("CN", *loaded_callback_);
const RegionData& tree = builder_.Build("CN", "zh-Hans", &best_language_);
ASSERT_FALSE(tree.sub_regions().empty());
EXPECT_FALSE(tree.sub_regions().front()->sub_regions().empty());
}
TEST_F(RegionDataBuilderTest, BuildChRegionTree) {
supplier_.LoadRules("CH", *loaded_callback_);
const RegionData& tree = builder_.Build("CH", "de-CH", &best_language_);
EXPECT_TRUE(tree.sub_regions().empty());
}
TEST_F(RegionDataBuilderTest, BuildZwRegionTree) {
supplier_.LoadRules("ZW", *loaded_callback_);
const RegionData& tree = builder_.Build("ZW", "en-ZW", &best_language_);
EXPECT_TRUE(tree.sub_regions().empty());
}
TEST_F(RegionDataBuilderTest, UsTreeHasStateAbbreviationsAndNames) {
supplier_.LoadRules("US", *loaded_callback_);
const RegionData& tree = builder_.Build("US", "en-US", &best_language_);
EXPECT_EQ("en", best_language_);
ASSERT_FALSE(tree.sub_regions().empty());
EXPECT_EQ("AL", tree.sub_regions().front()->key());
EXPECT_EQ("Alabama", tree.sub_regions().front()->name());
}
TEST_F(RegionDataBuilderTest,
KrWithKoLatnLanguageHasKoreanKeysAndLatinScriptNames) {
supplier_.LoadRules("KR", *loaded_callback_);
const RegionData& tree = builder_.Build("KR", "ko-Latn", &best_language_);
EXPECT_EQ("ko-Latn", best_language_);
ASSERT_FALSE(tree.sub_regions().empty());
EXPECT_EQ("강원도", tree.sub_regions().front()->key());
EXPECT_EQ("Gangwon", tree.sub_regions().front()->name());
}
TEST_F(RegionDataBuilderTest, KrWithKoKrLanguageHasKoreanKeysAndNames) {
supplier_.LoadRules("KR", *loaded_callback_);
const RegionData& tree = builder_.Build("KR", "ko-KR", &best_language_);
EXPECT_EQ("ko", best_language_);
ASSERT_FALSE(tree.sub_regions().empty());
EXPECT_EQ("강원도", tree.sub_regions().front()->key());
EXPECT_EQ("강원", tree.sub_regions().front()->name());
}
} |
487 | cpp | google/libaddressinput | address_data | cpp/src/address_data.cc | cpp/test/address_data_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_DATA_H_
#define I18N_ADDRESSINPUT_ADDRESS_DATA_H_
#include <libaddressinput/address_field.h>
#include <iosfwd>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
struct AddressData {
std::string region_code;
std::vector<std::string> address_line;
std::string administrative_area;
std::string locality;
std::string dependent_locality;
std::string postal_code;
std::string sorting_code;
std::string language_code;
std::string organization;
std::string recipient;
bool IsFieldEmpty(AddressField field) const;
const std::string& GetFieldValue(AddressField field) const;
void SetFieldValue(AddressField field, const std::string& value);
const std::vector<std::string>& GetRepeatedFieldValue(
AddressField field) const;
bool operator==(const AddressData& other) const;
static bool IsRepeatedFieldValue(AddressField field);
};
}
}
std::ostream& operator<<(std::ostream& o,
const i18n::addressinput::AddressData& address);
#endif
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <ostream>
#include <string>
#include <vector>
#include <re2/re2.h>
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
std::string AddressData::*kStringField[] = {
&AddressData::region_code,
&AddressData::administrative_area,
&AddressData::locality,
&AddressData::dependent_locality,
&AddressData::sorting_code,
&AddressData::postal_code,
nullptr,
&AddressData::organization,
&AddressData::recipient,
};
const std::vector<std::string> AddressData::*kVectorStringField[] = {
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
&AddressData::address_line,
nullptr,
nullptr,
};
static_assert(size(kStringField) == size(kVectorStringField),
"field_mapping_array_size_mismatch");
bool IsStringEmpty(const std::string& str) {
static const RE2 kMatcher(R"(\S)");
return str.empty() || !RE2::PartialMatch(str, kMatcher);
}
}
bool AddressData::IsFieldEmpty(AddressField field) const {
assert(field >= 0);
assert(static_cast<size_t>(field) < size(kStringField));
if (kStringField[field] != nullptr) {
const auto& value = GetFieldValue(field);
return IsStringEmpty(value);
} else {
const auto& value = GetRepeatedFieldValue(field);
return std::find_if_not(value.begin(), value.end(), IsStringEmpty) ==
value.end();
}
}
const std::string& AddressData::GetFieldValue(AddressField field) const {
assert(field >= 0);
assert(static_cast<size_t>(field) < size(kStringField));
assert(kStringField[field] != nullptr);
return this->*kStringField[field];
}
void AddressData::SetFieldValue(AddressField field, const std::string& value) {
assert(field >= 0);
assert(static_cast<size_t>(field) < size(kStringField));
assert(kStringField[field] != nullptr);
(this->*kStringField[field]).assign(value);
}
const std::vector<std::string>& AddressData::GetRepeatedFieldValue(
AddressField field) const {
assert(IsRepeatedFieldValue(field));
return this->*kVectorStringField[field];
}
bool AddressData::operator==(const AddressData& other) const {
return region_code == other.region_code &&
address_line == other.address_line &&
administrative_area == other.administrative_area &&
locality == other.locality &&
dependent_locality == other.dependent_locality &&
postal_code == other.postal_code &&
sorting_code == other.sorting_code &&
language_code == other.language_code &&
organization == other.organization &&
recipient == other.recipient;
}
bool AddressData::IsRepeatedFieldValue(AddressField field) {
assert(field >= 0);
assert(static_cast<size_t>(field) < size(kVectorStringField));
return kVectorStringField[field] != nullptr;
}
}
}
std::ostream& operator<<(std::ostream& o,
const i18n::addressinput::AddressData& address) {
o << "region_code: \"" << address.region_code << "\"\n"
"administrative_area: \"" << address.administrative_area << "\"\n"
"locality: \"" << address.locality << "\"\n"
"dependent_locality: \"" << address.dependent_locality << "\"\n"
"postal_code: \"" << address.postal_code << "\"\n"
"sorting_code: \"" << address.sorting_code << "\"\n";
for (const auto& line : address.address_line) {
o << "address_line: \"" << line << "\"\n";
}
o << "language_code: \"" << address.language_code << "\"\n"
"organization: \"" << address.organization << "\"\n"
"recipient: \"" << address.recipient << "\"\n";
return o;
} | #include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <sstream>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressField;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::ADMIN_AREA;
using i18n::addressinput::LOCALITY;
using i18n::addressinput::DEPENDENT_LOCALITY;
using i18n::addressinput::SORTING_CODE;
using i18n::addressinput::POSTAL_CODE;
using i18n::addressinput::STREET_ADDRESS;
using i18n::addressinput::ORGANIZATION;
using i18n::addressinput::RECIPIENT;
TEST(AddressDataTest, GetFieldValue) {
const AddressData address{
.region_code = "rrr",
.administrative_area = "sss",
.locality = "ccc",
.dependent_locality = "ddd",
.postal_code = "zzz",
.sorting_code = "xxx",
.organization = "ooo",
.recipient = "nnn",
};
EXPECT_EQ(address.region_code,
address.GetFieldValue(COUNTRY));
EXPECT_EQ(address.administrative_area,
address.GetFieldValue(ADMIN_AREA));
EXPECT_EQ(address.locality,
address.GetFieldValue(LOCALITY));
EXPECT_EQ(address.dependent_locality,
address.GetFieldValue(DEPENDENT_LOCALITY));
EXPECT_EQ(address.sorting_code,
address.GetFieldValue(SORTING_CODE));
EXPECT_EQ(address.postal_code,
address.GetFieldValue(POSTAL_CODE));
EXPECT_EQ(address.organization,
address.GetFieldValue(ORGANIZATION));
EXPECT_EQ(address.recipient,
address.GetFieldValue(RECIPIENT));
}
TEST(AddressDataTest, GetRepeatedFieldValue) {
const AddressData address{.address_line{
"aaa",
"222",
}};
EXPECT_EQ(address.address_line,
address.GetRepeatedFieldValue(STREET_ADDRESS));
}
TEST(AddressDataTest, IsFieldEmpty) {
AddressData address;
EXPECT_TRUE(address.IsFieldEmpty(COUNTRY));
EXPECT_TRUE(address.IsFieldEmpty(ADMIN_AREA));
EXPECT_TRUE(address.IsFieldEmpty(LOCALITY));
EXPECT_TRUE(address.IsFieldEmpty(DEPENDENT_LOCALITY));
EXPECT_TRUE(address.IsFieldEmpty(SORTING_CODE));
EXPECT_TRUE(address.IsFieldEmpty(POSTAL_CODE));
EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS));
EXPECT_TRUE(address.IsFieldEmpty(ORGANIZATION));
EXPECT_TRUE(address.IsFieldEmpty(RECIPIENT));
address = {
.region_code = "rrr",
.address_line{"aaa"},
.administrative_area = "sss",
.locality = "ccc",
.dependent_locality = "ddd",
.postal_code = "zzz",
.sorting_code = "xxx",
.organization = "ooo",
.recipient = "nnn",
};
EXPECT_FALSE(address.IsFieldEmpty(COUNTRY));
EXPECT_FALSE(address.IsFieldEmpty(ADMIN_AREA));
EXPECT_FALSE(address.IsFieldEmpty(LOCALITY));
EXPECT_FALSE(address.IsFieldEmpty(DEPENDENT_LOCALITY));
EXPECT_FALSE(address.IsFieldEmpty(SORTING_CODE));
EXPECT_FALSE(address.IsFieldEmpty(POSTAL_CODE));
EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS));
EXPECT_FALSE(address.IsFieldEmpty(ORGANIZATION));
EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT));
}
TEST(AddressDataTest, IsFieldEmptyWhitespace) {
AddressData address;
address.recipient = " ";
EXPECT_TRUE(address.IsFieldEmpty(RECIPIENT));
address.recipient = "abc";
EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT));
address.recipient = " b ";
EXPECT_FALSE(address.IsFieldEmpty(RECIPIENT));
}
TEST(AddressDataTest, IsFieldEmptyVector) {
AddressData address;
EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS));
address.address_line.emplace_back("");
EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS));
address.address_line.emplace_back("aaa");
EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS));
address.address_line.emplace_back("");
EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS));
}
TEST(AddressDataTest, IsFieldEmptyVectorWhitespace) {
AddressData address{.address_line{
" ",
" ",
" ",
}};
EXPECT_TRUE(address.IsFieldEmpty(STREET_ADDRESS));
address.address_line = {
"abc",
};
EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS));
address.address_line = {
" ",
" b ",
" ",
};
EXPECT_FALSE(address.IsFieldEmpty(STREET_ADDRESS));
}
TEST(AddressDataTest, StreamFunction) {
std::ostringstream oss;
const AddressData address{
.region_code = "R",
.address_line{
"Line 1",
"Line 2",
},
.administrative_area = "S",
.locality = "C",
.dependent_locality = "D",
.postal_code = "Z",
.sorting_code = "X",
.language_code = "zh-Hant",
.organization = "O",
.recipient = "N",
};
oss << address;
EXPECT_EQ("region_code: \"R\"\n"
"administrative_area: \"S\"\n"
"locality: \"C\"\n"
"dependent_locality: \"D\"\n"
"postal_code: \"Z\"\n"
"sorting_code: \"X\"\n"
"address_line: \"Line 1\"\n"
"address_line: \"Line 2\"\n"
"language_code: \"zh-Hant\"\n"
"organization: \"O\"\n"
"recipient: \"N\"\n", oss.str());
}
TEST(AddressDataTest, TestEquals) {
const AddressData address{
.region_code = "R",
.address_line{
"Line 1",
"Line 2",
},
.administrative_area = "S",
.locality = "C",
.dependent_locality = "D",
.postal_code = "Z",
.sorting_code = "X",
.language_code = "zh-Hant",
.organization = "O",
.recipient = "N",
};
AddressData clone = address;
EXPECT_EQ(address, clone);
clone.language_code.clear();
EXPECT_FALSE(address == clone);
}
#ifndef NDEBUG
TEST(AddressDataTest, GetFieldValueInvalid) {
const AddressData address;
ASSERT_DEATH_IF_SUPPORTED(address.GetFieldValue(STREET_ADDRESS),
"ssertion.*failed");
}
TEST(AddressDataTest, GetVectorFieldValueInvalid) {
const AddressData address;
ASSERT_DEATH_IF_SUPPORTED(address.GetRepeatedFieldValue(COUNTRY),
"ssertion.*failed");
}
TEST(AddressDataTest, IsFieldEmptyInvalid) {
static const auto invalid_field = static_cast<AddressField>(-1);
AddressData address;
ASSERT_DEATH_IF_SUPPORTED(address.IsFieldEmpty(invalid_field),
"ssertion.*failed");
}
#endif
} |
488 | cpp | google/libaddressinput | format_element | cpp/src/format_element.cc | cpp/test/format_element_test.cc | #ifndef I18N_ADDRESSINPUT_FORMAT_ELEMENT_H_
#define I18N_ADDRESSINPUT_FORMAT_ELEMENT_H_
#include <libaddressinput/address_field.h>
#include <iosfwd>
#include <string>
namespace i18n {
namespace addressinput {
class FormatElement {
public:
explicit FormatElement(AddressField field);
explicit FormatElement(const std::string& literal);
FormatElement();
bool IsField() const { return literal_.empty(); }
bool IsNewline() const { return literal_ == "\n"; }
AddressField GetField() const { return field_; }
const std::string& GetLiteral() const { return literal_; }
bool operator==(const FormatElement& other) const;
private:
AddressField field_;
std::string literal_;
};
}
}
std::ostream& operator<<(std::ostream& o,
const i18n::addressinput::FormatElement& element);
#endif
#include "format_element.h"
#include <libaddressinput/address_field.h>
#include <cassert>
#include <ostream>
#include <string>
namespace i18n {
namespace addressinput {
FormatElement::FormatElement(AddressField field) : field_(field), literal_() {}
FormatElement::FormatElement(const std::string& literal)
: field_(COUNTRY), literal_(literal) {
assert(!literal.empty());
}
FormatElement::FormatElement() : field_(COUNTRY), literal_("\n") {}
bool FormatElement::operator==(const FormatElement& other) const {
return field_ == other.field_ && literal_ == other.literal_;
}
}
}
std::ostream& operator<<(std::ostream& o,
const i18n::addressinput::FormatElement& element) {
if (element.IsField()) {
o << "Field: " << element.GetField();
} else if (element.IsNewline()) {
o << "Newline";
} else {
o << "Literal: " << element.GetLiteral();
}
return o;
} | #include "format_element.h"
#include <libaddressinput/address_field.h>
#include <sstream>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::FormatElement;
using i18n::addressinput::SORTING_CODE;
TEST(FormatElementTest, StreamFunctionNewline) {
std::ostringstream oss;
oss << FormatElement();
EXPECT_EQ("Newline", oss.str());
}
TEST(FormatElementTest, StreamFunctionLiteral) {
std::ostringstream oss;
oss << FormatElement("Text");
EXPECT_EQ("Literal: Text", oss.str());
}
TEST(FormatElementTest, StreamFunctionField) {
std::ostringstream oss;
oss << FormatElement(SORTING_CODE);
EXPECT_EQ("Field: SORTING_CODE", oss.str());
}
TEST(FormatElementTest, IsNewline) {
EXPECT_TRUE(FormatElement().IsNewline());
EXPECT_FALSE(FormatElement(" ").IsNewline());
EXPECT_FALSE(FormatElement(SORTING_CODE).IsNewline());
}
TEST(FormatElementTest, IsField) {
EXPECT_FALSE(FormatElement().IsField());
EXPECT_FALSE(FormatElement(" ").IsField());
EXPECT_TRUE(FormatElement(SORTING_CODE).IsField());
}
} |
489 | cpp | google/libaddressinput | null_storage | cpp/src/null_storage.cc | cpp/test/null_storage_test.cc | #ifndef I18N_ADDRESSINPUT_NULL_STORAGE_H_
#define I18N_ADDRESSINPUT_NULL_STORAGE_H_
#include <libaddressinput/storage.h>
#include <string>
namespace i18n {
namespace addressinput {
class NullStorage : public Storage {
public:
NullStorage(const NullStorage&) = delete;
NullStorage& operator=(const NullStorage&) = delete;
NullStorage();
~NullStorage() override;
void Put(const std::string& key, std::string* data) override;
void Get(const std::string& key, const Callback& data_ready) const override;
};
}
}
#endif
#include <libaddressinput/null_storage.h>
#include <cassert>
#include <cstddef>
#include <string>
namespace i18n {
namespace addressinput {
NullStorage::NullStorage() = default;
NullStorage::~NullStorage() = default;
void NullStorage::Put(const std::string& key, std::string* data) {
assert(data != nullptr);
delete data;
}
void NullStorage::Get(const std::string& key,
const Callback& data_ready) const {
data_ready(false, key, nullptr);
}
}
} | #include <libaddressinput/null_storage.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/storage.h>
#include <cstddef>
#include <memory>
#include <string>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::Storage;
class NullStorageTest : public testing::Test {
public:
NullStorageTest(const NullStorageTest&) = delete;
NullStorageTest& operator=(const NullStorageTest&) = delete;
protected:
NullStorageTest()
: data_ready_(BuildCallback(this, &NullStorageTest::OnDataReady)) {}
NullStorage storage_;
bool success_;
std::string key_;
std::string data_;
const std::unique_ptr<const Storage::Callback> data_ready_;
static const char kKey[];
private:
void OnDataReady(bool success, const std::string& key, std::string* data) {
ASSERT_FALSE(success && data == nullptr);
success_ = success;
key_ = key;
if (data != nullptr) {
data_ = *data;
delete data;
}
}
};
const char NullStorageTest::kKey[] = "foo";
TEST_F(NullStorageTest, Put) {
storage_.Put(kKey, new std::string("bar"));
}
TEST_F(NullStorageTest, Get) {
storage_.Get(kKey, *data_ready_);
EXPECT_FALSE(success_);
EXPECT_EQ(kKey, key_);
EXPECT_TRUE(data_.empty());
}
} |
490 | cpp | google/libaddressinput | validating_util | cpp/src/validating_util.cc | cpp/test/validating_util_test.cc | #ifndef I18N_ADDRESSINPUT_VALIDATING_UTIL_H_
#define I18N_ADDRESSINPUT_VALIDATING_UTIL_H_
#include <ctime>
#include <string>
namespace i18n {
namespace addressinput {
class ValidatingUtil {
public:
static void Wrap(time_t timestamp, std::string* data);
static bool UnwrapTimestamp(std::string* data, time_t now);
static bool UnwrapChecksum(std::string* data);
ValidatingUtil(const ValidatingUtil&) = delete;
ValidatingUtil& operator=(const ValidatingUtil&) = delete;
};
}
}
#endif
#include "validating_util.h"
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <string>
#include "util/md5.h"
namespace i18n {
namespace addressinput {
namespace {
const char kTimestampPrefix[] = "timestamp=";
const size_t kTimestampPrefixLength = sizeof kTimestampPrefix - 1;
const char kChecksumPrefix[] = "checksum=";
const size_t kChecksumPrefixLength = sizeof kChecksumPrefix - 1;
const char kSeparator = '\n';
bool UnwrapHeader(const char* header_prefix,
size_t header_prefix_length,
std::string* data,
std::string* header_value) {
assert(header_prefix != nullptr);
assert(data != nullptr);
assert(header_value != nullptr);
if (data->compare(
0, header_prefix_length, header_prefix, header_prefix_length) != 0) {
return false;
}
std::string::size_type separator_position =
data->find(kSeparator, header_prefix_length);
if (separator_position == std::string::npos) {
return false;
}
header_value->assign(
*data, header_prefix_length, separator_position - header_prefix_length);
data->erase(0, separator_position + 1);
return true;
}
}
void ValidatingUtil::Wrap(time_t timestamp, std::string* data) {
assert(data != nullptr);
char timestamp_string[2 + 3 * sizeof timestamp];
int size = std::snprintf(timestamp_string, sizeof(timestamp_string), "%ld",
static_cast<long>(timestamp));
assert(size > 0);
assert(size < sizeof timestamp_string);
(void)size;
std::string header;
header.append(kTimestampPrefix, kTimestampPrefixLength);
header.append(timestamp_string);
header.push_back(kSeparator);
header.append(kChecksumPrefix, kChecksumPrefixLength);
header.append(MD5String(*data));
header.push_back(kSeparator);
data->reserve(header.size() + data->size());
data->insert(0, header);
}
bool ValidatingUtil::UnwrapTimestamp(std::string* data, time_t now) {
assert(data != nullptr);
if (now < 0) {
return false;
}
std::string timestamp_string;
if (!UnwrapHeader(
kTimestampPrefix, kTimestampPrefixLength, data, ×tamp_string)) {
return false;
}
time_t timestamp = atol(timestamp_string.c_str());
if (timestamp < 0) {
return false;
}
static const double kOneMonthInSeconds = 30.0 * 24.0 * 60.0 * 60.0;
double age_in_seconds = difftime(now, timestamp);
return !(age_in_seconds < 0.0) && age_in_seconds < kOneMonthInSeconds;
}
bool ValidatingUtil::UnwrapChecksum(std::string* data) {
assert(data != nullptr);
std::string checksum;
if (!UnwrapHeader(kChecksumPrefix, kChecksumPrefixLength, data, &checksum)) {
return false;
}
return checksum == MD5String(*data);
}
}
} | #include "validating_util.h"
#include <string>
#include <gtest/gtest.h>
#define ITOA_HELPER(i) #i
#define ITOA(i) ITOA_HELPER(i)
#define DATA "{'foo': 'bar'}"
#define TIMESTAMP 1388001600
#define TIMESTAMP_HALF_MONTH_AGO 1386705600
#define TIMESTAMP_TWO_MONTHS_AGO 1382817600
#define CHECKSUM "dd63dafcbd4d5b28badfcaf86fb6fcdb"
namespace {
using i18n::addressinput::ValidatingUtil;
const char kUnwrappedData[] = DATA;
const time_t kTimestamp = TIMESTAMP;
const char kChecksummedData[] = "checksum=" CHECKSUM "\n"
DATA;
const char kCorruptedChecksummedData[] = "checksuM=" CHECKSUM "\n"
DATA;
const char kChecksumInMiddle[] = DATA "\n"
"checksum=" CHECKSUM "\n"
DATA;
const char kWrappedData[] = "timestamp=" ITOA(TIMESTAMP) "\n"
"checksum=" CHECKSUM "\n"
DATA;
const char kCorruptedWrappedData[] = "timestamP=" ITOA(TIMESTAMP) "\n"
"checksum=" CHECKSUM "\n"
DATA;
const char kTimestampInMiddle[] = DATA "\n"
"timestamp=" ITOA(TIMESTAMP) "\n"
DATA;
const char kTimestampHalfMonthAgo[] =
"timestamp=" ITOA(TIMESTAMP_HALF_MONTH_AGO) "\n"
DATA;
const char kTimestampTwoMonthsAgo[] =
"timestamp=" ITOA(TIMESTAMP_TWO_MONTHS_AGO) "\n"
DATA;
TEST(ValidatingUtilTest, UnwrapChecksum_CorruptedData) {
std::string data(kCorruptedChecksummedData);
EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data));
}
TEST(ValidatingUtilTest, UnwrapChecksum_EmptyString) {
std::string data;
EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data));
}
TEST(ValidatingUtilTest, UnwrapChecksum_GarbageData) {
std::string data("garbage");
EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data));
}
TEST(ValidatingUtilTest, UnwrapChecksum_InMiddle) {
std::string data(kChecksumInMiddle);
EXPECT_FALSE(ValidatingUtil::UnwrapChecksum(&data));
}
TEST(ValidatingUtilTest, UnwrapChecksum) {
std::string data(kChecksummedData);
EXPECT_TRUE(ValidatingUtil::UnwrapChecksum(&data));
EXPECT_EQ(kUnwrappedData, data);
}
TEST(ValidatingUtilTest, UnwrapTimestamp_CorruptedData) {
std::string data(kCorruptedWrappedData);
EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
}
TEST(ValidatingUtilTest, UnwrapTimestamp_EmptyString) {
std::string data;
EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
}
TEST(ValidatingUtilTest, UnwrapTimestamp_GarbageData) {
std::string data("garbage");
EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
}
TEST(ValidatingUtilTest, UnwrapTimestamp_InMiddle) {
std::string data(kTimestampInMiddle);
EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
}
TEST(ValidatingUtilTest, UnwrapTimestamp_Recent) {
std::string data(kTimestampHalfMonthAgo);
EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
EXPECT_EQ(kUnwrappedData, data);
}
TEST(ValidatingUtilTest, UnwrapTimestamp_Stale) {
std::string data(kTimestampTwoMonthsAgo);
EXPECT_FALSE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
}
TEST(ValidatingUtilTest, UnwrapTimestamp) {
std::string data(kWrappedData);
EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
EXPECT_EQ(kChecksummedData, data);
}
TEST(ValidatingUtilTest, Wrap) {
std::string data = kUnwrappedData;
ValidatingUtil::Wrap(kTimestamp, &data);
EXPECT_EQ(kWrappedData, data);
}
TEST(ValidatingUtilTest, WrapUnwrapIt) {
std::string data = kUnwrappedData;
ValidatingUtil::Wrap(kTimestamp, &data);
EXPECT_TRUE(ValidatingUtil::UnwrapTimestamp(&data, kTimestamp));
EXPECT_EQ(kChecksummedData, data);
EXPECT_TRUE(ValidatingUtil::UnwrapChecksum(&data));
EXPECT_EQ(kUnwrappedData, data);
}
} |
491 | cpp | google/libaddressinput | validation_task | cpp/src/validation_task.cc | cpp/test/validation_task_test.cc | #ifndef I18N_ADDRESSINPUT_VALIDATION_TASK_H_
#define I18N_ADDRESSINPUT_VALIDATION_TASK_H_
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <libaddressinput/address_validator.h>
#include <libaddressinput/supplier.h>
#include <memory>
#include <string>
namespace i18n {
namespace addressinput {
class LookupKey;
struct AddressData;
class ValidationTask {
public:
ValidationTask(const ValidationTask&) = delete;
ValidationTask& operator=(const ValidationTask&) = delete;
ValidationTask(const AddressData& address,
bool allow_postal,
bool require_name,
const FieldProblemMap* filter,
FieldProblemMap* problems,
const AddressValidator::Callback& validated);
~ValidationTask();
void Run(Supplier* supplier);
private:
friend class ValidationTaskTest;
void Validate(bool success,
const LookupKey& lookup_key,
const Supplier::RuleHierarchy& hierarchy);
void CheckUnexpectedField(const std::string& region_code) const;
void CheckMissingRequiredField(const std::string& region_code) const;
void CheckUnknownValue(const Supplier::RuleHierarchy& hierarchy) const;
void CheckUnsupportedField() const;
void CheckPostalCodeFormatAndValue(
const Supplier::RuleHierarchy& hierarchy) const;
void CheckUsesPoBox(const Supplier::RuleHierarchy& hierarchy) const;
void ReportProblem(AddressField field, AddressProblem problem) const;
void ReportProblemMaybe(AddressField field, AddressProblem problem) const;
bool ShouldReport(AddressField field, AddressProblem problem) const;
const AddressData& address_;
const bool allow_postal_;
const bool require_name_;
const FieldProblemMap* filter_;
FieldProblemMap* const problems_;
const AddressValidator::Callback& validated_;
const std::unique_ptr<const Supplier::Callback> supplied_;
const std::unique_ptr<LookupKey> lookup_key_;
size_t max_depth_;
};
}
}
#endif
#include "validation_task.h"
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_metadata.h>
#include <libaddressinput/address_problem.h>
#include <libaddressinput/address_validator.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/supplier.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <string>
#include <re2/re2.h>
#include "lookup_key.h"
#include "post_box_matchers.h"
#include "rule.h"
#include "util/re2ptr.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
ValidationTask::ValidationTask(const AddressData& address, bool allow_postal,
bool require_name, const FieldProblemMap* filter,
FieldProblemMap* problems,
const AddressValidator::Callback& validated)
: address_(address),
allow_postal_(allow_postal),
require_name_(require_name),
filter_(filter),
problems_(problems),
validated_(validated),
supplied_(BuildCallback(this, &ValidationTask::Validate)),
lookup_key_(new LookupKey),
max_depth_(size(LookupKey::kHierarchy)) {
assert(problems_ != nullptr);
assert(supplied_ != nullptr);
assert(lookup_key_ != nullptr);
}
ValidationTask::~ValidationTask() = default;
void ValidationTask::Run(Supplier* supplier) {
assert(supplier != nullptr);
problems_->clear();
lookup_key_->FromAddress(address_);
max_depth_ = supplier->GetLoadedRuleDepth(lookup_key_->ToKeyString(0));
supplier->SupplyGlobally(*lookup_key_, *supplied_);
}
void ValidationTask::Validate(bool success,
const LookupKey& lookup_key,
const Supplier::RuleHierarchy& hierarchy) {
assert(&lookup_key == lookup_key_.get());
if (success) {
if (address_.IsFieldEmpty(COUNTRY)) {
ReportProblemMaybe(COUNTRY, MISSING_REQUIRED_FIELD);
} else if (hierarchy.rule[0] == nullptr) {
ReportProblemMaybe(COUNTRY, UNKNOWN_VALUE);
} else {
const std::string& region_code = address_.region_code;
CheckUnexpectedField(region_code);
CheckMissingRequiredField(region_code);
CheckUnknownValue(hierarchy);
CheckPostalCodeFormatAndValue(hierarchy);
CheckUsesPoBox(hierarchy);
CheckUnsupportedField();
}
}
validated_(success, address_, *problems_);
delete this;
}
void ValidationTask::CheckUnexpectedField(
const std::string& region_code) const {
static const AddressField kFields[] = {
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
POSTAL_CODE,
STREET_ADDRESS,
ORGANIZATION,
RECIPIENT,
};
for (AddressField field : kFields) {
if (!address_.IsFieldEmpty(field) && !IsFieldUsed(field, region_code)) {
ReportProblemMaybe(field, UNEXPECTED_FIELD);
}
}
}
void ValidationTask::CheckMissingRequiredField(
const std::string& region_code) const {
static const AddressField kFields[] = {
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
POSTAL_CODE,
STREET_ADDRESS,
};
for (AddressField field : kFields) {
if (address_.IsFieldEmpty(field) && IsFieldRequired(field, region_code)) {
ReportProblemMaybe(field, MISSING_REQUIRED_FIELD);
}
}
if (require_name_ && address_.IsFieldEmpty(RECIPIENT)) {
ReportProblemMaybe(RECIPIENT, MISSING_REQUIRED_FIELD);
}
}
void ValidationTask::CheckUnknownValue(
const Supplier::RuleHierarchy& hierarchy) const {
for (size_t depth = 1; depth < size(LookupKey::kHierarchy); ++depth) {
AddressField field = LookupKey::kHierarchy[depth];
if (!(address_.IsFieldEmpty(field) ||
hierarchy.rule[depth - 1] == nullptr ||
hierarchy.rule[depth - 1]->GetSubKeys().empty() ||
hierarchy.rule[depth] != nullptr)) {
ReportProblemMaybe(field, UNKNOWN_VALUE);
}
}
}
void ValidationTask::CheckUnsupportedField() const {
for (size_t depth = max_depth_; depth < size(LookupKey::kHierarchy);
++depth) {
ReportProblemMaybe(LookupKey::kHierarchy[depth], UNSUPPORTED_FIELD);
}
}
void ValidationTask::CheckPostalCodeFormatAndValue(
const Supplier::RuleHierarchy& hierarchy) const {
assert(hierarchy.rule[0] != nullptr);
const Rule& country_rule = *hierarchy.rule[0];
if (!(ShouldReport(POSTAL_CODE, INVALID_FORMAT) ||
ShouldReport(POSTAL_CODE, MISMATCHING_VALUE))) {
return;
}
if (address_.IsFieldEmpty(POSTAL_CODE)) {
return;
} else if (std::find(problems_->begin(), problems_->end(),
FieldProblemMap::value_type(POSTAL_CODE,
UNEXPECTED_FIELD))
!= problems_->end()) {
return;
}
const RE2ptr* format_ptr = country_rule.GetPostalCodeMatcher();
if (format_ptr != nullptr &&
!RE2::FullMatch(address_.postal_code, *format_ptr->ptr) &&
ShouldReport(POSTAL_CODE, INVALID_FORMAT)) {
ReportProblem(POSTAL_CODE, INVALID_FORMAT);
return;
}
if (!ShouldReport(POSTAL_CODE, MISMATCHING_VALUE)) {
return;
}
for (size_t depth = size(LookupKey::kHierarchy) - 1; depth > 0; --depth) {
if (hierarchy.rule[depth] != nullptr) {
const RE2ptr* prefix_ptr = hierarchy.rule[depth]->GetPostalCodeMatcher();
if (prefix_ptr != nullptr) {
if (!RE2::PartialMatch(address_.postal_code, *prefix_ptr->ptr)) {
ReportProblem(POSTAL_CODE, MISMATCHING_VALUE);
}
return;
}
}
}
}
void ValidationTask::CheckUsesPoBox(
const Supplier::RuleHierarchy& hierarchy) const {
assert(hierarchy.rule[0] != nullptr);
const Rule& country_rule = *hierarchy.rule[0];
if (allow_postal_ ||
!ShouldReport(STREET_ADDRESS, USES_P_O_BOX) ||
address_.IsFieldEmpty(STREET_ADDRESS)) {
return;
}
const auto matchers = PostBoxMatchers::GetMatchers(country_rule);
for (const auto& line : address_.address_line) {
for (auto ptr : matchers) {
assert(ptr != nullptr);
if (RE2::PartialMatch(line, *ptr->ptr)) {
ReportProblem(STREET_ADDRESS, USES_P_O_BOX);
return;
}
}
}
}
void ValidationTask::ReportProblem(AddressField field,
AddressProblem problem) const {
problems_->emplace(field, problem);
}
void ValidationTask::ReportProblemMaybe(AddressField field,
AddressProblem problem) const {
if (ShouldReport(field, problem)) {
ReportProblem(field, problem);
}
}
bool ValidationTask::ShouldReport(AddressField field,
AddressProblem problem) const {
return filter_ == nullptr || filter_->empty() ||
std::find(filter_->begin(),
filter_->end(),
FieldProblemMap::value_type(field, problem)) !=
filter_->end();
}
}
} | #include "validation_task.h"
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <libaddressinput/address_validator.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/supplier.h>
#include <cstddef>
#include <memory>
#include <gtest/gtest.h>
#include "lookup_key.h"
#include "rule.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
class ValidationTaskTest : public testing::Test {
public:
ValidationTaskTest(const ValidationTaskTest&) = delete;
ValidationTaskTest& operator=(const ValidationTaskTest&) = delete;
protected:
ValidationTaskTest()
: json_(),
success_(true),
address_(),
allow_postal_(false),
require_name_(false),
filter_{
{COUNTRY, UNEXPECTED_FIELD},
{COUNTRY, MISSING_REQUIRED_FIELD},
{RECIPIENT, UNEXPECTED_FIELD},
{RECIPIENT, MISSING_REQUIRED_FIELD},
},
problems_(),
expected_(),
called_(false),
validated_(BuildCallback(this, &ValidationTaskTest::Validated)) {
static const AddressField kFields[] = {
COUNTRY,
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
SORTING_CODE,
POSTAL_CODE,
STREET_ADDRESS,
ORGANIZATION,
RECIPIENT,
};
static const AddressProblem kProblems[] = {
UNKNOWN_VALUE,
INVALID_FORMAT,
MISMATCHING_VALUE,
USES_P_O_BOX,
};
for (AddressField field : kFields) {
for (AddressProblem problem : kProblems) {
filter_.emplace(field, problem);
}
}
}
void Validate() {
Rule rule[size(LookupKey::kHierarchy)];
auto* task = new ValidationTask(
address_,
allow_postal_,
require_name_,
&filter_,
&problems_,
*validated_);
Supplier::RuleHierarchy hierarchy;
for (size_t i = 0;
i < size(LookupKey::kHierarchy) && json_[i] != nullptr; ++i) {
ASSERT_TRUE(rule[i].ParseSerializedRule(json_[i]));
hierarchy.rule[i] = &rule[i];
}
(*task->supplied_)(success_, *task->lookup_key_, hierarchy);
}
const char* json_[size(LookupKey::kHierarchy)];
bool success_;
AddressData address_;
bool allow_postal_;
bool require_name_;
FieldProblemMap filter_;
FieldProblemMap problems_;
FieldProblemMap expected_;
bool called_;
private:
void Validated(bool success,
const AddressData& address,
const FieldProblemMap& problems) {
ASSERT_EQ(success_, success);
ASSERT_EQ(&address_, &address);
ASSERT_EQ(&problems_, &problems);
called_ = true;
}
const std::unique_ptr<const AddressValidator::Callback> validated_;
};
namespace {
TEST_F(ValidationTaskTest, FailureCountryRuleNull) {
success_ = false;
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, FailureCountryRuleEmpty) {
json_[0] = "{}";
success_ = false;
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, SuccessCountryRuleNullNameEmpty) {
expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, SuccessCountryRuleNullNameNotEmpty) {
address_ = {.region_code = "rrr"};
expected_ = {{COUNTRY, UNKNOWN_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, SuccessCountryRuleEmptyNameEmpty) {
json_[0] = "{}";
expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, SuccessCountryRuleEmptyNameNotEmpty) {
json_[0] = "{}";
address_ = {.region_code = "rrr"};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, MissingRequiredFieldsUS) {
json_[0] = "{}";
address_ = {.region_code = "US"};
filter_ = {
{ADMIN_AREA, MISSING_REQUIRED_FIELD},
{LOCALITY, MISSING_REQUIRED_FIELD},
{POSTAL_CODE, MISSING_REQUIRED_FIELD},
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
};
expected_ = {
{ADMIN_AREA, MISSING_REQUIRED_FIELD},
{LOCALITY, MISSING_REQUIRED_FIELD},
{POSTAL_CODE, MISSING_REQUIRED_FIELD},
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, MissingNoRequiredFieldsUS) {
json_[0] = "{}";
address_ = {
.region_code = "US",
.address_line{"aaa"},
.administrative_area = "sss",
.locality = "ccc",
.postal_code = "zzz",
.organization = "ooo",
.recipient = "nnn",
};
filter_ = {
{ADMIN_AREA, MISSING_REQUIRED_FIELD},
{LOCALITY, MISSING_REQUIRED_FIELD},
{POSTAL_CODE, MISSING_REQUIRED_FIELD},
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
{ORGANIZATION, MISSING_REQUIRED_FIELD},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UnexpectedFieldUS) {
json_[0] = "{}";
address_ = {
.region_code = "US",
.dependent_locality = "ddd",
};
filter_ = {{DEPENDENT_LOCALITY, UNEXPECTED_FIELD}};
expected_ = {{DEPENDENT_LOCALITY, UNEXPECTED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, MissingRequiredFieldRequireName) {
json_[0] = "{}";
address_ = {.region_code = "rrr"};
require_name_ = true;
expected_ = {{RECIPIENT, MISSING_REQUIRED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UnknownValueRuleNull) {
json_[0] = R"({"fmt":"%R%S","require":"RS","sub_keys":"aa~bb"})";
address_ = {
.region_code = "rrr",
.administrative_area = "sss",
};
expected_ = {{ADMIN_AREA, UNKNOWN_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, NoUnknownValueRuleNotNull) {
json_[0] = R"({"fmt":"%R%S","require":"RS","sub_keys":"aa~bb"})";
json_[1] = "{}";
address_ = {
.region_code = "rrr",
.administrative_area = "sss",
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeUnrecognizedFormatTooShort) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
address_ = {
.region_code = "rrr",
.postal_code = "12",
};
expected_ = {{POSTAL_CODE, INVALID_FORMAT}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeUnrecognizedFormatTooLong) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
address_ = {
.region_code = "rrr",
.postal_code = "1234",
};
expected_ = {{POSTAL_CODE, INVALID_FORMAT}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeRecognizedFormat) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
address_ = {
.region_code = "rrr",
.postal_code = "123",
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeMismatchingValue1) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
json_[1] = R"({"zip":"1"})";
address_ = {
.region_code = "rrr",
.postal_code = "000",
};
expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeMismatchingValue2) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
json_[1] = R"({"zip":"1"})";
json_[2] = R"({"zip":"12"})";
address_ = {
.region_code = "rrr",
.postal_code = "100",
};
expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeMismatchingValue3) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
json_[1] = R"({"zip":"1"})";
json_[2] = R"({"zip":"12"})";
json_[3] = R"({"zip":"123"})";
address_ = {
.region_code = "rrr",
.postal_code = "120",
};
expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeMatchingValue) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{3}"})";
json_[1] = R"({"zip":"1"})";
json_[2] = R"({"zip":"12"})";
json_[3] = R"({"zip":"123"})";
address_ = {
.region_code = "rrr",
.postal_code = "123",
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodePrefixMismatchingValue) {
json_[0] = R"({"fmt":"%Z","zip":"\\d{5}"})";
json_[1] = R"({"zip":"9[0-5]|96[01]"})";
address_ = {
.region_code = "rrr",
.postal_code = "10960",
};
expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, PostalCodeFilterIgnoresMismatching) {
json_[0] = R"({"zip":"\\d{3}"})";
json_[1] = R"({"zip":"1"})";
address_ = {
.region_code = "rrr",
.postal_code = "000",
};
filter_ = {{POSTAL_CODE, INVALID_FORMAT}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UsesPoBoxLanguageUnd) {
json_[0] = R"({"fmt":"%A"})";
address_ = {
.region_code = "rrr",
.address_line{
"aaa",
"P.O. Box",
"aaa",
},
};
expected_ = {{STREET_ADDRESS, USES_P_O_BOX}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UsesPoBoxLanguageDa) {
json_[0] = R"({"fmt":"%A","languages":"da"})";
address_ = {
.region_code = "rrr",
.address_line{
"aaa",
"Postboks",
"aaa",
},
};
expected_ = {{STREET_ADDRESS, USES_P_O_BOX}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UsesPoBoxLanguageDaNotMatchDe) {
json_[0] = R"({"fmt":"%A","languages":"da"})";
address_ = {
.region_code = "rrr",
.address_line{
"aaa",
"Postfach",
"aaa",
},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_F(ValidationTaskTest, UsesPoBoxAllowPostal) {
json_[0] = R"({"fmt":"%A"})";
address_ = {
.region_code = "rrr",
.address_line{
"aaa",
"P.O. Box",
"aaa",
},
};
allow_postal_ = true;
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
}
}
} |
492 | cpp | google/libaddressinput | address_formatter | cpp/src/address_formatter.cc | cpp/test/address_formatter_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_FORMATTER_H_
#define I18N_ADDRESSINPUT_ADDRESS_FORMATTER_H_
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
struct AddressData;
void GetFormattedNationalAddress(
const AddressData& address_data, std::vector<std::string>* lines);
void GetFormattedNationalAddressLine(
const AddressData& address_data, std::string* line);
void GetStreetAddressLinesAsSingleLine(
const AddressData& address_data, std::string* line);
}
}
#endif
#include <libaddressinput/address_formatter.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <string>
#include <vector>
#include "format_element.h"
#include "language.h"
#include "region_data_constants.h"
#include "rule.h"
#include "util/cctype_tolower_equal.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
const char kCommaSeparator[] = ", ";
const char kSpaceSeparator[] = " ";
const char kArabicCommaSeparator[] = "، ";
const char kLanguagesThatUseSpace[][3] = {
"th",
"ko",
};
const char kLanguagesThatHaveNoSeparator[][3] = {
"ja",
"zh",
};
const char kLanguagesThatUseAnArabicComma[][3] = {
"ar",
"fa",
"ku",
"ps",
"ur",
};
std::string GetLineSeparatorForLanguage(const std::string& language_tag) {
Language address_language(language_tag);
if (address_language.has_latin_script) {
return kCommaSeparator;
}
const std::string& base_language = address_language.base;
using std::placeholders::_1;
if (std::find_if(kLanguagesThatUseSpace,
kLanguagesThatUseSpace + size(kLanguagesThatUseSpace),
std::bind(&EqualToTolowerString, _1, base_language)) !=
kLanguagesThatUseSpace + size(kLanguagesThatUseSpace)) {
return kSpaceSeparator;
} else if (std::find_if(
kLanguagesThatHaveNoSeparator,
kLanguagesThatHaveNoSeparator +
size(kLanguagesThatHaveNoSeparator),
std::bind(&EqualToTolowerString, _1, base_language)) !=
kLanguagesThatHaveNoSeparator +
size(kLanguagesThatHaveNoSeparator)) {
return "";
} else if (std::find_if(
kLanguagesThatUseAnArabicComma,
kLanguagesThatUseAnArabicComma +
size(kLanguagesThatUseAnArabicComma),
std::bind(&EqualToTolowerString, _1, base_language)) !=
kLanguagesThatUseAnArabicComma +
size(kLanguagesThatUseAnArabicComma)) {
return kArabicCommaSeparator;
}
return kCommaSeparator;
}
void CombineLinesForLanguage(const std::vector<std::string>& lines,
const std::string& language_tag,
std::string* line) {
line->clear();
std::string separator = GetLineSeparatorForLanguage(language_tag);
for (auto it = lines.begin(); it != lines.end(); ++it) {
if (it != lines.begin()) {
line->append(separator);
}
line->append(*it);
}
}
}
void GetFormattedNationalAddress(
const AddressData& address_data, std::vector<std::string>* lines) {
assert(lines != nullptr);
lines->clear();
Rule rule;
rule.CopyFrom(Rule::GetDefault());
rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(address_data.region_code));
Language language(address_data.language_code);
const std::vector<FormatElement>& format =
language.has_latin_script && !rule.GetLatinFormat().empty()
? rule.GetLatinFormat()
: rule.GetFormat();
std::vector<FormatElement> pruned_format;
for (auto element_it = format.begin();
element_it != format.end();
++element_it) {
if (element_it->IsNewline() ||
(element_it->IsField() &&
!address_data.IsFieldEmpty(element_it->GetField())) ||
(!element_it->IsField() &&
(element_it + 1 == format.end() ||
!(element_it + 1)->IsField() ||
!address_data.IsFieldEmpty((element_it + 1)->GetField())) &&
(element_it == format.begin() ||
!(element_it - 1)->IsField() ||
(!pruned_format.empty() && pruned_format.back().IsField())))) {
pruned_format.push_back(*element_it);
}
}
std::string line;
for (const auto& element : pruned_format) {
if (element.IsNewline()) {
if (!line.empty()) {
lines->push_back(line);
line.clear();
}
} else if (element.IsField()) {
AddressField field = element.GetField();
if (field == STREET_ADDRESS) {
if (!address_data.IsFieldEmpty(field)) {
line.append(address_data.address_line.front());
if (address_data.address_line.size() > 1U) {
lines->push_back(line);
line.clear();
const auto last_element_iterator =
address_data.address_line.begin() +
address_data.address_line.size() - 1;
lines->insert(lines->end(), address_data.address_line.begin() + 1,
last_element_iterator);
line.append(*last_element_iterator);
}
}
} else {
line.append(address_data.GetFieldValue(field));
}
} else {
line.append(element.GetLiteral());
}
}
if (!line.empty()) {
lines->push_back(line);
}
}
void GetFormattedNationalAddressLine(
const AddressData& address_data, std::string* line) {
std::vector<std::string> address_lines;
GetFormattedNationalAddress(address_data, &address_lines);
CombineLinesForLanguage(address_lines, address_data.language_code, line);
}
void GetStreetAddressLinesAsSingleLine(
const AddressData& address_data, std::string* line) {
CombineLinesForLanguage(
address_data.address_line, address_data.language_code, line);
}
}
} | #include <libaddressinput/address_formatter.h>
#include <libaddressinput/address_data.h>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::GetFormattedNationalAddress;
using i18n::addressinput::GetFormattedNationalAddressLine;
using i18n::addressinput::GetStreetAddressLinesAsSingleLine;
TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_EmptyAddress) {
const AddressData address;
std::string result;
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_TRUE(result.empty());
}
TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_1Line) {
AddressData address{
.region_code = "US",
.address_line{"Line 1"},
};
std::string result;
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1", result);
address.language_code = "en";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1", result);
address.language_code = "zh-Hans";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1", result);
}
TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_2Lines) {
AddressData address{
.region_code = "US",
.address_line{
"Line 1",
"Line 2",
},
};
std::string result;
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1, Line 2", result);
address.language_code = "en";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1, Line 2", result);
address.language_code = "zh-Hans";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1Line 2", result);
address.language_code = "ko";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1 Line 2", result);
address.language_code = "ar";
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ("Line 1، Line 2", result);
}
TEST(AddressFormatterTest, GetStreetAddressLinesAsSingleLine_5Lines) {
const AddressData address{
.region_code = "US",
.address_line{
"Line 1",
"Line 2",
"Line 3",
"Line 4",
"Line 5",
},
.language_code = "fr",
};
std::string result;
GetStreetAddressLinesAsSingleLine(address, &result);
EXPECT_EQ(result, "Line 1, Line 2, Line 3, Line 4, Line 5");
}
TEST(AddressFormatterTest, GetFormattedNationalAddressLocalLanguage) {
AddressData address{
.region_code = "NZ",
.address_line{
"Rotopapa",
"Irwell 3RD",
},
.locality = "Leeston",
.postal_code = "8704",
};
const std::vector<std::string> expected{
"Rotopapa",
"Irwell 3RD",
"Leeston 8704",
};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.language_code = "en-Latn-CN";
lines.clear();
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
std::string one_line;
GetFormattedNationalAddressLine(address, &one_line);
EXPECT_EQ("Rotopapa, Irwell 3RD, Leeston 8704", one_line);
}
TEST(AddressFormatterTest, GetFormattedNationalAddressLatinFormat) {
static const char kTaiwanCity[] = "大安區";
static const char kTaiwanAdmin[] = "台北市";
static const char kTaiwanStreetLine[] = "台灣信義路三段33號";
static const char kPostalCode[] = "106";
const AddressData address{
.region_code = "TW",
.address_line{kTaiwanStreetLine},
.administrative_area = kTaiwanAdmin,
.locality = kTaiwanCity,
.postal_code = kPostalCode,
.language_code = "zh-Hant",
};
const std::vector<std::string> expected{
kPostalCode,
std::string(kTaiwanAdmin).append(kTaiwanCity),
kTaiwanStreetLine,
};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
std::string one_line;
GetFormattedNationalAddressLine(address, &one_line);
EXPECT_EQ(std::string(kPostalCode)
.append(kTaiwanAdmin)
.append(kTaiwanCity)
.append(kTaiwanStreetLine),
one_line);
const AddressData latin_address{
.region_code = "TW",
.address_line{"No. 33, Section 3 Xinyi Rd"},
.administrative_area = "Taipei City",
.locality = "Da-an District",
.postal_code = kPostalCode,
.language_code = "zh-Latn",
};
const std::vector<std::string> expected_latin{
"No. 33, Section 3 Xinyi Rd",
"Da-an District, Taipei City 106",
};
lines.clear();
GetFormattedNationalAddress(latin_address, &lines);
EXPECT_EQ(expected_latin, lines);
GetFormattedNationalAddressLine(latin_address, &one_line);
EXPECT_EQ("No. 33, Section 3 Xinyi Rd, Da-an District, Taipei City 106",
one_line);
}
TEST(AddressFormatterTest, GetFormattedNationalAddressMultilingualCountry) {
const AddressData address{
.region_code = "CA",
.address_line{
"5 Rue du Tresor",
"Apt. 4",
},
.administrative_area = "QC",
.locality = "Montmagny",
.postal_code = "G1R 123",
.language_code = "fr",
};
const std::vector<std::string> expected{
"5 Rue du Tresor",
"Apt. 4",
"Montmagny QC G1R 123",
};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest, GetFormattedNationalAddress_InlineStreetAddress) {
const AddressData address{
.region_code = "CI",
.address_line{"32 Boulevard Carde"},
.locality = "Abidjan",
.sorting_code = "64",
.language_code = "zh-Hant",
};
const std::vector<std::string> expected{"64 32 Boulevard Carde Abidjan 64"};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddressMissingFields_LiteralsAroundField) {
AddressData address{.region_code = "CH"};
std::vector<std::string> expected;
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality = "Zurich";
expected.emplace_back("Zurich");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.postal_code = "8001";
expected.back().assign("CH-8001 Zurich");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality.clear();
expected.back().assign("CH-8001");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddressMissingFields_LiteralsBetweenFields) {
AddressData address{.region_code = "US"};
std::vector<std::string> expected;
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.administrative_area = "CA";
expected.emplace_back("CA");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality = "Los Angeles";
expected.back().assign("Los Angeles, CA");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.postal_code = "90291";
expected.back().assign("Los Angeles, CA 90291");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.administrative_area.clear();
expected.back().assign("Los Angeles 90291");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality.clear();
address.administrative_area = "CA";
expected.back().assign("CA 90291");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddressMissingFields_LiteralOnSeparateLine) {
AddressData address{.region_code = "AX"};
std::vector<std::string> expected{"ÅLAND"};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality = "City";
expected.emplace(expected.begin(), "City");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.postal_code = "123";
expected.front().assign("AX-123 City");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddressMissingFields_LiteralBeforeField) {
AddressData address{
.region_code = "JP",
.language_code = "ja",
};
std::vector<std::string> expected;
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.postal_code = "123";
expected.emplace_back("〒123");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.administrative_area = "Prefecture";
expected.emplace_back("Prefecture");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.postal_code.clear();
expected.erase(expected.begin());
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddress_LiteralBeforeOneAddressLine) {
const AddressData address{
.region_code = "JP",
.address_line{"Roppongi Hills"},
.administrative_area = "Tokyo",
.language_code = "ja_Latn",
};
const std::vector<std::string> expected{"Roppongi Hills, Tokyo"};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddress_LiteralBeforeTwoAddressLines) {
const AddressData address{
.region_code = "JP",
.address_line{
"Roppongi Hills",
"Mori Tower",
},
.administrative_area = "Tokyo",
.language_code = "ja_Latn",
};
const std::vector<std::string> expected{
"Roppongi Hills",
"Mori Tower, Tokyo",
};
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
TEST(AddressFormatterTest,
GetFormattedNationalAddressMissingFields_DuplicateField) {
AddressData address{.region_code = "CI"};
std::vector<std::string> expected;
std::vector<std::string> lines;
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.sorting_code = "123";
expected.emplace_back("123 123");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.address_line.emplace_back("456 Main St");
expected.back().assign("123 456 Main St 123");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.locality = "Yamoussoukro";
expected.back().assign("123 456 Main St Yamoussoukro 123");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.sorting_code.erase();
expected.back().assign("456 Main St Yamoussoukro");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
address.address_line.clear();
expected.back().assign("Yamoussoukro");
GetFormattedNationalAddress(address, &lines);
EXPECT_EQ(expected, lines);
}
} |
493 | cpp | google/libaddressinput | address_field_util | cpp/src/address_field_util.cc | cpp/test/address_field_util_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_FIELD_UTIL_H_
#define I18N_ADDRESSINPUT_ADDRESS_FIELD_UTIL_H_
#include <libaddressinput/address_field.h>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
class FormatElement;
void ParseFormatRule(const std::string& format,
std::vector<FormatElement>* elements);
void ParseAddressFieldsRequired(const std::string& required,
std::vector<AddressField>* fields);
}
}
#endif
#include "address_field_util.h"
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <cassert>
#include <string>
#include <vector>
#include "format_element.h"
namespace i18n {
namespace addressinput {
namespace {
bool ParseFieldToken(char c, AddressField* field) {
assert(field != nullptr);
static const struct { char c; AddressField field; } kTokenMap[] = {
{ 'R', COUNTRY },
{ 'S', ADMIN_AREA },
{ 'C', LOCALITY },
{ 'D', DEPENDENT_LOCALITY },
{ 'X', SORTING_CODE },
{ 'Z', POSTAL_CODE },
{ 'A', STREET_ADDRESS },
{ 'O', ORGANIZATION },
{ 'N', RECIPIENT },
};
for (const auto& entry : kTokenMap) {
if (c == entry.c) {
*field = entry.field;
return true;
}
}
return false;
}
}
void ParseFormatRule(const std::string& format,
std::vector<FormatElement>* elements) {
assert(elements != nullptr);
elements->clear();
std::string::const_iterator prev = format.begin();
for (std::string::const_iterator next = format.begin();
next != format.end(); prev = ++next) {
if ((next = std::find(next, format.end(), '%')) == format.end()) {
break;
}
if (prev < next) {
elements->emplace_back(std::string(prev, next));
}
if ((prev = ++next) == format.end()) {
break;
}
AddressField field;
if (*next == 'n') {
elements->emplace_back();
} else if (ParseFieldToken(*next, &field)) {
elements->emplace_back(field);
}
}
if (prev != format.end()) {
elements->emplace_back(std::string(prev, format.end()));
}
}
void ParseAddressFieldsRequired(const std::string& required,
std::vector<AddressField>* fields) {
assert(fields != nullptr);
fields->clear();
for (char c : required) {
AddressField field;
if (ParseFieldToken(c, &field)) {
fields->push_back(field);
}
}
}
}
} | #include "address_field_util.h"
#include <libaddressinput/address_field.h>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "format_element.h"
namespace {
using i18n::addressinput::AddressField;
using i18n::addressinput::FormatElement;
using i18n::addressinput::ParseFormatRule;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::LOCALITY;
using i18n::addressinput::POSTAL_CODE;
using i18n::addressinput::STREET_ADDRESS;
using i18n::addressinput::ORGANIZATION;
using i18n::addressinput::RECIPIENT;
TEST(AddressFieldUtilTest, FormatParseNewline) {
std::vector<FormatElement> actual;
ParseFormatRule("%O%n%N%n%A%nAX-%Z %C%nÅLAND", &actual);
const std::vector<FormatElement> expected{
FormatElement{ORGANIZATION},
FormatElement{},
FormatElement{RECIPIENT},
FormatElement{},
FormatElement{STREET_ADDRESS},
FormatElement{},
FormatElement{"AX-"},
FormatElement{POSTAL_CODE},
FormatElement{" "},
FormatElement{LOCALITY},
FormatElement{},
FormatElement{"ÅLAND"},
};
EXPECT_EQ(expected, actual);
}
TEST(AddressFieldUtilTest, FormatUnknownTokenIsIgnored) {
std::vector<FormatElement> actual;
ParseFormatRule("%1%R", &actual);
const std::vector<FormatElement> expected{FormatElement{COUNTRY}};
EXPECT_EQ(expected, actual);
}
TEST(AddressFieldUtilTest, FormatPrefixWithoutTokenIsIgnored) {
std::vector<FormatElement> actual;
ParseFormatRule("%", &actual);
EXPECT_TRUE(actual.empty());
}
TEST(AddressFieldUtilTest, FormatEmptyString) {
std::vector<FormatElement> fields;
ParseFormatRule(std::string(), &fields);
EXPECT_TRUE(fields.empty());
}
TEST(AddressFieldUtilTest, RequiredParseDefault) {
std::vector<AddressField> actual;
ParseAddressFieldsRequired("AC", &actual);
const std::vector<AddressField> expected{
STREET_ADDRESS,
LOCALITY,
};
EXPECT_EQ(expected, actual);
}
TEST(AddressFieldUtilTest, RequiredEmptyString) {
std::vector<AddressField> fields;
ParseAddressFieldsRequired(std::string(), &fields);
EXPECT_TRUE(fields.empty());
}
} |
494 | cpp | google/libaddressinput | address_normalizer | cpp/src/address_normalizer.cc | cpp/test/address_normalizer_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_NORMALIZER_H_
#define I18N_ADDRESSINPUT_ADDRESS_NORMALIZER_H_
#include <memory>
namespace i18n {
namespace addressinput {
class PreloadSupplier;
class StringCompare;
struct AddressData;
class AddressNormalizer {
public:
AddressNormalizer(const AddressNormalizer&) = delete;
AddressNormalizer& operator=(const AddressNormalizer&) = delete;
explicit AddressNormalizer(const PreloadSupplier* supplier);
~AddressNormalizer();
void Normalize(AddressData* address) const;
private:
const PreloadSupplier* const supplier_;
const std::unique_ptr<const StringCompare> compare_;
};
}
}
#endif
#include <libaddressinput/address_normalizer.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/preload_supplier.h>
#include <cassert>
#include <cstddef>
#include <string>
#include <vector>
#include "lookup_key.h"
#include "rule.h"
#include "util/size.h"
#include "util/string_compare.h"
namespace i18n {
namespace addressinput {
AddressNormalizer::AddressNormalizer(const PreloadSupplier* supplier)
: supplier_(supplier),
compare_(new StringCompare) {
assert(supplier_ != nullptr);
}
AddressNormalizer::~AddressNormalizer() = default;
void AddressNormalizer::Normalize(AddressData* address) const {
assert(address != nullptr);
assert(supplier_->IsLoaded(address->region_code));
AddressData region_address;
region_address.region_code = address->region_code;
LookupKey parent_key;
parent_key.FromAddress(region_address);
const Rule* parent_rule = supplier_->GetRule(parent_key);
assert(parent_rule != nullptr);
std::vector<std::string> languages(parent_rule->GetLanguages());
if (languages.empty()) {
languages.emplace_back("");
} else {
languages[0] = "";
}
LookupKey lookup_key;
for (size_t depth = 1; depth < size(LookupKey::kHierarchy); ++depth) {
AddressField field = LookupKey::kHierarchy[depth];
if (address->IsFieldEmpty(field)) {
return;
}
const std::string& field_value = address->GetFieldValue(field);
bool no_match_found_yet = true;
for (const auto& sub_key : parent_rule->GetSubKeys()) {
if (!no_match_found_yet) {
break;
}
for (const std::string& language_tag : languages) {
lookup_key.set_language(language_tag);
lookup_key.FromLookupKey(parent_key, sub_key);
const Rule* rule = supplier_->GetRule(lookup_key);
if (rule == nullptr) continue;
bool matches_latin_name =
compare_->NaturalEquals(field_value, rule->GetLatinName());
bool matches_local_name_id =
compare_->NaturalEquals(field_value, sub_key) ||
compare_->NaturalEquals(field_value, rule->GetName());
if (matches_latin_name || matches_local_name_id) {
address->SetFieldValue(
field, matches_latin_name ? rule->GetLatinName() : sub_key);
no_match_found_yet = false;
parent_key.FromLookupKey(parent_key, sub_key);
parent_rule = supplier_->GetRule(parent_key);
assert(parent_rule != nullptr);
break;
}
}
}
if (no_match_found_yet) {
return;
}
}
}
}
} | #include <libaddressinput/address_normalizer.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <libaddressinput/preload_supplier.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "testdata_source.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressNormalizer;
using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::PreloadSupplier;
using i18n::addressinput::TestdataSource;
class AddressNormalizerTest : public testing::Test {
public:
AddressNormalizerTest(const AddressNormalizerTest&) = delete;
AddressNormalizerTest& operator=(const AddressNormalizerTest&) = delete;
protected:
AddressNormalizerTest()
: supplier_(new TestdataSource(true), new NullStorage),
loaded_(BuildCallback(this, &AddressNormalizerTest::OnLoaded)),
normalizer_(&supplier_) {}
PreloadSupplier supplier_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_;
const AddressNormalizer normalizer_;
private:
void OnLoaded(bool success, const std::string& region_code, int num_rules) {
ASSERT_TRUE(success);
ASSERT_FALSE(region_code.empty());
ASSERT_LT(0, num_rules);
}
};
TEST_F(AddressNormalizerTest, CountryWithNoLanguageNoAdminArea) {
supplier_.LoadRules("IR", *loaded_);
AddressData address{
.region_code = "IR",
.administrative_area = "Tehran",
};
normalizer_.Normalize(&address);
EXPECT_EQ("Tehran", address.administrative_area);
}
TEST_F(AddressNormalizerTest, BrazilAdminAreaAndLocality) {
supplier_.LoadRules("BR", *loaded_);
AddressData address{
.region_code = "BR",
.administrative_area = "Maranhão",
.locality = "Cantanhede",
};
normalizer_.Normalize(&address);
EXPECT_EQ("MA", address.administrative_area);
EXPECT_EQ("Cantanhede", address.locality);
}
TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotConsistent) {
supplier_.LoadRules("CA", *loaded_);
AddressData address{
.region_code = "CA",
.administrative_area = "Nouveau-Brunswick",
.language_code = "en-CA",
};
normalizer_.Normalize(&address);
EXPECT_EQ("NB", address.administrative_area);
}
TEST_F(AddressNormalizerTest, FrenchCanadaName) {
supplier_.LoadRules("CA", *loaded_);
AddressData address{
.region_code = "CA",
.administrative_area = "Nouveau-Brunswick",
.language_code = "fr-CA",
};
normalizer_.Normalize(&address);
EXPECT_EQ("NB", address.administrative_area);
}
TEST_F(AddressNormalizerTest, FrenchCanadaNameLanguageNotListed) {
supplier_.LoadRules("CA", *loaded_);
AddressData address{
.region_code = "CA",
.administrative_area = "Colombie-Britannique",
.language_code = "fa-CA",
};
normalizer_.Normalize(&address);
EXPECT_EQ("BC", address.administrative_area);
}
TEST_F(AddressNormalizerTest, CaliforniaShortNameCa) {
supplier_.LoadRules("US", *loaded_);
AddressData address{
.region_code = "US",
.administrative_area = "California",
.locality = "Mountain View",
.language_code = "en-US",
};
normalizer_.Normalize(&address);
EXPECT_EQ("CA", address.administrative_area);
}
TEST_F(AddressNormalizerTest, CountryWithNonStandardData) {
supplier_.LoadRules("HK", *loaded_);
AddressData address{
.region_code = "HK",
.administrative_area = "香港島",
};
normalizer_.Normalize(&address);
EXPECT_EQ("香港島", address.administrative_area);
}
TEST_F(AddressNormalizerTest, GangwonLatinNameStaysUnchanged) {
supplier_.LoadRules("KR", *loaded_);
AddressData address{
.region_code = "KR",
.administrative_area = "Gangwon",
.language_code = "ko-Latn",
};
normalizer_.Normalize(&address);
EXPECT_EQ("Gangwon", address.administrative_area);
}
TEST_F(AddressNormalizerTest, GangwonKoreanName) {
supplier_.LoadRules("KR", *loaded_);
AddressData address{
.region_code = "KR",
.administrative_area = "강원",
.language_code = "ko-KR",
};
normalizer_.Normalize(&address);
EXPECT_EQ("강원도", address.administrative_area);
}
TEST_F(AddressNormalizerTest, DontSwitchLatinScriptForUnknownLanguage) {
supplier_.LoadRules("KR", *loaded_);
AddressData address{
.region_code = "KR",
.administrative_area = "Gangwon",
};
normalizer_.Normalize(&address);
EXPECT_EQ("Gangwon", address.administrative_area);
}
TEST_F(AddressNormalizerTest, DontSwitchLocalScriptForUnknownLanguage) {
supplier_.LoadRules("KR", *loaded_);
AddressData address{
.region_code = "KR",
.administrative_area = "강원",
};
normalizer_.Normalize(&address);
EXPECT_EQ("강원도", address.administrative_area);
}
} |
495 | cpp | google/libaddressinput | address_validator | cpp/src/address_validator.cc | cpp/test/address_validator_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_VALIDATOR_H_
#define I18N_ADDRESSINPUT_ADDRESS_VALIDATOR_H_
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <libaddressinput/callback.h>
#include <map>
namespace i18n {
namespace addressinput {
class Supplier;
struct AddressData;
using FieldProblemMap = std::multimap<AddressField, AddressProblem>;
class AddressValidator {
public:
using Callback =
i18n::addressinput::Callback<const AddressData&, const FieldProblemMap&>;
AddressValidator(const AddressValidator&) = delete;
AddressValidator& operator=(const AddressValidator&) = delete;
AddressValidator(Supplier* supplier);
~AddressValidator() = default;
void Validate(const AddressData& address,
bool allow_postal,
bool require_name,
const FieldProblemMap* filter,
FieldProblemMap* problems,
const Callback& validated) const;
private:
Supplier* const supplier_;
};
}
}
#endif
#include <libaddressinput/address_validator.h>
#include <cassert>
#include <cstddef>
#include "validation_task.h"
namespace i18n {
namespace addressinput {
AddressValidator::AddressValidator(Supplier* supplier) : supplier_(supplier) {
assert(supplier_ != nullptr);
}
void AddressValidator::Validate(const AddressData& address,
bool allow_postal,
bool require_name,
const FieldProblemMap* filter,
FieldProblemMap* problems,
const Callback& validated) const {
(new ValidationTask(
address,
allow_postal,
require_name,
filter,
problems,
validated))->Run(supplier_);
}
}
} | #include <libaddressinput/address_validator.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_problem.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <libaddressinput/ondemand_supplier.h>
#include <libaddressinput/preload_supplier.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "testdata_source.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressValidator;
using i18n::addressinput::BuildCallback;
using i18n::addressinput::FieldProblemMap;
using i18n::addressinput::NullStorage;
using i18n::addressinput::OndemandSupplier;
using i18n::addressinput::PreloadSupplier;
using i18n::addressinput::TestdataSource;
using i18n::addressinput::ADMIN_AREA;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::DEPENDENT_LOCALITY;
using i18n::addressinput::LOCALITY;
using i18n::addressinput::POSTAL_CODE;
using i18n::addressinput::STREET_ADDRESS;
using i18n::addressinput::INVALID_FORMAT;
using i18n::addressinput::MISMATCHING_VALUE;
using i18n::addressinput::MISSING_REQUIRED_FIELD;
using i18n::addressinput::UNEXPECTED_FIELD;
using i18n::addressinput::UNKNOWN_VALUE;
using i18n::addressinput::UNSUPPORTED_FIELD;
class ValidatorWrapper {
public:
virtual ~ValidatorWrapper() = default;
virtual void Validate(const AddressData& address, bool allow_postal,
bool require_name, const FieldProblemMap* filter,
FieldProblemMap* problems,
const AddressValidator::Callback& validated) = 0;
};
class OndemandValidatorWrapper : public ValidatorWrapper {
public:
OndemandValidatorWrapper(const OndemandValidatorWrapper&) = delete;
OndemandValidatorWrapper& operator=(const OndemandValidatorWrapper&) = delete;
static ValidatorWrapper* Build() { return new OndemandValidatorWrapper; }
void Validate(const AddressData& address, bool allow_postal,
bool require_name, const FieldProblemMap* filter,
FieldProblemMap* problems,
const AddressValidator::Callback& validated) override {
validator_.Validate(address, allow_postal, require_name, filter, problems,
validated);
}
private:
OndemandValidatorWrapper()
: supplier_(new TestdataSource(false), new NullStorage),
validator_(&supplier_) {}
OndemandSupplier supplier_;
const AddressValidator validator_;
};
class PreloadValidatorWrapper : public ValidatorWrapper {
public:
PreloadValidatorWrapper(const PreloadValidatorWrapper&) = delete;
PreloadValidatorWrapper& operator=(const PreloadValidatorWrapper&) = delete;
static ValidatorWrapper* Build() { return new PreloadValidatorWrapper; }
void Validate(const AddressData& address, bool allow_postal,
bool require_name, const FieldProblemMap* filter,
FieldProblemMap* problems,
const AddressValidator::Callback& validated) override {
const std::string& region_code = address.region_code;
if (!region_code.empty() && !supplier_.IsLoaded(region_code)) {
supplier_.LoadRules(region_code, *loaded_);
}
validator_.Validate(address, allow_postal, require_name, filter, problems,
validated);
}
private:
PreloadValidatorWrapper()
: supplier_(new TestdataSource(true), new NullStorage),
validator_(&supplier_),
loaded_(BuildCallback(this, &PreloadValidatorWrapper::Loaded)) {}
void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); }
PreloadSupplier supplier_;
const AddressValidator validator_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_;
};
class AddressValidatorTest
: public testing::TestWithParam<ValidatorWrapper* (*)()> {
public:
AddressValidatorTest(const AddressValidatorTest&) = delete;
AddressValidatorTest& operator=(const AddressValidatorTest&) = delete;
protected:
AddressValidatorTest()
: address_(),
allow_postal_(false),
require_name_(false),
filter_(),
problems_(),
expected_(),
called_(false),
validator_wrapper_((*GetParam())()),
validated_(BuildCallback(this, &AddressValidatorTest::Validated)) {}
void Validate() {
validator_wrapper_->Validate(address_, allow_postal_, require_name_,
&filter_, &problems_, *validated_);
}
AddressData address_;
bool allow_postal_;
bool require_name_;
FieldProblemMap filter_;
FieldProblemMap problems_;
FieldProblemMap expected_;
bool called_;
private:
void Validated(bool success, const AddressData& address,
const FieldProblemMap& problems) {
ASSERT_TRUE(success);
ASSERT_EQ(&address_, &address);
ASSERT_EQ(&problems_, &problems);
called_ = true;
}
const std::unique_ptr<ValidatorWrapper> validator_wrapper_;
const std::unique_ptr<const AddressValidator::Callback> validated_;
};
INSTANTIATE_TEST_SUITE_P(OndemandSupplier, AddressValidatorTest,
testing::Values(&OndemandValidatorWrapper::Build));
INSTANTIATE_TEST_SUITE_P(PreloadSupplier, AddressValidatorTest,
testing::Values(&PreloadValidatorWrapper::Build));
TEST_P(AddressValidatorTest, EmptyAddress) {
expected_ = {{COUNTRY, MISSING_REQUIRED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, InvalidCountry) {
address_ = {.region_code = "QZ"};
expected_ = {{COUNTRY, UNKNOWN_VALUE}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidAddressUS) {
address_ = {
.region_code = "US",
.address_line{"1600 Amphitheatre Parkway"},
.administrative_area = "CA",
.locality = "Mountain View",
.postal_code = "94043",
.language_code = "en",
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_ = {
{LOCALITY, UNSUPPORTED_FIELD},
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
};
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, InvalidAddressUS) {
address_ = {
.region_code = "US",
.postal_code = "123",
};
expected_ = {
{ADMIN_AREA, MISSING_REQUIRED_FIELD},
{LOCALITY, MISSING_REQUIRED_FIELD},
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
{POSTAL_CODE, INVALID_FORMAT},
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD);
expected_.emplace(LOCALITY, UNSUPPORTED_FIELD);
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidAddressCH) {
address_ = {
.region_code = "CH",
.address_line{"Brandschenkestrasse 110"},
.locality = "ZH",
.postal_code = "8002",
.language_code = "de",
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_ = {
{LOCALITY, UNSUPPORTED_FIELD},
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
};
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, InvalidAddressCH) {
address_ = {
.region_code = "CH",
.postal_code = "123",
};
expected_ = {
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
{POSTAL_CODE, INVALID_FORMAT},
{LOCALITY, MISSING_REQUIRED_FIELD},
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_.emplace(LOCALITY, UNSUPPORTED_FIELD);
expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD);
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidPostalCodeMX) {
address_ = {
.region_code = "MX",
.address_line{"Av Gregorio Méndez Magaña 1400"},
.administrative_area = "TAB",
.locality = "Villahermosa",
.postal_code = "86070",
.language_code = "es",
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_ = {
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
{LOCALITY, UNSUPPORTED_FIELD},
};
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, MismatchingPostalCodeMX) {
address_ = {
.region_code = "MX",
.address_line{"Av Gregorio Méndez Magaña 1400"},
.administrative_area = "TAB",
.locality = "Villahermosa",
.postal_code = "80000",
.language_code = "es",
};
expected_ = {{POSTAL_CODE, MISMATCHING_VALUE}};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_.emplace(LOCALITY, UNSUPPORTED_FIELD);
expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD);
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidateFilter) {
address_ = {
.region_code = "CH",
.postal_code = "123",
};
filter_ = {{POSTAL_CODE, INVALID_FORMAT}};
expected_ = {{POSTAL_CODE, INVALID_FORMAT}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidateClearsProblems) {
address_ = {
.region_code = "CH",
.address_line{"Brandschenkestrasse 110"},
.locality = "ZH",
.postal_code = "123",
.language_code = "de",
};
problems_ = {
{LOCALITY, UNEXPECTED_FIELD},
{LOCALITY, MISSING_REQUIRED_FIELD},
{STREET_ADDRESS, MISSING_REQUIRED_FIELD},
};
expected_ = {{POSTAL_CODE, INVALID_FORMAT}};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_.emplace(LOCALITY, UNSUPPORTED_FIELD);
expected_.emplace(DEPENDENT_LOCALITY, UNSUPPORTED_FIELD);
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidKanjiAddressJP) {
address_ = {
.region_code = "JP",
.address_line{"徳島市..."},
.administrative_area = "徳島県",
.postal_code = "770-0847",
.language_code = "ja",
};
if (GetParam() == &PreloadValidatorWrapper::Build) {
expected_ = {
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
{LOCALITY, UNSUPPORTED_FIELD},
};
}
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidLatinAddressJP) {
if (GetParam() == &OndemandValidatorWrapper::Build) return;
address_ = {
.region_code = "JP",
.address_line{"...Tokushima"},
.administrative_area = "Tokushima",
.postal_code = "770-0847",
.language_code = "ja-Latn",
};
expected_ = {
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
{LOCALITY, UNSUPPORTED_FIELD},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidAddressBR) {
if (GetParam() == &OndemandValidatorWrapper::Build) return;
address_ = {
.region_code = "BR",
.address_line{"Rodovia Raposo Tavares, 6388-6682"},
.administrative_area = "São Paulo",
.locality = "Presidente Prudente",
.postal_code = "19063-008",
.language_code = "pt",
};
expected_ = {{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD}};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidAddressCA_en) {
if (GetParam() == &OndemandValidatorWrapper::Build) return;
address_ = {
.region_code = "CA",
.address_line{"..."},
.administrative_area = "New Brunswick",
.locality = "Saint John County",
.postal_code = "E2L 4Z6",
.language_code = "en",
};
expected_ = {
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
{LOCALITY, UNSUPPORTED_FIELD},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
TEST_P(AddressValidatorTest, ValidAddressCA_fr) {
if (GetParam() == &OndemandValidatorWrapper::Build) return;
address_ = {
.region_code = "CA",
.address_line{"..."},
.administrative_area = "Nouveau-Brunswick",
.locality = "Comté de Saint-Jean",
.postal_code = "E2L 4Z6",
.language_code = "fr",
};
expected_ = {
{DEPENDENT_LOCALITY, UNSUPPORTED_FIELD},
{LOCALITY, UNSUPPORTED_FIELD},
};
ASSERT_NO_FATAL_FAILURE(Validate());
ASSERT_TRUE(called_);
EXPECT_EQ(expected_, problems_);
}
} |
496 | cpp | google/libaddressinput | lookup_key | cpp/src/lookup_key.cc | cpp/test/lookup_key_test.cc | #ifndef I18N_ADDRESSINPUT_LOOKUP_KEY_H_
#define I18N_ADDRESSINPUT_LOOKUP_KEY_H_
#include <libaddressinput/address_field.h>
#include <cstddef>
#include <map>
#include <string>
#include "util/size.h"
namespace i18n {
namespace addressinput {
struct AddressData;
class LookupKey {
public:
static const AddressField kHierarchy[4];
LookupKey(const LookupKey&) = delete;
LookupKey& operator=(const LookupKey&) = delete;
LookupKey();
~LookupKey();
void FromAddress(const AddressData& address);
void FromLookupKey(const LookupKey& parent, const std::string& child_node);
std::string ToKeyString(size_t max_depth) const;
const std::string& GetRegionCode() const;
size_t GetDepth() const;
void set_language(const std::string& language) { language_ = language; }
private:
std::map<AddressField, std::string> nodes_;
std::string language_;
};
}
}
#endif
#include "lookup_key.h"
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <functional>
#include <string>
#include "language.h"
#include "region_data_constants.h"
#include "rule.h"
#include "util/cctype_tolower_equal.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
namespace {
const char kSlashDelim[] = "/";
const char kDashDelim[] = "--";
const char kData[] = "data";
const char kUnknown[] = "ZZ";
bool ShouldSetLanguageForKey(const std::string& language_tag,
const std::string& region_code) {
if (RegionDataConstants::GetMaxLookupKeyDepth(region_code) == 0) {
return false;
}
Rule rule;
rule.CopyFrom(Rule::GetDefault());
if (!rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(region_code))) {
return false;
}
const auto& languages = rule.GetLanguages();
if (languages.empty() || languages[0] == language_tag) {
return false;
}
using std::placeholders::_1;
return std::find_if(languages.begin() + 1, languages.end(),
std::bind(&EqualToTolowerString, _1, language_tag)) !=
languages.end();
}
}
const AddressField LookupKey::kHierarchy[] = {
COUNTRY,
ADMIN_AREA,
LOCALITY,
DEPENDENT_LOCALITY,
};
LookupKey::LookupKey() = default;
LookupKey::~LookupKey() = default;
void LookupKey::FromAddress(const AddressData& address) {
nodes_.clear();
if (address.region_code.empty()) {
nodes_.emplace(COUNTRY, kUnknown);
} else {
for (AddressField field : kHierarchy) {
if (address.IsFieldEmpty(field)) {
break;
}
const std::string& value = address.GetFieldValue(field);
if (value.find('/') != std::string::npos) {
break;
}
nodes_.emplace(field, value);
}
}
Language address_language(address.language_code);
std::string language_tag_no_latn = address_language.has_latin_script
? address_language.base
: address_language.tag;
if (ShouldSetLanguageForKey(language_tag_no_latn, address.region_code)) {
language_ = language_tag_no_latn;
}
}
void LookupKey::FromLookupKey(const LookupKey& parent,
const std::string& child_node) {
assert(parent.nodes_.size() < size(kHierarchy));
assert(!child_node.empty());
if (this != &parent) nodes_ = parent.nodes_;
AddressField child_field = kHierarchy[nodes_.size()];
nodes_.emplace(child_field, child_node);
}
std::string LookupKey::ToKeyString(size_t max_depth) const {
assert(max_depth < size(kHierarchy));
std::string key_string(kData);
for (size_t i = 0; i <= max_depth; ++i) {
AddressField field = kHierarchy[i];
auto it = nodes_.find(field);
if (it == nodes_.end()) {
break;
}
key_string.append(kSlashDelim);
key_string.append(it->second);
}
if (!language_.empty()) {
key_string.append(kDashDelim);
key_string.append(language_);
}
return key_string;
}
const std::string& LookupKey::GetRegionCode() const {
auto it = nodes_.find(COUNTRY);
assert(it != nodes_.end());
return it->second;
}
size_t LookupKey::GetDepth() const {
size_t depth = nodes_.size() - 1;
assert(depth < size(kHierarchy));
return depth;
}
}
} | #include "lookup_key.h"
#include <libaddressinput/address_data.h>
#include <cstddef>
#include <gtest/gtest.h>
#include "util/size.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::LookupKey;
const size_t kMaxDepth = size(LookupKey::kHierarchy) - 1;
TEST(LookupKeyTest, Empty) {
const AddressData address;
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/ZZ", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepth1) {
const AddressData address{.region_code = "111"};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(0, lookup_key.GetDepth());
EXPECT_EQ("data/111", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepth2) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(1, lookup_key.GetDepth());
EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepth3) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
.locality = "333",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(2, lookup_key.GetDepth());
EXPECT_EQ("data/111/222/333", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepth4) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
.locality = "333",
.dependent_locality = "444",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(3, lookup_key.GetDepth());
EXPECT_EQ("data/111/222/333/444", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepthNonContiguous) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
.dependent_locality = "444",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(1, lookup_key.GetDepth());
EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, AddressDepthTerminateOnSlash) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
.locality = "3/3",
.dependent_locality = "444",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(1, lookup_key.GetDepth());
EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth));
}
TEST(LookupKeyTest, RequestDepth) {
const AddressData address{
.region_code = "111",
.administrative_area = "222",
.locality = "333",
.dependent_locality = "444",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/111", lookup_key.ToKeyString(0));
EXPECT_EQ("data/111/222", lookup_key.ToKeyString(1));
EXPECT_EQ("data/111/222/333", lookup_key.ToKeyString(2));
EXPECT_EQ("data/111/222/333/444", lookup_key.ToKeyString(3));
}
TEST(LookupKeyTest, WithLanguageCodeDefaultLanguage) {
const AddressData address{
.region_code = "CA",
.administrative_area = "ON",
.language_code = "en",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/CA", lookup_key.ToKeyString(0));
EXPECT_EQ("data/CA/ON", lookup_key.ToKeyString(1));
}
TEST(LookupKeyTest, WithLanguageCodeAlternateLanguage) {
const AddressData address{
.region_code = "CA",
.administrative_area = "ON",
.language_code = "fr",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/CA--fr", lookup_key.ToKeyString(0));
EXPECT_EQ("data/CA/ON--fr", lookup_key.ToKeyString(1));
}
TEST(LookupKeyTest, WithLanguageCodeInvalidLanguage) {
const AddressData address{
.region_code = "CA",
.administrative_area = "ON",
.language_code = "de",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/CA", lookup_key.ToKeyString(0));
EXPECT_EQ("data/CA/ON", lookup_key.ToKeyString(1));
}
TEST(LookupKeyTest, WithLanguageCodeAlternateLanguageNoState) {
const AddressData address{
.region_code = "AF",
.language_code = "ps",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/AF", lookup_key.ToKeyString(0));
}
TEST(LookupKeyTest, GetRegionCode) {
const AddressData address{.region_code = "rrr"};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ(address.region_code, lookup_key.GetRegionCode());
}
TEST(LookupKeyTest, FromAddressClearsExistingNodes) {
AddressData address{
.region_code = "111",
.administrative_area = "222",
};
LookupKey lookup_key;
lookup_key.FromAddress(address);
EXPECT_EQ("data/111/222", lookup_key.ToKeyString(kMaxDepth));
address.administrative_area.clear();
lookup_key.FromAddress(address);
EXPECT_EQ("data/111", lookup_key.ToKeyString(kMaxDepth));
}
} |
497 | cpp | google/libaddressinput | address_input_helper | cpp/src/address_input_helper.cc | cpp/test/address_input_helper_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_INPUT_HELPER_H_
#define I18N_ADDRESSINPUT_ADDRESS_INPUT_HELPER_H_
#include <vector>
namespace i18n {
namespace addressinput {
class LookupKey;
class PreloadSupplier;
struct AddressData;
struct Node;
class AddressInputHelper {
public:
AddressInputHelper(const AddressInputHelper&) = delete;
AddressInputHelper& operator=(const AddressInputHelper&) = delete;
AddressInputHelper(PreloadSupplier* supplier);
~AddressInputHelper() = default;
void FillAddress(AddressData* address) const;
private:
void CheckChildrenForPostCodeMatches(
const AddressData& address, const LookupKey& lookup_key,
const Node* parent, std::vector<Node>* hierarchy) const;
PreloadSupplier* const supplier_;
};
}
}
#endif
#include <libaddressinput/address_input_helper.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_metadata.h>
#include <libaddressinput/preload_supplier.h>
#include <cassert>
#include <cstddef>
#include <string>
#include <vector>
#include <re2/re2.h>
#include "language.h"
#include "lookup_key.h"
#include "region_data_constants.h"
#include "rule.h"
#include "util/re2ptr.h"
#include "util/size.h"
namespace i18n {
namespace addressinput {
struct Node {
const Node* parent;
const Rule* rule;
};
namespace {
const char kLookupKeySeparator = '/';
const size_t kHierarchyDepth = size(LookupKey::kHierarchy);
std::string GetBestName(const Language& language, const Rule& rule) {
if (language.has_latin_script) {
const std::string& name = rule.GetLatinName();
if (!name.empty()) {
return name;
}
}
const std::string& id = rule.GetId();
std::string::size_type pos = id.rfind(kLookupKeySeparator);
assert(pos != std::string::npos);
return id.substr(pos + 1);
}
void FillAddressFromMatchedRules(
const std::vector<Node>* hierarchy,
AddressData* address) {
assert(hierarchy != nullptr);
assert(address != nullptr);
Language language(address->language_code);
for (size_t depth = kHierarchyDepth - 1; depth > 0; --depth) {
if (hierarchy[depth].size() == 1) {
for (const Node* node = &hierarchy[depth].front();
node != nullptr; node = node->parent, --depth) {
const Rule* rule = node->rule;
assert(rule != nullptr);
AddressField field = LookupKey::kHierarchy[depth];
if (address->IsFieldEmpty(field)) {
address->SetFieldValue(field, GetBestName(language, *rule));
}
}
break;
}
}
}
}
AddressInputHelper::AddressInputHelper(PreloadSupplier* supplier)
: supplier_(supplier) {
assert(supplier_ != nullptr);
}
void AddressInputHelper::FillAddress(AddressData* address) const {
assert(address != nullptr);
const std::string& region_code = address->region_code;
if (!RegionDataConstants::IsSupported(region_code)) {
return;
}
AddressData lookup_key_address;
lookup_key_address.region_code = region_code;
LookupKey lookup_key;
lookup_key.FromAddress(lookup_key_address);
const Rule* region_rule = supplier_->GetRule(lookup_key);
assert(region_rule != nullptr);
const RE2ptr* postal_code_reg_exp = region_rule->GetPostalCodeMatcher();
if (postal_code_reg_exp != nullptr) {
if (address->postal_code.empty()) {
address->postal_code = region_rule->GetSolePostalCode();
}
if (!address->postal_code.empty() &&
RE2::FullMatch(address->postal_code, *postal_code_reg_exp->ptr)) {
std::vector<Node> hierarchy[kHierarchyDepth];
CheckChildrenForPostCodeMatches(*address, lookup_key, nullptr, hierarchy);
FillAddressFromMatchedRules(hierarchy, address);
}
}
}
void AddressInputHelper::CheckChildrenForPostCodeMatches(
const AddressData& address,
const LookupKey& lookup_key,
const Node* parent,
std::vector<Node>* hierarchy) const {
const Rule* rule = supplier_->GetRule(lookup_key);
assert(rule != nullptr);
const RE2ptr* postal_code_prefix = rule->GetPostalCodeMatcher();
if (postal_code_prefix == nullptr ||
RE2::PartialMatch(address.postal_code, *postal_code_prefix->ptr)) {
size_t depth = lookup_key.GetDepth();
assert(depth < size(LookupKey::kHierarchy));
hierarchy[depth].emplace_back();
Node* node = &hierarchy[depth].back();
node->parent = parent;
node->rule = rule;
if (depth < size(LookupKey::kHierarchy) - 1 &&
IsFieldUsed(LookupKey::kHierarchy[depth + 1], address.region_code)) {
for (const auto& sub_key : rule->GetSubKeys()) {
LookupKey child_key;
child_key.FromLookupKey(lookup_key, sub_key);
CheckChildrenForPostCodeMatches(address, child_key, node, hierarchy);
}
}
}
}
}
} | #include <libaddressinput/address_input_helper.h>
#include <libaddressinput/address_data.h>
#include <libaddressinput/callback.h>
#include <libaddressinput/null_storage.h>
#include <libaddressinput/preload_supplier.h>
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include "mock_source.h"
#include "testdata_source.h"
namespace {
using i18n::addressinput::AddressData;
using i18n::addressinput::AddressInputHelper;
using i18n::addressinput::BuildCallback;
using i18n::addressinput::MockSource;
using i18n::addressinput::NullStorage;
using i18n::addressinput::PreloadSupplier;
using i18n::addressinput::TestdataSource;
class AddressInputHelperTest : public testing::Test {
public:
AddressInputHelperTest(const AddressInputHelperTest&) = delete;
AddressInputHelperTest& operator=(const AddressInputHelperTest&) = delete;
protected:
AddressInputHelperTest()
: supplier_(new TestdataSource(true), new NullStorage),
address_input_helper_(&supplier_),
loaded_(BuildCallback(this, &AddressInputHelperTest::Loaded)) {}
void FillAddress(AddressData* address) {
const std::string& region_code = address->region_code;
if (!region_code.empty()) {
supplier_.LoadRules(region_code, *loaded_);
}
address_input_helper_.FillAddress(address);
}
private:
void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); }
PreloadSupplier supplier_;
const AddressInputHelper address_input_helper_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_;
};
TEST_F(AddressInputHelperTest, AddressWithMissingPostalCode) {
AddressData address{
.region_code = "CX",
.administrative_area = "WA",
};
AddressData expected = address;
expected.postal_code = "6798";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingAdmin) {
AddressData address{
.region_code = "US",
.address_line{"10 High St"},
.postal_code = "58098",
};
AddressData expected = address;
expected.administrative_area = "ND";
FillAddress(&address);
EXPECT_EQ(expected, address);
address.administrative_area = "CA";
expected.administrative_area = "CA";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingLowerLevel) {
AddressData address{
.region_code = "TW",
.postal_code = "53012",
};
AddressData expected = address;
expected.administrative_area = "彰化縣";
expected.locality = "二水鄉";
FillAddress(&address);
EXPECT_EQ(expected, address);
address.administrative_area = "Already filled in";
expected.administrative_area = "Already filled in";
address.locality = "";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingLowerLevelLatin) {
AddressData address{
.region_code = "TW",
.postal_code = "53012",
.language_code = "zh-Latn",
};
AddressData expected = address;
expected.locality = "Ershuei Township";
expected.administrative_area = "Changhua County";
FillAddress(&address);
EXPECT_EQ(expected, address);
address.administrative_area = "Already filled in";
expected.administrative_area = "Already filled in";
address.locality = "";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingDependentLocality) {
AddressData address{
.region_code = "KR",
.postal_code = "425-111",
};
AddressData expected = address;
expected.administrative_area = "경기도";
expected.locality = "안산시";
expected.dependent_locality = "단원구";
FillAddress(&address);
EXPECT_EQ(expected, address);
AddressData address_ko_latn{
.region_code = "KR",
.postal_code = "425-111",
.language_code = "ko-Latn",
};
expected = address_ko_latn;
expected.administrative_area = "Gyeonggi";
expected.locality = "Ansan-si";
expected.dependent_locality = "Danwon-gu";
FillAddress(&address_ko_latn);
EXPECT_EQ(expected, address_ko_latn);
}
TEST_F(AddressInputHelperTest, AddressWithPostalCodeMatchingMultipleValues) {
AddressData address{
.region_code = "KR",
.postal_code = "527-111",
};
AddressData expected = address;
expected.administrative_area = "전라남도";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithInvalidPostalCode) {
AddressData address{
.region_code = "US",
.postal_code = "970",
};
AddressData expected = address;
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithNoPostalCodeValidation) {
AddressData address{
.region_code = "GA",
.postal_code = "123",
};
AddressData expected = address;
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, AddressWithInvalidOrMissingRegionCode) {
AddressData address{
.administrative_area = "YYY",
.postal_code = "XXX",
};
AddressData expected = address;
FillAddress(&address);
EXPECT_EQ(expected, address);
address.region_code = "XXXX";
expected.region_code = "XXXX";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperTest, RegionWithUnusedAdminAreaNames) {
AddressData address{
.region_code = "CH",
.postal_code = "1111",
.language_code = "de-CH",
};
AddressData expected = address;
FillAddress(&address);
EXPECT_EQ(expected, address);
}
class AddressInputHelperMockDataTest : public testing::Test {
public:
AddressInputHelperMockDataTest(
const AddressInputHelperMockDataTest&) = delete;
AddressInputHelperMockDataTest& operator=(
const AddressInputHelperMockDataTest&) = delete;
protected:
AddressInputHelperMockDataTest()
: source_(new MockSource),
supplier_(source_, new NullStorage),
address_input_helper_(&supplier_),
loaded_(BuildCallback(this, &AddressInputHelperMockDataTest::Loaded)) {}
void FillAddress(AddressData* address) {
const std::string& region_code = address->region_code;
if (!region_code.empty()) {
supplier_.LoadRules(region_code, *loaded_);
}
address_input_helper_.FillAddress(address);
}
MockSource* const source_;
private:
void Loaded(bool success, const std::string&, int) { ASSERT_TRUE(success); }
PreloadSupplier supplier_;
const AddressInputHelper address_input_helper_;
const std::unique_ptr<const PreloadSupplier::Callback> loaded_;
};
TEST_F(AddressInputHelperMockDataTest,
PostalCodeSharedAcrossDifferentHierarchies) {
source_->data_ = {
{
"data/KR",
R"({"data/KR": )"
R"({"id":"data/KR", "sub_keys":"A~B", "zip":"\\d{5}"}, )"
R"("data/KR/A": )"
R"({"id":"data/KR/A", "sub_keys":"A1"}, )"
R"("data/KR/A/A1": )"
R"({"id":"data/KR/A/A1", "zip":"1"}, )"
R"("data/KR/B": )"
R"({"id":"data/KR/B", "sub_keys":"B1"}, )"
R"("data/KR/B/B1": )"
R"({"id":"data/KR/B/B1", "zip":"12"}})"}};
AddressData address{
.region_code = "KR",
.administrative_area = "",
.postal_code = "12345",
};
AddressData expected = address;
FillAddress(&address);
EXPECT_EQ(expected, address);
}
TEST_F(AddressInputHelperMockDataTest,
PostalCodeSharedAcrossDifferentHierarchiesSameState) {
source_->data_ = {
{
"data/KR",
R"({"data/KR": )"
R"({"id":"data/KR", "sub_keys":"A~B", "zip":"\\d{5}"}, )"
R"("data/KR/A": )"
R"({"id":"data/KR/A", "sub_keys":"A1~A2"}, )"
R"("data/KR/A/A1": )"
R"({"id":"data/KR/A/A1", "sub_keys":"A1a", "zip":"1"}, )"
R"("data/KR/A/A1/A1a": )"
R"({"id":"data/KR/A/A1/A1a", "zip":"12"}, )"
R"("data/KR/A/A2": )"
R"({"id":"data/KR/A/A2", "sub_keys":"A2a", "zip":"1"}, )"
R"("data/KR/A/A2/A2a": )"
R"({"id":"data/KR/A/A2/A2a", "zip":"123"}, )"
R"("data/KR/B": )"
R"({"id":"data/KR/B", "zip":"2"}})"}};
AddressData address{
.region_code = "KR",
.administrative_area = "",
.postal_code = "12345",
};
AddressData expected = address;
expected.administrative_area = "A";
FillAddress(&address);
EXPECT_EQ(expected, address);
}
} |
498 | cpp | google/libaddressinput | address_metadata | cpp/src/address_metadata.cc | cpp/test/address_metadata_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_METADATA_H_
#define I18N_ADDRESSINPUT_ADDRESS_METADATA_H_
#include <libaddressinput/address_field.h>
#include <string>
namespace i18n {
namespace addressinput {
bool IsFieldRequired(AddressField field, const std::string& region_code);
bool IsFieldUsed(AddressField field, const std::string& region_code);
}
}
#endif
#include <libaddressinput/address_metadata.h>
#include <libaddressinput/address_field.h>
#include <algorithm>
#include <string>
#include "format_element.h"
#include "region_data_constants.h"
#include "rule.h"
namespace i18n {
namespace addressinput {
bool IsFieldRequired(AddressField field, const std::string& region_code) {
if (field == COUNTRY) {
return true;
}
Rule rule;
rule.CopyFrom(Rule::GetDefault());
if (!rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(region_code))) {
return false;
}
return std::find(rule.GetRequired().begin(),
rule.GetRequired().end(),
field) != rule.GetRequired().end();
}
bool IsFieldUsed(AddressField field, const std::string& region_code) {
if (field == COUNTRY) {
return true;
}
Rule rule;
rule.CopyFrom(Rule::GetDefault());
if (!rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(region_code))) {
return false;
}
return std::find(rule.GetFormat().begin(),
rule.GetFormat().end(),
FormatElement(field)) != rule.GetFormat().end();
}
}
} | #include <libaddressinput/address_metadata.h>
#include <libaddressinput/address_field.h>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::IsFieldRequired;
using i18n::addressinput::IsFieldUsed;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::ADMIN_AREA;
using i18n::addressinput::DEPENDENT_LOCALITY;
TEST(AddressMetadataTest, IsFieldRequiredCountry) {
EXPECT_TRUE(IsFieldRequired(COUNTRY, "US"));
EXPECT_TRUE(IsFieldRequired(COUNTRY, "CH"));
EXPECT_TRUE(IsFieldRequired(COUNTRY, "rrr"));
}
TEST(AddressMetadataTest, IsUsedRequiredCountry) {
EXPECT_TRUE(IsFieldUsed(COUNTRY, "US"));
EXPECT_TRUE(IsFieldUsed(COUNTRY, "CH"));
EXPECT_TRUE(IsFieldUsed(COUNTRY, "rrr"));
}
TEST(AddressMetadataTest, IsFieldRequiredAdminAreaUS) {
EXPECT_TRUE(IsFieldRequired(ADMIN_AREA, "US"));
}
TEST(AddressMetadataTest, IsFieldRequiredAdminAreaAT) {
EXPECT_FALSE(IsFieldRequired(ADMIN_AREA, "AT"));
}
TEST(AddressMetadataTest, IsFieldRequiredAdminAreaSU) {
EXPECT_FALSE(IsFieldRequired(ADMIN_AREA, "SU"));
}
TEST(AddressMetadataTest, IsFieldUsedDependentLocalityUS) {
EXPECT_FALSE(IsFieldUsed(DEPENDENT_LOCALITY, "US"));
}
TEST(AddressMetadataTest, IsFieldUsedDependentLocalityCN) {
EXPECT_TRUE(IsFieldUsed(DEPENDENT_LOCALITY, "CN"));
}
TEST(AddressMetadataTest, IsFieldUsedDependentLocalitySU) {
EXPECT_FALSE(IsFieldUsed(DEPENDENT_LOCALITY, "SU"));
}
} |
499 | cpp | google/libaddressinput | address_ui | cpp/src/address_ui.cc | cpp/test/address_ui_test.cc | #ifndef I18N_ADDRESSINPUT_ADDRESS_UI_H_
#define I18N_ADDRESSINPUT_ADDRESS_UI_H_
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
class Localization;
struct AddressUiComponent;
const std::vector<std::string>& GetRegionCodes();
std::vector<AddressUiComponent> BuildComponents(
const std::string& region_code,
const Localization& localization,
const std::string& ui_language_tag,
std::string* best_address_language_tag);
std::vector<AddressUiComponent> BuildComponentsWithLiterals(
const std::string& region_code, const Localization& localization,
const std::string& ui_language_tag, std::string* best_address_language_tag);
}
}
#endif
#include <libaddressinput/address_ui.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_ui_component.h>
#include <libaddressinput/localization.h>
#include <cassert>
#include <cstddef>
#include <set>
#include <string>
#include <vector>
#include "format_element.h"
#include "grit.h"
#include "language.h"
#include "messages.h"
#include "region_data_constants.h"
#include "rule.h"
namespace i18n {
namespace addressinput {
namespace {
std::string GetLabelForField(const Localization& localization,
AddressField field,
int admin_area_name_message_id,
int postal_code_name_message_id,
int locality_name_message_id,
int sublocality_name_message_id) {
int message_id;
switch (field) {
case SORTING_CODE:
return "CEDEX";
case COUNTRY:
message_id = IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL;
break;
case ADMIN_AREA:
message_id = admin_area_name_message_id;
break;
case LOCALITY:
message_id = locality_name_message_id;
break;
case DEPENDENT_LOCALITY:
message_id = sublocality_name_message_id;
break;
case POSTAL_CODE:
message_id = postal_code_name_message_id;
break;
case STREET_ADDRESS:
message_id = IDS_LIBADDRESSINPUT_ADDRESS_LINE_1_LABEL;
break;
case ORGANIZATION:
message_id = IDS_LIBADDRESSINPUT_ORGANIZATION_LABEL;
break;
case RECIPIENT:
message_id = IDS_LIBADDRESSINPUT_RECIPIENT_LABEL;
break;
default:
message_id = INVALID_MESSAGE_ID;
}
return localization.GetString(message_id);
}
std::vector<AddressUiComponent> BuildComponents(
const std::string& region_code, const Localization& localization,
const std::string& ui_language_tag, bool include_literals,
std::string* best_address_language_tag) {
assert(best_address_language_tag != nullptr);
std::vector<AddressUiComponent> result;
Rule rule;
rule.CopyFrom(Rule::GetDefault());
if (!rule.ParseSerializedRule(
RegionDataConstants::GetRegionData(region_code))) {
return result;
}
const Language best_address_language =
ChooseBestAddressLanguage(rule, Language(ui_language_tag));
*best_address_language_tag = best_address_language.tag;
const std::vector<FormatElement>& format =
!rule.GetLatinFormat().empty() && best_address_language.has_latin_script
? rule.GetLatinFormat()
: rule.GetFormat();
std::set<AddressField> fields;
bool preceded_by_newline = true;
bool followed_by_newline = true;
for (auto format_it = format.begin();
format_it != format.end(); ++format_it) {
if (!format_it->IsField()) {
if (include_literals) {
AddressUiComponent component;
component.literal = format_it->GetLiteral();
result.push_back(component);
}
if (format_it->IsNewline()) preceded_by_newline = true;
continue;
} else if (!fields.insert(format_it->GetField()).second) {
continue;
}
AddressUiComponent component;
auto next_format_it = format_it + 1;
followed_by_newline =
next_format_it == format.end() || next_format_it->IsNewline();
component.length_hint = preceded_by_newline && followed_by_newline
? AddressUiComponent::HINT_LONG
: AddressUiComponent::HINT_SHORT;
preceded_by_newline = false;
component.field = format_it->GetField();
component.name = GetLabelForField(localization,
format_it->GetField(),
rule.GetAdminAreaNameMessageId(),
rule.GetPostalCodeNameMessageId(),
rule.GetLocalityNameMessageId(),
rule.GetSublocalityNameMessageId());
result.push_back(component);
}
return result;
}
}
const std::vector<std::string>& GetRegionCodes() {
return RegionDataConstants::GetRegionCodes();
}
std::vector<AddressUiComponent> BuildComponents(
const std::string& region_code, const Localization& localization,
const std::string& ui_language_tag,
std::string* best_address_language_tag) {
return BuildComponents(region_code, localization, ui_language_tag,
false, best_address_language_tag);
}
std::vector<AddressUiComponent> BuildComponentsWithLiterals(
const std::string& region_code, const Localization& localization,
const std::string& ui_language_tag,
std::string* best_address_language_tag) {
return BuildComponents(region_code, localization, ui_language_tag,
true, best_address_language_tag);
}
}
} | #include <libaddressinput/address_ui.h>
#include <libaddressinput/address_field.h>
#include <libaddressinput/address_ui_component.h>
#include <libaddressinput/localization.h>
#include <set>
#include <string>
#include <vector>
#include <gtest/gtest.h>
namespace {
using i18n::addressinput::AddressField;
using i18n::addressinput::AddressUiComponent;
using i18n::addressinput::BuildComponents;
using i18n::addressinput::GetRegionCodes;
using i18n::addressinput::Localization;
using i18n::addressinput::COUNTRY;
using i18n::addressinput::ADMIN_AREA;
using i18n::addressinput::POSTAL_CODE;
using i18n::addressinput::STREET_ADDRESS;
using i18n::addressinput::ORGANIZATION;
using i18n::addressinput::RECIPIENT;
const char kUiLanguageTag[] = "en";
testing::AssertionResult ComponentsAreValid(
const std::vector<AddressUiComponent>& components) {
if (components.empty()) {
return testing::AssertionFailure() << "no components";
}
for (const auto& component : components) {
static const AddressField kMinAddressField = COUNTRY;
static const AddressField kMaxAddressField = RECIPIENT;
if (component.literal.empty()) {
if (component.field < kMinAddressField ||
component.field > kMaxAddressField) {
return testing::AssertionFailure()
<< "unexpected field " << component.field;
}
if (component.name.empty()) {
return testing::AssertionFailure()
<< "empty field name for field " << component.field;
}
} else {
if (!component.name.empty()) {
return testing::AssertionFailure() << "literals don't have names";
}
}
}
return testing::AssertionSuccess();
}
class AddressUiTest : public testing::TestWithParam<std::string> {
public:
AddressUiTest(const AddressUiTest&) = delete;
AddressUiTest& operator=(const AddressUiTest&) = delete;
protected:
AddressUiTest() = default;
Localization localization_;
std::string best_address_language_tag_;
};
TEST_P(AddressUiTest, RegionCodeHasTwoCharacters) {
EXPECT_EQ(2, GetParam().size());
}
TEST_P(AddressUiTest, ComponentsAreValid) {
EXPECT_TRUE(ComponentsAreValid(BuildComponents(
GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_)));
}
TEST_P(AddressUiTest, ComponentsWithLiteralsAreValid) {
EXPECT_TRUE(ComponentsAreValid(BuildComponentsWithLiterals(
GetParam(), localization_, kUiLanguageTag, &best_address_language_tag_)));
}
TEST_P(AddressUiTest, UniqueFieldTypes) {
std::set<AddressField> fields;
const std::vector<AddressUiComponent>& components =
BuildComponents(GetParam(), localization_, kUiLanguageTag,
&best_address_language_tag_);
for (const auto& component : components) {
EXPECT_TRUE(fields.insert(component.field).second);
}
}
TEST_P(AddressUiTest, UniqueFieldTypesByBuildComponentsWithLiterals) {
std::set<AddressField> fields;
const std::vector<AddressUiComponent>& components =
BuildComponentsWithLiterals(GetParam(), localization_, kUiLanguageTag,
&best_address_language_tag_);
for (const auto& component : components) {
if (component.literal.empty()) {
EXPECT_TRUE(fields.insert(component.field).second);
}
}
}
INSTANTIATE_TEST_SUITE_P(AllRegions, AddressUiTest,
testing::ValuesIn(GetRegionCodes()));
TEST_F(AddressUiTest, InvalidRegionCodeReturnsEmptyVector) {
EXPECT_TRUE(BuildComponents(
"INVALID-REGION-CODE", localization_, kUiLanguageTag,
&best_address_language_tag_).empty());
}
TEST_F(AddressUiTest, ComponentsWithLiteralsReadsLiteralsForLV) {
const std::vector<AddressUiComponent>& components =
BuildComponentsWithLiterals("LV", localization_, kUiLanguageTag,
&best_address_language_tag_);
std::string literal;
int newlines_count = 0;
for (const auto& component : components) {
if (!component.literal.empty()) {
if (component.literal == "\n") {
newlines_count++;
continue;
}
EXPECT_TRUE(literal.empty());
literal = component.literal;
}
}
EXPECT_EQ(", ", literal);
EXPECT_EQ(4, newlines_count);
}
struct LanguageTestCase {
LanguageTestCase(const std::string& region_code,
const std::string& ui_language_tag,
const std::string& expected_best_address_language_tag,
AddressField expected_first_field)
: region_code(region_code),
ui_language_tag(ui_language_tag),
expected_best_address_language_tag(expected_best_address_language_tag),
expected_first_field(expected_first_field) {}
~LanguageTestCase() = default;
const std::string region_code;
const std::string ui_language_tag;
const std::string expected_best_address_language_tag;
const AddressField expected_first_field;
};
class BestAddressLanguageTagTest
: public testing::TestWithParam<LanguageTestCase> {
public:
BestAddressLanguageTagTest(const BestAddressLanguageTagTest&) = delete;
BestAddressLanguageTagTest& operator=(const BestAddressLanguageTagTest&) =
delete;
protected:
BestAddressLanguageTagTest() = default;
Localization localization_;
std::string best_address_language_tag_;
};
std::string GetterStub(int) { return std::string(); }
TEST_P(BestAddressLanguageTagTest, CorrectBestAddressLanguageTag) {
localization_.SetGetter(&GetterStub);
const std::vector<AddressUiComponent>& components = BuildComponents(
GetParam().region_code, localization_, GetParam().ui_language_tag,
&best_address_language_tag_);
EXPECT_EQ(GetParam().expected_best_address_language_tag,
best_address_language_tag_);
ASSERT_FALSE(components.empty());
EXPECT_EQ(GetParam().expected_first_field, components.front().field);
}
INSTANTIATE_TEST_SUITE_P(
LanguageTestCases, BestAddressLanguageTagTest,
testing::Values(
LanguageTestCase("AM", "", "hy", RECIPIENT),
LanguageTestCase("AM", "hy", "hy", RECIPIENT),
LanguageTestCase("AM", "en", "hy-Latn", RECIPIENT),
LanguageTestCase("CN", "zh-hans", "zh", POSTAL_CODE),
LanguageTestCase("CN", "zh-hant", "zh", POSTAL_CODE),
LanguageTestCase("CN", "zh-hans-CN", "zh", POSTAL_CODE),
LanguageTestCase("CN", "zh", "zh", POSTAL_CODE),
LanguageTestCase("CN", "ZH_HANS", "zh", POSTAL_CODE),
LanguageTestCase("CN", "zh-cmn-Hans-CN", "zh", POSTAL_CODE),
LanguageTestCase("CN", "zh-Latn", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "zh-latn-CN", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "en", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "ja", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "ko", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "ZH_LATN", "zh-Latn", RECIPIENT),
LanguageTestCase("CN", "cmn-Hans-CN", "zh-Latn", RECIPIENT),
LanguageTestCase("HK", "zh", "zh-Hant", ADMIN_AREA),
LanguageTestCase("HK", "zh-hans", "zh-Hant", ADMIN_AREA),
LanguageTestCase("HK", "zh-hant", "zh-Hant", ADMIN_AREA),
LanguageTestCase("HK", "zh-yue-HK", "zh-Hant", ADMIN_AREA),
LanguageTestCase("HK", "en", "en", ADMIN_AREA),
LanguageTestCase("HK", "zh-latn", "zh-Latn", RECIPIENT),
LanguageTestCase("HK", "fr", "zh-Latn", RECIPIENT),
LanguageTestCase("HK", "ja", "zh-Latn", RECIPIENT),
LanguageTestCase("HK", "ko", "zh-Latn", RECIPIENT),
LanguageTestCase("HK", "yue-HK", "zh-Latn", RECIPIENT),
LanguageTestCase("MO", "zh", "zh-Hant", STREET_ADDRESS),
LanguageTestCase("MO", "zh-Hant", "zh-Hant", STREET_ADDRESS),
LanguageTestCase("MO", "pt", "pt", STREET_ADDRESS),
LanguageTestCase("MO", "zh-Latn", "zh-Latn", RECIPIENT),
LanguageTestCase("MO", "en", "zh-Latn", RECIPIENT),
LanguageTestCase("CH", "de", "de", ORGANIZATION),
LanguageTestCase("CH", "de-DE", "de", ORGANIZATION),
LanguageTestCase("CH", "de-Latn-DE", "de", ORGANIZATION),
LanguageTestCase("CH", "fr", "fr", ORGANIZATION),
LanguageTestCase("CH", "it", "it", ORGANIZATION),
LanguageTestCase("CH", "en", "de", ORGANIZATION),
LanguageTestCase("AQ", "en", "en", RECIPIENT),
LanguageTestCase("AQ", "fr", "fr", RECIPIENT),
LanguageTestCase("AQ", "es", "es", RECIPIENT),
LanguageTestCase("AQ", "zh-Hans", "zh-Hans", RECIPIENT),
LanguageTestCase("EG", "ar", "ar", RECIPIENT),
LanguageTestCase("EG", "ar-Arab", "ar", RECIPIENT),
LanguageTestCase("EG", "ar-Latn", "ar-Latn", RECIPIENT),
LanguageTestCase("EG", "fr", "ar-Latn", RECIPIENT),
LanguageTestCase("EG", "fa", "ar-Latn", RECIPIENT),
LanguageTestCase("EG", "fa-Arab", "ar-Latn", RECIPIENT)));
} |